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
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
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 trace_net_dev_start_xmit(skb, dev);
3531 rc = netdev_start_xmit(skb, dev, txq, more);
3532 trace_net_dev_xmit(skb, rc, dev, len);
3537 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3538 struct netdev_queue *txq, int *ret)
3540 struct sk_buff *skb = first;
3541 int rc = NETDEV_TX_OK;
3544 struct sk_buff *next = skb->next;
3546 skb_mark_not_on_list(skb);
3547 rc = xmit_one(skb, dev, txq, next != NULL);
3548 if (unlikely(!dev_xmit_complete(rc))) {
3554 if (netif_tx_queue_stopped(txq) && skb) {
3555 rc = NETDEV_TX_BUSY;
3565 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3566 netdev_features_t features)
3568 if (skb_vlan_tag_present(skb) &&
3569 !vlan_hw_offload_capable(features, skb->vlan_proto))
3570 skb = __vlan_hwaccel_push_inside(skb);
3574 int skb_csum_hwoffload_help(struct sk_buff *skb,
3575 const netdev_features_t features)
3577 if (unlikely(skb_csum_is_sctp(skb)))
3578 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3579 skb_crc32c_csum_help(skb);
3581 if (features & NETIF_F_HW_CSUM)
3584 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3585 switch (skb->csum_offset) {
3586 case offsetof(struct tcphdr, check):
3587 case offsetof(struct udphdr, check):
3592 return skb_checksum_help(skb);
3594 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3596 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3598 netdev_features_t features;
3600 features = netif_skb_features(skb);
3601 skb = validate_xmit_vlan(skb, features);
3605 skb = sk_validate_xmit_skb(skb, dev);
3609 if (netif_needs_gso(skb, features)) {
3610 struct sk_buff *segs;
3612 segs = skb_gso_segment(skb, features);
3620 if (skb_needs_linearize(skb, features) &&
3621 __skb_linearize(skb))
3624 /* If packet is not checksummed and device does not
3625 * support checksumming for this protocol, complete
3626 * checksumming here.
3628 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3629 if (skb->encapsulation)
3630 skb_set_inner_transport_header(skb,
3631 skb_checksum_start_offset(skb));
3633 skb_set_transport_header(skb,
3634 skb_checksum_start_offset(skb));
3635 if (skb_csum_hwoffload_help(skb, features))
3640 skb = validate_xmit_xfrm(skb, features, again);
3647 dev_core_stats_tx_dropped_inc(dev);
3651 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3653 struct sk_buff *next, *head = NULL, *tail;
3655 for (; skb != NULL; skb = next) {
3657 skb_mark_not_on_list(skb);
3659 /* in case skb wont be segmented, point to itself */
3662 skb = validate_xmit_skb(skb, dev, again);
3670 /* If skb was segmented, skb->prev points to
3671 * the last segment. If not, it still contains skb.
3677 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3679 static void qdisc_pkt_len_init(struct sk_buff *skb)
3681 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3683 qdisc_skb_cb(skb)->pkt_len = skb->len;
3685 /* To get more precise estimation of bytes sent on wire,
3686 * we add to pkt_len the headers size of all segments
3688 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3689 unsigned int hdr_len;
3690 u16 gso_segs = shinfo->gso_segs;
3692 /* mac layer + network layer */
3693 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3695 /* + transport layer */
3696 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3697 const struct tcphdr *th;
3698 struct tcphdr _tcphdr;
3700 th = skb_header_pointer(skb, skb_transport_offset(skb),
3701 sizeof(_tcphdr), &_tcphdr);
3703 hdr_len += __tcp_hdrlen(th);
3705 struct udphdr _udphdr;
3707 if (skb_header_pointer(skb, skb_transport_offset(skb),
3708 sizeof(_udphdr), &_udphdr))
3709 hdr_len += sizeof(struct udphdr);
3712 if (shinfo->gso_type & SKB_GSO_DODGY)
3713 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3716 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3720 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3721 struct sk_buff **to_free,
3722 struct netdev_queue *txq)
3726 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3727 if (rc == NET_XMIT_SUCCESS)
3728 trace_qdisc_enqueue(q, txq, skb);
3732 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3733 struct net_device *dev,
3734 struct netdev_queue *txq)
3736 spinlock_t *root_lock = qdisc_lock(q);
3737 struct sk_buff *to_free = NULL;
3741 qdisc_calculate_pkt_len(skb, q);
3743 if (q->flags & TCQ_F_NOLOCK) {
3744 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3745 qdisc_run_begin(q)) {
3746 /* Retest nolock_qdisc_is_empty() within the protection
3747 * of q->seqlock to protect from racing with requeuing.
3749 if (unlikely(!nolock_qdisc_is_empty(q))) {
3750 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3757 qdisc_bstats_cpu_update(q, skb);
3758 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3759 !nolock_qdisc_is_empty(q))
3763 return NET_XMIT_SUCCESS;
3766 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3770 if (unlikely(to_free))
3771 kfree_skb_list_reason(to_free,
3772 SKB_DROP_REASON_QDISC_DROP);
3777 * Heuristic to force contended enqueues to serialize on a
3778 * separate lock before trying to get qdisc main lock.
3779 * This permits qdisc->running owner to get the lock more
3780 * often and dequeue packets faster.
3781 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3782 * and then other tasks will only enqueue packets. The packets will be
3783 * sent after the qdisc owner is scheduled again. To prevent this
3784 * scenario the task always serialize on the lock.
3786 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3787 if (unlikely(contended))
3788 spin_lock(&q->busylock);
3790 spin_lock(root_lock);
3791 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3792 __qdisc_drop(skb, &to_free);
3794 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3795 qdisc_run_begin(q)) {
3797 * This is a work-conserving queue; there are no old skbs
3798 * waiting to be sent out; and the qdisc is not running -
3799 * xmit the skb directly.
3802 qdisc_bstats_update(q, skb);
3804 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3805 if (unlikely(contended)) {
3806 spin_unlock(&q->busylock);
3813 rc = NET_XMIT_SUCCESS;
3815 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3816 if (qdisc_run_begin(q)) {
3817 if (unlikely(contended)) {
3818 spin_unlock(&q->busylock);
3825 spin_unlock(root_lock);
3826 if (unlikely(to_free))
3827 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP);
3828 if (unlikely(contended))
3829 spin_unlock(&q->busylock);
3833 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3834 static void skb_update_prio(struct sk_buff *skb)
3836 const struct netprio_map *map;
3837 const struct sock *sk;
3838 unsigned int prioidx;
3842 map = rcu_dereference_bh(skb->dev->priomap);
3845 sk = skb_to_full_sk(skb);
3849 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3851 if (prioidx < map->priomap_len)
3852 skb->priority = map->priomap[prioidx];
3855 #define skb_update_prio(skb)
3859 * dev_loopback_xmit - loop back @skb
3860 * @net: network namespace this loopback is happening in
3861 * @sk: sk needed to be a netfilter okfn
3862 * @skb: buffer to transmit
3864 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3866 skb_reset_mac_header(skb);
3867 __skb_pull(skb, skb_network_offset(skb));
3868 skb->pkt_type = PACKET_LOOPBACK;
3869 if (skb->ip_summed == CHECKSUM_NONE)
3870 skb->ip_summed = CHECKSUM_UNNECESSARY;
3871 WARN_ON(!skb_dst(skb));
3876 EXPORT_SYMBOL(dev_loopback_xmit);
3878 #ifdef CONFIG_NET_EGRESS
3879 static struct sk_buff *
3880 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3882 #ifdef CONFIG_NET_CLS_ACT
3883 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3884 struct tcf_result cl_res;
3889 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3890 tc_skb_cb(skb)->mru = 0;
3891 tc_skb_cb(skb)->post_ct = false;
3892 mini_qdisc_bstats_cpu_update(miniq, skb);
3894 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
3896 case TC_ACT_RECLASSIFY:
3897 skb->tc_index = TC_H_MIN(cl_res.classid);
3900 mini_qdisc_qstats_cpu_drop(miniq);
3901 *ret = NET_XMIT_DROP;
3902 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS);
3907 *ret = NET_XMIT_SUCCESS;
3910 case TC_ACT_REDIRECT:
3911 /* No need to push/pop skb's mac_header here on egress! */
3912 skb_do_redirect(skb);
3913 *ret = NET_XMIT_SUCCESS;
3918 #endif /* CONFIG_NET_CLS_ACT */
3922 #endif /* CONFIG_NET_EGRESS */
3925 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3926 struct xps_dev_maps *dev_maps, unsigned int tci)
3928 int tc = netdev_get_prio_tc_map(dev, skb->priority);
3929 struct xps_map *map;
3930 int queue_index = -1;
3932 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
3935 tci *= dev_maps->num_tc;
3938 map = rcu_dereference(dev_maps->attr_map[tci]);
3941 queue_index = map->queues[0];
3943 queue_index = map->queues[reciprocal_scale(
3944 skb_get_hash(skb), map->len)];
3945 if (unlikely(queue_index >= dev->real_num_tx_queues))
3952 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3953 struct sk_buff *skb)
3956 struct xps_dev_maps *dev_maps;
3957 struct sock *sk = skb->sk;
3958 int queue_index = -1;
3960 if (!static_key_false(&xps_needed))
3964 if (!static_key_false(&xps_rxqs_needed))
3967 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
3969 int tci = sk_rx_queue_get(sk);
3972 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3977 if (queue_index < 0) {
3978 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
3980 unsigned int tci = skb->sender_cpu - 1;
3982 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3994 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3995 struct net_device *sb_dev)
3999 EXPORT_SYMBOL(dev_pick_tx_zero);
4001 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4002 struct net_device *sb_dev)
4004 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4006 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4008 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4009 struct net_device *sb_dev)
4011 struct sock *sk = skb->sk;
4012 int queue_index = sk_tx_queue_get(sk);
4014 sb_dev = sb_dev ? : dev;
4016 if (queue_index < 0 || skb->ooo_okay ||
4017 queue_index >= dev->real_num_tx_queues) {
4018 int new_index = get_xps_queue(dev, sb_dev, skb);
4021 new_index = skb_tx_hash(dev, sb_dev, skb);
4023 if (queue_index != new_index && sk &&
4025 rcu_access_pointer(sk->sk_dst_cache))
4026 sk_tx_queue_set(sk, new_index);
4028 queue_index = new_index;
4033 EXPORT_SYMBOL(netdev_pick_tx);
4035 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4036 struct sk_buff *skb,
4037 struct net_device *sb_dev)
4039 int queue_index = 0;
4042 u32 sender_cpu = skb->sender_cpu - 1;
4044 if (sender_cpu >= (u32)NR_CPUS)
4045 skb->sender_cpu = raw_smp_processor_id() + 1;
4048 if (dev->real_num_tx_queues != 1) {
4049 const struct net_device_ops *ops = dev->netdev_ops;
4051 if (ops->ndo_select_queue)
4052 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4054 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4056 queue_index = netdev_cap_txqueue(dev, queue_index);
4059 skb_set_queue_mapping(skb, queue_index);
4060 return netdev_get_tx_queue(dev, queue_index);
4064 * __dev_queue_xmit - transmit a buffer
4065 * @skb: buffer to transmit
4066 * @sb_dev: suboordinate device used for L2 forwarding offload
4068 * Queue a buffer for transmission to a network device. The caller must
4069 * have set the device and priority and built the buffer before calling
4070 * this function. The function can be called from an interrupt.
4072 * A negative errno code is returned on a failure. A success does not
4073 * guarantee the frame will be transmitted as it may be dropped due
4074 * to congestion or traffic shaping.
4076 * -----------------------------------------------------------------------------------
4077 * I notice this method can also return errors from the queue disciplines,
4078 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4081 * Regardless of the return value, the skb is consumed, so it is currently
4082 * difficult to retry a send to this method. (You can bump the ref count
4083 * before sending to hold a reference for retry if you are careful.)
4085 * When calling this method, interrupts MUST be enabled. This is because
4086 * the BH enable code must have IRQs enabled so that it will not deadlock.
4089 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4091 struct net_device *dev = skb->dev;
4092 struct netdev_queue *txq;
4097 skb_reset_mac_header(skb);
4099 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4100 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4102 /* Disable soft irqs for various locks below. Also
4103 * stops preemption for RCU.
4107 skb_update_prio(skb);
4109 qdisc_pkt_len_init(skb);
4110 #ifdef CONFIG_NET_CLS_ACT
4111 skb->tc_at_ingress = 0;
4113 #ifdef CONFIG_NET_EGRESS
4114 if (static_branch_unlikely(&egress_needed_key)) {
4115 if (nf_hook_egress_active()) {
4116 skb = nf_hook_egress(skb, &rc, dev);
4120 nf_skip_egress(skb, true);
4121 skb = sch_handle_egress(skb, &rc, dev);
4124 nf_skip_egress(skb, false);
4127 /* If device/qdisc don't need skb->dst, release it right now while
4128 * its hot in this cpu cache.
4130 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4135 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4136 q = rcu_dereference_bh(txq->qdisc);
4138 trace_net_dev_queue(skb);
4140 rc = __dev_xmit_skb(skb, q, dev, txq);
4144 /* The device has no queue. Common case for software devices:
4145 * loopback, all the sorts of tunnels...
4147 * Really, it is unlikely that netif_tx_lock protection is necessary
4148 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4150 * However, it is possible, that they rely on protection
4153 * Check this and shot the lock. It is not prone from deadlocks.
4154 *Either shot noqueue qdisc, it is even simpler 8)
4156 if (dev->flags & IFF_UP) {
4157 int cpu = smp_processor_id(); /* ok because BHs are off */
4159 /* Other cpus might concurrently change txq->xmit_lock_owner
4160 * to -1 or to their cpu id, but not to our id.
4162 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4163 if (dev_xmit_recursion())
4164 goto recursion_alert;
4166 skb = validate_xmit_skb(skb, dev, &again);
4170 HARD_TX_LOCK(dev, txq, cpu);
4172 if (!netif_xmit_stopped(txq)) {
4173 dev_xmit_recursion_inc();
4174 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4175 dev_xmit_recursion_dec();
4176 if (dev_xmit_complete(rc)) {
4177 HARD_TX_UNLOCK(dev, txq);
4181 HARD_TX_UNLOCK(dev, txq);
4182 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4185 /* Recursion is detected! It is possible,
4189 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4195 rcu_read_unlock_bh();
4197 dev_core_stats_tx_dropped_inc(dev);
4198 kfree_skb_list(skb);
4201 rcu_read_unlock_bh();
4205 int dev_queue_xmit(struct sk_buff *skb)
4207 return __dev_queue_xmit(skb, NULL);
4209 EXPORT_SYMBOL(dev_queue_xmit);
4211 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4213 return __dev_queue_xmit(skb, sb_dev);
4215 EXPORT_SYMBOL(dev_queue_xmit_accel);
4217 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4219 struct net_device *dev = skb->dev;
4220 struct sk_buff *orig_skb = skb;
4221 struct netdev_queue *txq;
4222 int ret = NETDEV_TX_BUSY;
4225 if (unlikely(!netif_running(dev) ||
4226 !netif_carrier_ok(dev)))
4229 skb = validate_xmit_skb_list(skb, dev, &again);
4230 if (skb != orig_skb)
4233 skb_set_queue_mapping(skb, queue_id);
4234 txq = skb_get_tx_queue(dev, skb);
4238 dev_xmit_recursion_inc();
4239 HARD_TX_LOCK(dev, txq, smp_processor_id());
4240 if (!netif_xmit_frozen_or_drv_stopped(txq))
4241 ret = netdev_start_xmit(skb, dev, txq, false);
4242 HARD_TX_UNLOCK(dev, txq);
4243 dev_xmit_recursion_dec();
4248 dev_core_stats_tx_dropped_inc(dev);
4249 kfree_skb_list(skb);
4250 return NET_XMIT_DROP;
4252 EXPORT_SYMBOL(__dev_direct_xmit);
4254 /*************************************************************************
4256 *************************************************************************/
4258 int netdev_max_backlog __read_mostly = 1000;
4259 EXPORT_SYMBOL(netdev_max_backlog);
4261 int netdev_tstamp_prequeue __read_mostly = 1;
4262 int netdev_budget __read_mostly = 300;
4263 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4264 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4265 int weight_p __read_mostly = 64; /* old backlog weight */
4266 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4267 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4268 int dev_rx_weight __read_mostly = 64;
4269 int dev_tx_weight __read_mostly = 64;
4271 /* Called with irq disabled */
4272 static inline void ____napi_schedule(struct softnet_data *sd,
4273 struct napi_struct *napi)
4275 struct task_struct *thread;
4277 lockdep_assert_irqs_disabled();
4279 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4280 /* Paired with smp_mb__before_atomic() in
4281 * napi_enable()/dev_set_threaded().
4282 * Use READ_ONCE() to guarantee a complete
4283 * read on napi->thread. Only call
4284 * wake_up_process() when it's not NULL.
4286 thread = READ_ONCE(napi->thread);
4288 /* Avoid doing set_bit() if the thread is in
4289 * INTERRUPTIBLE state, cause napi_thread_wait()
4290 * makes sure to proceed with napi polling
4291 * if the thread is explicitly woken from here.
4293 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4294 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4295 wake_up_process(thread);
4300 list_add_tail(&napi->poll_list, &sd->poll_list);
4301 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4306 /* One global table that all flow-based protocols share. */
4307 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4308 EXPORT_SYMBOL(rps_sock_flow_table);
4309 u32 rps_cpu_mask __read_mostly;
4310 EXPORT_SYMBOL(rps_cpu_mask);
4312 struct static_key_false rps_needed __read_mostly;
4313 EXPORT_SYMBOL(rps_needed);
4314 struct static_key_false rfs_needed __read_mostly;
4315 EXPORT_SYMBOL(rfs_needed);
4317 static struct rps_dev_flow *
4318 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4319 struct rps_dev_flow *rflow, u16 next_cpu)
4321 if (next_cpu < nr_cpu_ids) {
4322 #ifdef CONFIG_RFS_ACCEL
4323 struct netdev_rx_queue *rxqueue;
4324 struct rps_dev_flow_table *flow_table;
4325 struct rps_dev_flow *old_rflow;
4330 /* Should we steer this flow to a different hardware queue? */
4331 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4332 !(dev->features & NETIF_F_NTUPLE))
4334 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4335 if (rxq_index == skb_get_rx_queue(skb))
4338 rxqueue = dev->_rx + rxq_index;
4339 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4342 flow_id = skb_get_hash(skb) & flow_table->mask;
4343 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4344 rxq_index, flow_id);
4348 rflow = &flow_table->flows[flow_id];
4350 if (old_rflow->filter == rflow->filter)
4351 old_rflow->filter = RPS_NO_FILTER;
4355 per_cpu(softnet_data, next_cpu).input_queue_head;
4358 rflow->cpu = next_cpu;
4363 * get_rps_cpu is called from netif_receive_skb and returns the target
4364 * CPU from the RPS map of the receiving queue for a given skb.
4365 * rcu_read_lock must be held on entry.
4367 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4368 struct rps_dev_flow **rflowp)
4370 const struct rps_sock_flow_table *sock_flow_table;
4371 struct netdev_rx_queue *rxqueue = dev->_rx;
4372 struct rps_dev_flow_table *flow_table;
4373 struct rps_map *map;
4378 if (skb_rx_queue_recorded(skb)) {
4379 u16 index = skb_get_rx_queue(skb);
4381 if (unlikely(index >= dev->real_num_rx_queues)) {
4382 WARN_ONCE(dev->real_num_rx_queues > 1,
4383 "%s received packet on queue %u, but number "
4384 "of RX queues is %u\n",
4385 dev->name, index, dev->real_num_rx_queues);
4391 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4393 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4394 map = rcu_dereference(rxqueue->rps_map);
4395 if (!flow_table && !map)
4398 skb_reset_network_header(skb);
4399 hash = skb_get_hash(skb);
4403 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4404 if (flow_table && sock_flow_table) {
4405 struct rps_dev_flow *rflow;
4409 /* First check into global flow table if there is a match */
4410 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4411 if ((ident ^ hash) & ~rps_cpu_mask)
4414 next_cpu = ident & rps_cpu_mask;
4416 /* OK, now we know there is a match,
4417 * we can look at the local (per receive queue) flow table
4419 rflow = &flow_table->flows[hash & flow_table->mask];
4423 * If the desired CPU (where last recvmsg was done) is
4424 * different from current CPU (one in the rx-queue flow
4425 * table entry), switch if one of the following holds:
4426 * - Current CPU is unset (>= nr_cpu_ids).
4427 * - Current CPU is offline.
4428 * - The current CPU's queue tail has advanced beyond the
4429 * last packet that was enqueued using this table entry.
4430 * This guarantees that all previous packets for the flow
4431 * have been dequeued, thus preserving in order delivery.
4433 if (unlikely(tcpu != next_cpu) &&
4434 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4435 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4436 rflow->last_qtail)) >= 0)) {
4438 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4441 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4451 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4452 if (cpu_online(tcpu)) {
4462 #ifdef CONFIG_RFS_ACCEL
4465 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4466 * @dev: Device on which the filter was set
4467 * @rxq_index: RX queue index
4468 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4469 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4471 * Drivers that implement ndo_rx_flow_steer() should periodically call
4472 * this function for each installed filter and remove the filters for
4473 * which it returns %true.
4475 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4476 u32 flow_id, u16 filter_id)
4478 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4479 struct rps_dev_flow_table *flow_table;
4480 struct rps_dev_flow *rflow;
4485 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4486 if (flow_table && flow_id <= flow_table->mask) {
4487 rflow = &flow_table->flows[flow_id];
4488 cpu = READ_ONCE(rflow->cpu);
4489 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4490 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4491 rflow->last_qtail) <
4492 (int)(10 * flow_table->mask)))
4498 EXPORT_SYMBOL(rps_may_expire_flow);
4500 #endif /* CONFIG_RFS_ACCEL */
4502 /* Called from hardirq (IPI) context */
4503 static void rps_trigger_softirq(void *data)
4505 struct softnet_data *sd = data;
4507 ____napi_schedule(sd, &sd->backlog);
4511 #endif /* CONFIG_RPS */
4514 * Check if this softnet_data structure is another cpu one
4515 * If yes, queue it to our IPI list and return 1
4518 static int napi_schedule_rps(struct softnet_data *sd)
4520 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4524 sd->rps_ipi_next = mysd->rps_ipi_list;
4525 mysd->rps_ipi_list = sd;
4527 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4530 #endif /* CONFIG_RPS */
4531 __napi_schedule_irqoff(&mysd->backlog);
4535 #ifdef CONFIG_NET_FLOW_LIMIT
4536 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4539 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4541 #ifdef CONFIG_NET_FLOW_LIMIT
4542 struct sd_flow_limit *fl;
4543 struct softnet_data *sd;
4544 unsigned int old_flow, new_flow;
4546 if (qlen < (netdev_max_backlog >> 1))
4549 sd = this_cpu_ptr(&softnet_data);
4552 fl = rcu_dereference(sd->flow_limit);
4554 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4555 old_flow = fl->history[fl->history_head];
4556 fl->history[fl->history_head] = new_flow;
4559 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4561 if (likely(fl->buckets[old_flow]))
4562 fl->buckets[old_flow]--;
4564 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4576 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4577 * queue (may be a remote CPU queue).
4579 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4580 unsigned int *qtail)
4582 enum skb_drop_reason reason;
4583 struct softnet_data *sd;
4584 unsigned long flags;
4587 reason = SKB_DROP_REASON_NOT_SPECIFIED;
4588 sd = &per_cpu(softnet_data, cpu);
4590 rps_lock_irqsave(sd, &flags);
4591 if (!netif_running(skb->dev))
4593 qlen = skb_queue_len(&sd->input_pkt_queue);
4594 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4597 __skb_queue_tail(&sd->input_pkt_queue, skb);
4598 input_queue_tail_incr_save(sd, qtail);
4599 rps_unlock_irq_restore(sd, &flags);
4600 return NET_RX_SUCCESS;
4603 /* Schedule NAPI for backlog device
4604 * We can use non atomic operation since we own the queue lock
4606 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4607 napi_schedule_rps(sd);
4610 reason = SKB_DROP_REASON_CPU_BACKLOG;
4614 rps_unlock_irq_restore(sd, &flags);
4616 dev_core_stats_rx_dropped_inc(skb->dev);
4617 kfree_skb_reason(skb, reason);
4621 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4623 struct net_device *dev = skb->dev;
4624 struct netdev_rx_queue *rxqueue;
4628 if (skb_rx_queue_recorded(skb)) {
4629 u16 index = skb_get_rx_queue(skb);
4631 if (unlikely(index >= dev->real_num_rx_queues)) {
4632 WARN_ONCE(dev->real_num_rx_queues > 1,
4633 "%s received packet on queue %u, but number "
4634 "of RX queues is %u\n",
4635 dev->name, index, dev->real_num_rx_queues);
4637 return rxqueue; /* Return first rxqueue */
4644 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4645 struct bpf_prog *xdp_prog)
4647 void *orig_data, *orig_data_end, *hard_start;
4648 struct netdev_rx_queue *rxqueue;
4649 bool orig_bcast, orig_host;
4650 u32 mac_len, frame_sz;
4651 __be16 orig_eth_type;
4656 /* The XDP program wants to see the packet starting at the MAC
4659 mac_len = skb->data - skb_mac_header(skb);
4660 hard_start = skb->data - skb_headroom(skb);
4662 /* SKB "head" area always have tailroom for skb_shared_info */
4663 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4664 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4666 rxqueue = netif_get_rxqueue(skb);
4667 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4668 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4669 skb_headlen(skb) + mac_len, true);
4671 orig_data_end = xdp->data_end;
4672 orig_data = xdp->data;
4673 eth = (struct ethhdr *)xdp->data;
4674 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4675 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4676 orig_eth_type = eth->h_proto;
4678 act = bpf_prog_run_xdp(xdp_prog, xdp);
4680 /* check if bpf_xdp_adjust_head was used */
4681 off = xdp->data - orig_data;
4684 __skb_pull(skb, off);
4686 __skb_push(skb, -off);
4688 skb->mac_header += off;
4689 skb_reset_network_header(skb);
4692 /* check if bpf_xdp_adjust_tail was used */
4693 off = xdp->data_end - orig_data_end;
4695 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4696 skb->len += off; /* positive on grow, negative on shrink */
4699 /* check if XDP changed eth hdr such SKB needs update */
4700 eth = (struct ethhdr *)xdp->data;
4701 if ((orig_eth_type != eth->h_proto) ||
4702 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4703 skb->dev->dev_addr)) ||
4704 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4705 __skb_push(skb, ETH_HLEN);
4706 skb->pkt_type = PACKET_HOST;
4707 skb->protocol = eth_type_trans(skb, skb->dev);
4710 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4711 * before calling us again on redirect path. We do not call do_redirect
4712 * as we leave that up to the caller.
4714 * Caller is responsible for managing lifetime of skb (i.e. calling
4715 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4720 __skb_push(skb, mac_len);
4723 metalen = xdp->data - xdp->data_meta;
4725 skb_metadata_set(skb, metalen);
4732 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4733 struct xdp_buff *xdp,
4734 struct bpf_prog *xdp_prog)
4738 /* Reinjected packets coming from act_mirred or similar should
4739 * not get XDP generic processing.
4741 if (skb_is_redirected(skb))
4744 /* XDP packets must be linear and must have sufficient headroom
4745 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4746 * native XDP provides, thus we need to do it here as well.
4748 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4749 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4750 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4751 int troom = skb->tail + skb->data_len - skb->end;
4753 /* In case we have to go down the path and also linearize,
4754 * then lets do the pskb_expand_head() work just once here.
4756 if (pskb_expand_head(skb,
4757 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4758 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4760 if (skb_linearize(skb))
4764 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4771 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act);
4774 trace_xdp_exception(skb->dev, xdp_prog, act);
4785 /* When doing generic XDP we have to bypass the qdisc layer and the
4786 * network taps in order to match in-driver-XDP behavior.
4788 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4790 struct net_device *dev = skb->dev;
4791 struct netdev_queue *txq;
4792 bool free_skb = true;
4795 txq = netdev_core_pick_tx(dev, skb, NULL);
4796 cpu = smp_processor_id();
4797 HARD_TX_LOCK(dev, txq, cpu);
4798 if (!netif_xmit_stopped(txq)) {
4799 rc = netdev_start_xmit(skb, dev, txq, 0);
4800 if (dev_xmit_complete(rc))
4803 HARD_TX_UNLOCK(dev, txq);
4805 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4810 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4812 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4815 struct xdp_buff xdp;
4819 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4820 if (act != XDP_PASS) {
4823 err = xdp_do_generic_redirect(skb->dev, skb,
4829 generic_xdp_tx(skb, xdp_prog);
4837 kfree_skb_reason(skb, SKB_DROP_REASON_XDP);
4840 EXPORT_SYMBOL_GPL(do_xdp_generic);
4842 static int netif_rx_internal(struct sk_buff *skb)
4846 net_timestamp_check(netdev_tstamp_prequeue, skb);
4848 trace_netif_rx(skb);
4851 if (static_branch_unlikely(&rps_needed)) {
4852 struct rps_dev_flow voidflow, *rflow = &voidflow;
4857 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4859 cpu = smp_processor_id();
4861 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4869 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
4875 * __netif_rx - Slightly optimized version of netif_rx
4876 * @skb: buffer to post
4878 * This behaves as netif_rx except that it does not disable bottom halves.
4879 * As a result this function may only be invoked from the interrupt context
4880 * (either hard or soft interrupt).
4882 int __netif_rx(struct sk_buff *skb)
4886 lockdep_assert_once(hardirq_count() | softirq_count());
4888 trace_netif_rx_entry(skb);
4889 ret = netif_rx_internal(skb);
4890 trace_netif_rx_exit(ret);
4893 EXPORT_SYMBOL(__netif_rx);
4896 * netif_rx - post buffer to the network code
4897 * @skb: buffer to post
4899 * This function receives a packet from a device driver and queues it for
4900 * the upper (protocol) levels to process via the backlog NAPI device. It
4901 * always succeeds. The buffer may be dropped during processing for
4902 * congestion control or by the protocol layers.
4903 * The network buffer is passed via the backlog NAPI device. Modern NIC
4904 * driver should use NAPI and GRO.
4905 * This function can used from interrupt and from process context. The
4906 * caller from process context must not disable interrupts before invoking
4910 * NET_RX_SUCCESS (no congestion)
4911 * NET_RX_DROP (packet was dropped)
4914 int netif_rx(struct sk_buff *skb)
4916 bool need_bh_off = !(hardirq_count() | softirq_count());
4921 trace_netif_rx_entry(skb);
4922 ret = netif_rx_internal(skb);
4923 trace_netif_rx_exit(ret);
4928 EXPORT_SYMBOL(netif_rx);
4930 static __latent_entropy void net_tx_action(struct softirq_action *h)
4932 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4934 if (sd->completion_queue) {
4935 struct sk_buff *clist;
4937 local_irq_disable();
4938 clist = sd->completion_queue;
4939 sd->completion_queue = NULL;
4943 struct sk_buff *skb = clist;
4945 clist = clist->next;
4947 WARN_ON(refcount_read(&skb->users));
4948 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4949 trace_consume_skb(skb);
4951 trace_kfree_skb(skb, net_tx_action,
4952 SKB_DROP_REASON_NOT_SPECIFIED);
4954 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4957 __kfree_skb_defer(skb);
4961 if (sd->output_queue) {
4964 local_irq_disable();
4965 head = sd->output_queue;
4966 sd->output_queue = NULL;
4967 sd->output_queue_tailp = &sd->output_queue;
4973 struct Qdisc *q = head;
4974 spinlock_t *root_lock = NULL;
4976 head = head->next_sched;
4978 /* We need to make sure head->next_sched is read
4979 * before clearing __QDISC_STATE_SCHED
4981 smp_mb__before_atomic();
4983 if (!(q->flags & TCQ_F_NOLOCK)) {
4984 root_lock = qdisc_lock(q);
4985 spin_lock(root_lock);
4986 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
4988 /* There is a synchronize_net() between
4989 * STATE_DEACTIVATED flag being set and
4990 * qdisc_reset()/some_qdisc_is_busy() in
4991 * dev_deactivate(), so we can safely bail out
4992 * early here to avoid data race between
4993 * qdisc_deactivate() and some_qdisc_is_busy()
4994 * for lockless qdisc.
4996 clear_bit(__QDISC_STATE_SCHED, &q->state);
5000 clear_bit(__QDISC_STATE_SCHED, &q->state);
5003 spin_unlock(root_lock);
5009 xfrm_dev_backlog(sd);
5012 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5013 /* This hook is defined here for ATM LANE */
5014 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5015 unsigned char *addr) __read_mostly;
5016 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5019 static inline struct sk_buff *
5020 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
5021 struct net_device *orig_dev, bool *another)
5023 #ifdef CONFIG_NET_CLS_ACT
5024 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
5025 struct tcf_result cl_res;
5027 /* If there's at least one ingress present somewhere (so
5028 * we get here via enabled static key), remaining devices
5029 * that are not configured with an ingress qdisc will bail
5036 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5040 qdisc_skb_cb(skb)->pkt_len = skb->len;
5041 tc_skb_cb(skb)->mru = 0;
5042 tc_skb_cb(skb)->post_ct = false;
5043 skb->tc_at_ingress = 1;
5044 mini_qdisc_bstats_cpu_update(miniq, skb);
5046 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
5048 case TC_ACT_RECLASSIFY:
5049 skb->tc_index = TC_H_MIN(cl_res.classid);
5052 mini_qdisc_qstats_cpu_drop(miniq);
5053 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS);
5060 case TC_ACT_REDIRECT:
5061 /* skb_mac_header check was done by cls/act_bpf, so
5062 * we can safely push the L2 header back before
5063 * redirecting to another netdev
5065 __skb_push(skb, skb->mac_len);
5066 if (skb_do_redirect(skb) == -EAGAIN) {
5067 __skb_pull(skb, skb->mac_len);
5072 case TC_ACT_CONSUMED:
5077 #endif /* CONFIG_NET_CLS_ACT */
5082 * netdev_is_rx_handler_busy - check if receive handler is registered
5083 * @dev: device to check
5085 * Check if a receive handler is already registered for a given device.
5086 * Return true if there one.
5088 * The caller must hold the rtnl_mutex.
5090 bool netdev_is_rx_handler_busy(struct net_device *dev)
5093 return dev && rtnl_dereference(dev->rx_handler);
5095 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5098 * netdev_rx_handler_register - register receive handler
5099 * @dev: device to register a handler for
5100 * @rx_handler: receive handler to register
5101 * @rx_handler_data: data pointer that is used by rx handler
5103 * Register a receive handler for a device. This handler will then be
5104 * called from __netif_receive_skb. A negative errno code is returned
5107 * The caller must hold the rtnl_mutex.
5109 * For a general description of rx_handler, see enum rx_handler_result.
5111 int netdev_rx_handler_register(struct net_device *dev,
5112 rx_handler_func_t *rx_handler,
5113 void *rx_handler_data)
5115 if (netdev_is_rx_handler_busy(dev))
5118 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5121 /* Note: rx_handler_data must be set before rx_handler */
5122 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5123 rcu_assign_pointer(dev->rx_handler, rx_handler);
5127 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5130 * netdev_rx_handler_unregister - unregister receive handler
5131 * @dev: device to unregister a handler from
5133 * Unregister a receive handler from a device.
5135 * The caller must hold the rtnl_mutex.
5137 void netdev_rx_handler_unregister(struct net_device *dev)
5141 RCU_INIT_POINTER(dev->rx_handler, NULL);
5142 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5143 * section has a guarantee to see a non NULL rx_handler_data
5147 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5149 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5152 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5153 * the special handling of PFMEMALLOC skbs.
5155 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5157 switch (skb->protocol) {
5158 case htons(ETH_P_ARP):
5159 case htons(ETH_P_IP):
5160 case htons(ETH_P_IPV6):
5161 case htons(ETH_P_8021Q):
5162 case htons(ETH_P_8021AD):
5169 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5170 int *ret, struct net_device *orig_dev)
5172 if (nf_hook_ingress_active(skb)) {
5176 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5181 ingress_retval = nf_hook_ingress(skb);
5183 return ingress_retval;
5188 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5189 struct packet_type **ppt_prev)
5191 struct packet_type *ptype, *pt_prev;
5192 rx_handler_func_t *rx_handler;
5193 struct sk_buff *skb = *pskb;
5194 struct net_device *orig_dev;
5195 bool deliver_exact = false;
5196 int ret = NET_RX_DROP;
5199 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5201 trace_netif_receive_skb(skb);
5203 orig_dev = skb->dev;
5205 skb_reset_network_header(skb);
5206 if (!skb_transport_header_was_set(skb))
5207 skb_reset_transport_header(skb);
5208 skb_reset_mac_len(skb);
5213 skb->skb_iif = skb->dev->ifindex;
5215 __this_cpu_inc(softnet_data.processed);
5217 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5221 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5224 if (ret2 != XDP_PASS) {
5230 if (eth_type_vlan(skb->protocol)) {
5231 skb = skb_vlan_untag(skb);
5236 if (skb_skip_tc_classify(skb))
5242 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5244 ret = deliver_skb(skb, pt_prev, orig_dev);
5248 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5250 ret = deliver_skb(skb, pt_prev, orig_dev);
5255 #ifdef CONFIG_NET_INGRESS
5256 if (static_branch_unlikely(&ingress_needed_key)) {
5257 bool another = false;
5259 nf_skip_egress(skb, true);
5260 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5267 nf_skip_egress(skb, false);
5268 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5272 skb_reset_redirect(skb);
5274 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5277 if (skb_vlan_tag_present(skb)) {
5279 ret = deliver_skb(skb, pt_prev, orig_dev);
5282 if (vlan_do_receive(&skb))
5284 else if (unlikely(!skb))
5288 rx_handler = rcu_dereference(skb->dev->rx_handler);
5291 ret = deliver_skb(skb, pt_prev, orig_dev);
5294 switch (rx_handler(&skb)) {
5295 case RX_HANDLER_CONSUMED:
5296 ret = NET_RX_SUCCESS;
5298 case RX_HANDLER_ANOTHER:
5300 case RX_HANDLER_EXACT:
5301 deliver_exact = true;
5303 case RX_HANDLER_PASS:
5310 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5312 if (skb_vlan_tag_get_id(skb)) {
5313 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5316 skb->pkt_type = PACKET_OTHERHOST;
5317 } else if (eth_type_vlan(skb->protocol)) {
5318 /* Outer header is 802.1P with vlan 0, inner header is
5319 * 802.1Q or 802.1AD and vlan_do_receive() above could
5320 * not find vlan dev for vlan id 0.
5322 __vlan_hwaccel_clear_tag(skb);
5323 skb = skb_vlan_untag(skb);
5326 if (vlan_do_receive(&skb))
5327 /* After stripping off 802.1P header with vlan 0
5328 * vlan dev is found for inner header.
5331 else if (unlikely(!skb))
5334 /* We have stripped outer 802.1P vlan 0 header.
5335 * But could not find vlan dev.
5336 * check again for vlan id to set OTHERHOST.
5340 /* Note: we might in the future use prio bits
5341 * and set skb->priority like in vlan_do_receive()
5342 * For the time being, just ignore Priority Code Point
5344 __vlan_hwaccel_clear_tag(skb);
5347 type = skb->protocol;
5349 /* deliver only exact match when indicated */
5350 if (likely(!deliver_exact)) {
5351 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5352 &ptype_base[ntohs(type) &
5356 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5357 &orig_dev->ptype_specific);
5359 if (unlikely(skb->dev != orig_dev)) {
5360 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5361 &skb->dev->ptype_specific);
5365 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5367 *ppt_prev = pt_prev;
5370 if (!deliver_exact) {
5371 dev_core_stats_rx_dropped_inc(skb->dev);
5372 kfree_skb_reason(skb, SKB_DROP_REASON_PTYPE_ABSENT);
5374 dev_core_stats_rx_nohandler_inc(skb->dev);
5377 /* Jamal, now you will not able to escape explaining
5378 * me how you were going to use this. :-)
5384 /* The invariant here is that if *ppt_prev is not NULL
5385 * then skb should also be non-NULL.
5387 * Apparently *ppt_prev assignment above holds this invariant due to
5388 * skb dereferencing near it.
5394 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5396 struct net_device *orig_dev = skb->dev;
5397 struct packet_type *pt_prev = NULL;
5400 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5402 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5403 skb->dev, pt_prev, orig_dev);
5408 * netif_receive_skb_core - special purpose version of netif_receive_skb
5409 * @skb: buffer to process
5411 * More direct receive version of netif_receive_skb(). It should
5412 * only be used by callers that have a need to skip RPS and Generic XDP.
5413 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5415 * This function may only be called from softirq context and interrupts
5416 * should be enabled.
5418 * Return values (usually ignored):
5419 * NET_RX_SUCCESS: no congestion
5420 * NET_RX_DROP: packet was dropped
5422 int netif_receive_skb_core(struct sk_buff *skb)
5427 ret = __netif_receive_skb_one_core(skb, false);
5432 EXPORT_SYMBOL(netif_receive_skb_core);
5434 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5435 struct packet_type *pt_prev,
5436 struct net_device *orig_dev)
5438 struct sk_buff *skb, *next;
5442 if (list_empty(head))
5444 if (pt_prev->list_func != NULL)
5445 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5446 ip_list_rcv, head, pt_prev, orig_dev);
5448 list_for_each_entry_safe(skb, next, head, list) {
5449 skb_list_del_init(skb);
5450 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5454 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5456 /* Fast-path assumptions:
5457 * - There is no RX handler.
5458 * - Only one packet_type matches.
5459 * If either of these fails, we will end up doing some per-packet
5460 * processing in-line, then handling the 'last ptype' for the whole
5461 * sublist. This can't cause out-of-order delivery to any single ptype,
5462 * because the 'last ptype' must be constant across the sublist, and all
5463 * other ptypes are handled per-packet.
5465 /* Current (common) ptype of sublist */
5466 struct packet_type *pt_curr = NULL;
5467 /* Current (common) orig_dev of sublist */
5468 struct net_device *od_curr = NULL;
5469 struct list_head sublist;
5470 struct sk_buff *skb, *next;
5472 INIT_LIST_HEAD(&sublist);
5473 list_for_each_entry_safe(skb, next, head, list) {
5474 struct net_device *orig_dev = skb->dev;
5475 struct packet_type *pt_prev = NULL;
5477 skb_list_del_init(skb);
5478 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5481 if (pt_curr != pt_prev || od_curr != orig_dev) {
5482 /* dispatch old sublist */
5483 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5484 /* start new sublist */
5485 INIT_LIST_HEAD(&sublist);
5489 list_add_tail(&skb->list, &sublist);
5492 /* dispatch final sublist */
5493 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5496 static int __netif_receive_skb(struct sk_buff *skb)
5500 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5501 unsigned int noreclaim_flag;
5504 * PFMEMALLOC skbs are special, they should
5505 * - be delivered to SOCK_MEMALLOC sockets only
5506 * - stay away from userspace
5507 * - have bounded memory usage
5509 * Use PF_MEMALLOC as this saves us from propagating the allocation
5510 * context down to all allocation sites.
5512 noreclaim_flag = memalloc_noreclaim_save();
5513 ret = __netif_receive_skb_one_core(skb, true);
5514 memalloc_noreclaim_restore(noreclaim_flag);
5516 ret = __netif_receive_skb_one_core(skb, false);
5521 static void __netif_receive_skb_list(struct list_head *head)
5523 unsigned long noreclaim_flag = 0;
5524 struct sk_buff *skb, *next;
5525 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5527 list_for_each_entry_safe(skb, next, head, list) {
5528 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5529 struct list_head sublist;
5531 /* Handle the previous sublist */
5532 list_cut_before(&sublist, head, &skb->list);
5533 if (!list_empty(&sublist))
5534 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5535 pfmemalloc = !pfmemalloc;
5536 /* See comments in __netif_receive_skb */
5538 noreclaim_flag = memalloc_noreclaim_save();
5540 memalloc_noreclaim_restore(noreclaim_flag);
5543 /* Handle the remaining sublist */
5544 if (!list_empty(head))
5545 __netif_receive_skb_list_core(head, pfmemalloc);
5546 /* Restore pflags */
5548 memalloc_noreclaim_restore(noreclaim_flag);
5551 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5553 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5554 struct bpf_prog *new = xdp->prog;
5557 switch (xdp->command) {
5558 case XDP_SETUP_PROG:
5559 rcu_assign_pointer(dev->xdp_prog, new);
5564 static_branch_dec(&generic_xdp_needed_key);
5565 } else if (new && !old) {
5566 static_branch_inc(&generic_xdp_needed_key);
5567 dev_disable_lro(dev);
5568 dev_disable_gro_hw(dev);
5580 static int netif_receive_skb_internal(struct sk_buff *skb)
5584 net_timestamp_check(netdev_tstamp_prequeue, skb);
5586 if (skb_defer_rx_timestamp(skb))
5587 return NET_RX_SUCCESS;
5591 if (static_branch_unlikely(&rps_needed)) {
5592 struct rps_dev_flow voidflow, *rflow = &voidflow;
5593 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5596 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5602 ret = __netif_receive_skb(skb);
5607 void netif_receive_skb_list_internal(struct list_head *head)
5609 struct sk_buff *skb, *next;
5610 struct list_head sublist;
5612 INIT_LIST_HEAD(&sublist);
5613 list_for_each_entry_safe(skb, next, head, list) {
5614 net_timestamp_check(netdev_tstamp_prequeue, skb);
5615 skb_list_del_init(skb);
5616 if (!skb_defer_rx_timestamp(skb))
5617 list_add_tail(&skb->list, &sublist);
5619 list_splice_init(&sublist, head);
5623 if (static_branch_unlikely(&rps_needed)) {
5624 list_for_each_entry_safe(skb, next, head, list) {
5625 struct rps_dev_flow voidflow, *rflow = &voidflow;
5626 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5629 /* Will be handled, remove from list */
5630 skb_list_del_init(skb);
5631 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5636 __netif_receive_skb_list(head);
5641 * netif_receive_skb - process receive buffer from network
5642 * @skb: buffer to process
5644 * netif_receive_skb() is the main receive data processing function.
5645 * It always succeeds. The buffer may be dropped during processing
5646 * for congestion control or by the protocol layers.
5648 * This function may only be called from softirq context and interrupts
5649 * should be enabled.
5651 * Return values (usually ignored):
5652 * NET_RX_SUCCESS: no congestion
5653 * NET_RX_DROP: packet was dropped
5655 int netif_receive_skb(struct sk_buff *skb)
5659 trace_netif_receive_skb_entry(skb);
5661 ret = netif_receive_skb_internal(skb);
5662 trace_netif_receive_skb_exit(ret);
5666 EXPORT_SYMBOL(netif_receive_skb);
5669 * netif_receive_skb_list - process many receive buffers from network
5670 * @head: list of skbs to process.
5672 * Since return value of netif_receive_skb() is normally ignored, and
5673 * wouldn't be meaningful for a list, this function returns void.
5675 * This function may only be called from softirq context and interrupts
5676 * should be enabled.
5678 void netif_receive_skb_list(struct list_head *head)
5680 struct sk_buff *skb;
5682 if (list_empty(head))
5684 if (trace_netif_receive_skb_list_entry_enabled()) {
5685 list_for_each_entry(skb, head, list)
5686 trace_netif_receive_skb_list_entry(skb);
5688 netif_receive_skb_list_internal(head);
5689 trace_netif_receive_skb_list_exit(0);
5691 EXPORT_SYMBOL(netif_receive_skb_list);
5693 static DEFINE_PER_CPU(struct work_struct, flush_works);
5695 /* Network device is going away, flush any packets still pending */
5696 static void flush_backlog(struct work_struct *work)
5698 struct sk_buff *skb, *tmp;
5699 struct softnet_data *sd;
5702 sd = this_cpu_ptr(&softnet_data);
5704 rps_lock_irq_disable(sd);
5705 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5706 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5707 __skb_unlink(skb, &sd->input_pkt_queue);
5708 dev_kfree_skb_irq(skb);
5709 input_queue_head_incr(sd);
5712 rps_unlock_irq_enable(sd);
5714 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5715 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5716 __skb_unlink(skb, &sd->process_queue);
5718 input_queue_head_incr(sd);
5724 static bool flush_required(int cpu)
5726 #if IS_ENABLED(CONFIG_RPS)
5727 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5730 rps_lock_irq_disable(sd);
5732 /* as insertion into process_queue happens with the rps lock held,
5733 * process_queue access may race only with dequeue
5735 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5736 !skb_queue_empty_lockless(&sd->process_queue);
5737 rps_unlock_irq_enable(sd);
5741 /* without RPS we can't safely check input_pkt_queue: during a
5742 * concurrent remote skb_queue_splice() we can detect as empty both
5743 * input_pkt_queue and process_queue even if the latter could end-up
5744 * containing a lot of packets.
5749 static void flush_all_backlogs(void)
5751 static cpumask_t flush_cpus;
5754 /* since we are under rtnl lock protection we can use static data
5755 * for the cpumask and avoid allocating on stack the possibly
5762 cpumask_clear(&flush_cpus);
5763 for_each_online_cpu(cpu) {
5764 if (flush_required(cpu)) {
5765 queue_work_on(cpu, system_highpri_wq,
5766 per_cpu_ptr(&flush_works, cpu));
5767 cpumask_set_cpu(cpu, &flush_cpus);
5771 /* we can have in flight packet[s] on the cpus we are not flushing,
5772 * synchronize_net() in unregister_netdevice_many() will take care of
5775 for_each_cpu(cpu, &flush_cpus)
5776 flush_work(per_cpu_ptr(&flush_works, cpu));
5781 static void net_rps_send_ipi(struct softnet_data *remsd)
5785 struct softnet_data *next = remsd->rps_ipi_next;
5787 if (cpu_online(remsd->cpu))
5788 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5795 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5796 * Note: called with local irq disabled, but exits with local irq enabled.
5798 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5801 struct softnet_data *remsd = sd->rps_ipi_list;
5804 sd->rps_ipi_list = NULL;
5808 /* Send pending IPI's to kick RPS processing on remote cpus. */
5809 net_rps_send_ipi(remsd);
5815 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5818 return sd->rps_ipi_list != NULL;
5824 static int process_backlog(struct napi_struct *napi, int quota)
5826 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5830 /* Check if we have pending ipi, its better to send them now,
5831 * not waiting net_rx_action() end.
5833 if (sd_has_rps_ipi_waiting(sd)) {
5834 local_irq_disable();
5835 net_rps_action_and_irq_enable(sd);
5838 napi->weight = dev_rx_weight;
5840 struct sk_buff *skb;
5842 while ((skb = __skb_dequeue(&sd->process_queue))) {
5844 __netif_receive_skb(skb);
5846 input_queue_head_incr(sd);
5847 if (++work >= quota)
5852 rps_lock_irq_disable(sd);
5853 if (skb_queue_empty(&sd->input_pkt_queue)) {
5855 * Inline a custom version of __napi_complete().
5856 * only current cpu owns and manipulates this napi,
5857 * and NAPI_STATE_SCHED is the only possible flag set
5859 * We can use a plain write instead of clear_bit(),
5860 * and we dont need an smp_mb() memory barrier.
5865 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5866 &sd->process_queue);
5868 rps_unlock_irq_enable(sd);
5875 * __napi_schedule - schedule for receive
5876 * @n: entry to schedule
5878 * The entry's receive function will be scheduled to run.
5879 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5881 void __napi_schedule(struct napi_struct *n)
5883 unsigned long flags;
5885 local_irq_save(flags);
5886 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5887 local_irq_restore(flags);
5889 EXPORT_SYMBOL(__napi_schedule);
5892 * napi_schedule_prep - check if napi can be scheduled
5895 * Test if NAPI routine is already running, and if not mark
5896 * it as running. This is used as a condition variable to
5897 * insure only one NAPI poll instance runs. We also make
5898 * sure there is no pending NAPI disable.
5900 bool napi_schedule_prep(struct napi_struct *n)
5902 unsigned long val, new;
5905 val = READ_ONCE(n->state);
5906 if (unlikely(val & NAPIF_STATE_DISABLE))
5908 new = val | NAPIF_STATE_SCHED;
5910 /* Sets STATE_MISSED bit if STATE_SCHED was already set
5911 * This was suggested by Alexander Duyck, as compiler
5912 * emits better code than :
5913 * if (val & NAPIF_STATE_SCHED)
5914 * new |= NAPIF_STATE_MISSED;
5916 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
5918 } while (cmpxchg(&n->state, val, new) != val);
5920 return !(val & NAPIF_STATE_SCHED);
5922 EXPORT_SYMBOL(napi_schedule_prep);
5925 * __napi_schedule_irqoff - schedule for receive
5926 * @n: entry to schedule
5928 * Variant of __napi_schedule() assuming hard irqs are masked.
5930 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
5931 * because the interrupt disabled assumption might not be true
5932 * due to force-threaded interrupts and spinlock substitution.
5934 void __napi_schedule_irqoff(struct napi_struct *n)
5936 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
5937 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5941 EXPORT_SYMBOL(__napi_schedule_irqoff);
5943 bool napi_complete_done(struct napi_struct *n, int work_done)
5945 unsigned long flags, val, new, timeout = 0;
5949 * 1) Don't let napi dequeue from the cpu poll list
5950 * just in case its running on a different cpu.
5951 * 2) If we are busy polling, do nothing here, we have
5952 * the guarantee we will be called later.
5954 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
5955 NAPIF_STATE_IN_BUSY_POLL)))
5960 timeout = READ_ONCE(n->dev->gro_flush_timeout);
5961 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
5963 if (n->defer_hard_irqs_count > 0) {
5964 n->defer_hard_irqs_count--;
5965 timeout = READ_ONCE(n->dev->gro_flush_timeout);
5969 if (n->gro_bitmask) {
5970 /* When the NAPI instance uses a timeout and keeps postponing
5971 * it, we need to bound somehow the time packets are kept in
5974 napi_gro_flush(n, !!timeout);
5979 if (unlikely(!list_empty(&n->poll_list))) {
5980 /* If n->poll_list is not empty, we need to mask irqs */
5981 local_irq_save(flags);
5982 list_del_init(&n->poll_list);
5983 local_irq_restore(flags);
5987 val = READ_ONCE(n->state);
5989 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
5991 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
5992 NAPIF_STATE_SCHED_THREADED |
5993 NAPIF_STATE_PREFER_BUSY_POLL);
5995 /* If STATE_MISSED was set, leave STATE_SCHED set,
5996 * because we will call napi->poll() one more time.
5997 * This C code was suggested by Alexander Duyck to help gcc.
5999 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6001 } while (cmpxchg(&n->state, val, new) != val);
6003 if (unlikely(val & NAPIF_STATE_MISSED)) {
6009 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6010 HRTIMER_MODE_REL_PINNED);
6013 EXPORT_SYMBOL(napi_complete_done);
6015 /* must be called under rcu_read_lock(), as we dont take a reference */
6016 static struct napi_struct *napi_by_id(unsigned int napi_id)
6018 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6019 struct napi_struct *napi;
6021 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6022 if (napi->napi_id == napi_id)
6028 #if defined(CONFIG_NET_RX_BUSY_POLL)
6030 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6032 if (!skip_schedule) {
6033 gro_normal_list(napi);
6034 __napi_schedule(napi);
6038 if (napi->gro_bitmask) {
6039 /* flush too old packets
6040 * If HZ < 1000, flush all packets.
6042 napi_gro_flush(napi, HZ >= 1000);
6045 gro_normal_list(napi);
6046 clear_bit(NAPI_STATE_SCHED, &napi->state);
6049 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6052 bool skip_schedule = false;
6053 unsigned long timeout;
6056 /* Busy polling means there is a high chance device driver hard irq
6057 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6058 * set in napi_schedule_prep().
6059 * Since we are about to call napi->poll() once more, we can safely
6060 * clear NAPI_STATE_MISSED.
6062 * Note: x86 could use a single "lock and ..." instruction
6063 * to perform these two clear_bit()
6065 clear_bit(NAPI_STATE_MISSED, &napi->state);
6066 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6070 if (prefer_busy_poll) {
6071 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6072 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6073 if (napi->defer_hard_irqs_count && timeout) {
6074 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6075 skip_schedule = true;
6079 /* All we really want here is to re-enable device interrupts.
6080 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6082 rc = napi->poll(napi, budget);
6083 /* We can't gro_normal_list() here, because napi->poll() might have
6084 * rearmed the napi (napi_complete_done()) in which case it could
6085 * already be running on another CPU.
6087 trace_napi_poll(napi, rc, budget);
6088 netpoll_poll_unlock(have_poll_lock);
6090 __busy_poll_stop(napi, skip_schedule);
6094 void napi_busy_loop(unsigned int napi_id,
6095 bool (*loop_end)(void *, unsigned long),
6096 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6098 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6099 int (*napi_poll)(struct napi_struct *napi, int budget);
6100 void *have_poll_lock = NULL;
6101 struct napi_struct *napi;
6108 napi = napi_by_id(napi_id);
6118 unsigned long val = READ_ONCE(napi->state);
6120 /* If multiple threads are competing for this napi,
6121 * we avoid dirtying napi->state as much as we can.
6123 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6124 NAPIF_STATE_IN_BUSY_POLL)) {
6125 if (prefer_busy_poll)
6126 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6129 if (cmpxchg(&napi->state, val,
6130 val | NAPIF_STATE_IN_BUSY_POLL |
6131 NAPIF_STATE_SCHED) != val) {
6132 if (prefer_busy_poll)
6133 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6136 have_poll_lock = netpoll_poll_lock(napi);
6137 napi_poll = napi->poll;
6139 work = napi_poll(napi, budget);
6140 trace_napi_poll(napi, work, budget);
6141 gro_normal_list(napi);
6144 __NET_ADD_STATS(dev_net(napi->dev),
6145 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6148 if (!loop_end || loop_end(loop_end_arg, start_time))
6151 if (unlikely(need_resched())) {
6153 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6157 if (loop_end(loop_end_arg, start_time))
6164 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6169 EXPORT_SYMBOL(napi_busy_loop);
6171 #endif /* CONFIG_NET_RX_BUSY_POLL */
6173 static void napi_hash_add(struct napi_struct *napi)
6175 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6178 spin_lock(&napi_hash_lock);
6180 /* 0..NR_CPUS range is reserved for sender_cpu use */
6182 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6183 napi_gen_id = MIN_NAPI_ID;
6184 } while (napi_by_id(napi_gen_id));
6185 napi->napi_id = napi_gen_id;
6187 hlist_add_head_rcu(&napi->napi_hash_node,
6188 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6190 spin_unlock(&napi_hash_lock);
6193 /* Warning : caller is responsible to make sure rcu grace period
6194 * is respected before freeing memory containing @napi
6196 static void napi_hash_del(struct napi_struct *napi)
6198 spin_lock(&napi_hash_lock);
6200 hlist_del_init_rcu(&napi->napi_hash_node);
6202 spin_unlock(&napi_hash_lock);
6205 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6207 struct napi_struct *napi;
6209 napi = container_of(timer, struct napi_struct, timer);
6211 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6212 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6214 if (!napi_disable_pending(napi) &&
6215 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6216 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6217 __napi_schedule_irqoff(napi);
6220 return HRTIMER_NORESTART;
6223 static void init_gro_hash(struct napi_struct *napi)
6227 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6228 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6229 napi->gro_hash[i].count = 0;
6231 napi->gro_bitmask = 0;
6234 int dev_set_threaded(struct net_device *dev, bool threaded)
6236 struct napi_struct *napi;
6239 if (dev->threaded == threaded)
6243 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6244 if (!napi->thread) {
6245 err = napi_kthread_create(napi);
6254 dev->threaded = threaded;
6256 /* Make sure kthread is created before THREADED bit
6259 smp_mb__before_atomic();
6261 /* Setting/unsetting threaded mode on a napi might not immediately
6262 * take effect, if the current napi instance is actively being
6263 * polled. In this case, the switch between threaded mode and
6264 * softirq mode will happen in the next round of napi_schedule().
6265 * This should not cause hiccups/stalls to the live traffic.
6267 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6269 set_bit(NAPI_STATE_THREADED, &napi->state);
6271 clear_bit(NAPI_STATE_THREADED, &napi->state);
6276 EXPORT_SYMBOL(dev_set_threaded);
6278 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6279 int (*poll)(struct napi_struct *, int), int weight)
6281 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6284 INIT_LIST_HEAD(&napi->poll_list);
6285 INIT_HLIST_NODE(&napi->napi_hash_node);
6286 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6287 napi->timer.function = napi_watchdog;
6288 init_gro_hash(napi);
6290 INIT_LIST_HEAD(&napi->rx_list);
6293 if (weight > NAPI_POLL_WEIGHT)
6294 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6296 napi->weight = weight;
6298 #ifdef CONFIG_NETPOLL
6299 napi->poll_owner = -1;
6301 set_bit(NAPI_STATE_SCHED, &napi->state);
6302 set_bit(NAPI_STATE_NPSVC, &napi->state);
6303 list_add_rcu(&napi->dev_list, &dev->napi_list);
6304 napi_hash_add(napi);
6305 /* Create kthread for this napi if dev->threaded is set.
6306 * Clear dev->threaded if kthread creation failed so that
6307 * threaded mode will not be enabled in napi_enable().
6309 if (dev->threaded && napi_kthread_create(napi))
6312 EXPORT_SYMBOL(netif_napi_add);
6314 void napi_disable(struct napi_struct *n)
6316 unsigned long val, new;
6319 set_bit(NAPI_STATE_DISABLE, &n->state);
6322 val = READ_ONCE(n->state);
6323 if (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6324 usleep_range(20, 200);
6328 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6329 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6331 if (cmpxchg(&n->state, val, new) == val)
6335 hrtimer_cancel(&n->timer);
6337 clear_bit(NAPI_STATE_DISABLE, &n->state);
6339 EXPORT_SYMBOL(napi_disable);
6342 * napi_enable - enable NAPI scheduling
6345 * Resume NAPI from being scheduled on this context.
6346 * Must be paired with napi_disable.
6348 void napi_enable(struct napi_struct *n)
6350 unsigned long val, new;
6353 val = READ_ONCE(n->state);
6354 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6356 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6357 if (n->dev->threaded && n->thread)
6358 new |= NAPIF_STATE_THREADED;
6359 } while (cmpxchg(&n->state, val, new) != val);
6361 EXPORT_SYMBOL(napi_enable);
6363 static void flush_gro_hash(struct napi_struct *napi)
6367 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6368 struct sk_buff *skb, *n;
6370 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6372 napi->gro_hash[i].count = 0;
6376 /* Must be called in process context */
6377 void __netif_napi_del(struct napi_struct *napi)
6379 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6382 napi_hash_del(napi);
6383 list_del_rcu(&napi->dev_list);
6384 napi_free_frags(napi);
6386 flush_gro_hash(napi);
6387 napi->gro_bitmask = 0;
6390 kthread_stop(napi->thread);
6391 napi->thread = NULL;
6394 EXPORT_SYMBOL(__netif_napi_del);
6396 static int __napi_poll(struct napi_struct *n, bool *repoll)
6402 /* This NAPI_STATE_SCHED test is for avoiding a race
6403 * with netpoll's poll_napi(). Only the entity which
6404 * obtains the lock and sees NAPI_STATE_SCHED set will
6405 * actually make the ->poll() call. Therefore we avoid
6406 * accidentally calling ->poll() when NAPI is not scheduled.
6409 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6410 work = n->poll(n, weight);
6411 trace_napi_poll(n, work, weight);
6414 if (unlikely(work > weight))
6415 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6416 n->poll, work, weight);
6418 if (likely(work < weight))
6421 /* Drivers must not modify the NAPI state if they
6422 * consume the entire weight. In such cases this code
6423 * still "owns" the NAPI instance and therefore can
6424 * move the instance around on the list at-will.
6426 if (unlikely(napi_disable_pending(n))) {
6431 /* The NAPI context has more processing work, but busy-polling
6432 * is preferred. Exit early.
6434 if (napi_prefer_busy_poll(n)) {
6435 if (napi_complete_done(n, work)) {
6436 /* If timeout is not set, we need to make sure
6437 * that the NAPI is re-scheduled.
6444 if (n->gro_bitmask) {
6445 /* flush too old packets
6446 * If HZ < 1000, flush all packets.
6448 napi_gro_flush(n, HZ >= 1000);
6453 /* Some drivers may have called napi_schedule
6454 * prior to exhausting their budget.
6456 if (unlikely(!list_empty(&n->poll_list))) {
6457 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6458 n->dev ? n->dev->name : "backlog");
6467 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6469 bool do_repoll = false;
6473 list_del_init(&n->poll_list);
6475 have = netpoll_poll_lock(n);
6477 work = __napi_poll(n, &do_repoll);
6480 list_add_tail(&n->poll_list, repoll);
6482 netpoll_poll_unlock(have);
6487 static int napi_thread_wait(struct napi_struct *napi)
6491 set_current_state(TASK_INTERRUPTIBLE);
6493 while (!kthread_should_stop()) {
6494 /* Testing SCHED_THREADED bit here to make sure the current
6495 * kthread owns this napi and could poll on this napi.
6496 * Testing SCHED bit is not enough because SCHED bit might be
6497 * set by some other busy poll thread or by napi_disable().
6499 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6500 WARN_ON(!list_empty(&napi->poll_list));
6501 __set_current_state(TASK_RUNNING);
6506 /* woken being true indicates this thread owns this napi. */
6508 set_current_state(TASK_INTERRUPTIBLE);
6510 __set_current_state(TASK_RUNNING);
6515 static int napi_threaded_poll(void *data)
6517 struct napi_struct *napi = data;
6520 while (!napi_thread_wait(napi)) {
6522 bool repoll = false;
6526 have = netpoll_poll_lock(napi);
6527 __napi_poll(napi, &repoll);
6528 netpoll_poll_unlock(have);
6541 static __latent_entropy void net_rx_action(struct softirq_action *h)
6543 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6544 unsigned long time_limit = jiffies +
6545 usecs_to_jiffies(netdev_budget_usecs);
6546 int budget = netdev_budget;
6550 local_irq_disable();
6551 list_splice_init(&sd->poll_list, &list);
6555 struct napi_struct *n;
6557 if (list_empty(&list)) {
6558 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6563 n = list_first_entry(&list, struct napi_struct, poll_list);
6564 budget -= napi_poll(n, &repoll);
6566 /* If softirq window is exhausted then punt.
6567 * Allow this to run for 2 jiffies since which will allow
6568 * an average latency of 1.5/HZ.
6570 if (unlikely(budget <= 0 ||
6571 time_after_eq(jiffies, time_limit))) {
6577 local_irq_disable();
6579 list_splice_tail_init(&sd->poll_list, &list);
6580 list_splice_tail(&repoll, &list);
6581 list_splice(&list, &sd->poll_list);
6582 if (!list_empty(&sd->poll_list))
6583 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6585 net_rps_action_and_irq_enable(sd);
6588 struct netdev_adjacent {
6589 struct net_device *dev;
6590 netdevice_tracker dev_tracker;
6592 /* upper master flag, there can only be one master device per list */
6595 /* lookup ignore flag */
6598 /* counter for the number of times this device was added to us */
6601 /* private field for the users */
6604 struct list_head list;
6605 struct rcu_head rcu;
6608 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6609 struct list_head *adj_list)
6611 struct netdev_adjacent *adj;
6613 list_for_each_entry(adj, adj_list, list) {
6614 if (adj->dev == adj_dev)
6620 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6621 struct netdev_nested_priv *priv)
6623 struct net_device *dev = (struct net_device *)priv->data;
6625 return upper_dev == dev;
6629 * netdev_has_upper_dev - Check if device is linked to an upper device
6631 * @upper_dev: upper device to check
6633 * Find out if a device is linked to specified upper device and return true
6634 * in case it is. Note that this checks only immediate upper device,
6635 * not through a complete stack of devices. The caller must hold the RTNL lock.
6637 bool netdev_has_upper_dev(struct net_device *dev,
6638 struct net_device *upper_dev)
6640 struct netdev_nested_priv priv = {
6641 .data = (void *)upper_dev,
6646 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6649 EXPORT_SYMBOL(netdev_has_upper_dev);
6652 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6654 * @upper_dev: upper device to check
6656 * Find out if a device is linked to specified upper device and return true
6657 * in case it is. Note that this checks the entire upper device chain.
6658 * The caller must hold rcu lock.
6661 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6662 struct net_device *upper_dev)
6664 struct netdev_nested_priv priv = {
6665 .data = (void *)upper_dev,
6668 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6671 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6674 * netdev_has_any_upper_dev - Check if device is linked to some device
6677 * Find out if a device is linked to an upper device and return true in case
6678 * it is. The caller must hold the RTNL lock.
6680 bool netdev_has_any_upper_dev(struct net_device *dev)
6684 return !list_empty(&dev->adj_list.upper);
6686 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6689 * netdev_master_upper_dev_get - Get master upper device
6692 * Find a master upper device and return pointer to it or NULL in case
6693 * it's not there. The caller must hold the RTNL lock.
6695 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6697 struct netdev_adjacent *upper;
6701 if (list_empty(&dev->adj_list.upper))
6704 upper = list_first_entry(&dev->adj_list.upper,
6705 struct netdev_adjacent, list);
6706 if (likely(upper->master))
6710 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6712 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6714 struct netdev_adjacent *upper;
6718 if (list_empty(&dev->adj_list.upper))
6721 upper = list_first_entry(&dev->adj_list.upper,
6722 struct netdev_adjacent, list);
6723 if (likely(upper->master) && !upper->ignore)
6729 * netdev_has_any_lower_dev - Check if device is linked to some device
6732 * Find out if a device is linked to a lower device and return true in case
6733 * it is. The caller must hold the RTNL lock.
6735 static bool netdev_has_any_lower_dev(struct net_device *dev)
6739 return !list_empty(&dev->adj_list.lower);
6742 void *netdev_adjacent_get_private(struct list_head *adj_list)
6744 struct netdev_adjacent *adj;
6746 adj = list_entry(adj_list, struct netdev_adjacent, list);
6748 return adj->private;
6750 EXPORT_SYMBOL(netdev_adjacent_get_private);
6753 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6755 * @iter: list_head ** of the current position
6757 * Gets the next device from the dev's upper list, starting from iter
6758 * position. The caller must hold RCU read lock.
6760 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6761 struct list_head **iter)
6763 struct netdev_adjacent *upper;
6765 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6767 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6769 if (&upper->list == &dev->adj_list.upper)
6772 *iter = &upper->list;
6776 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6778 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6779 struct list_head **iter,
6782 struct netdev_adjacent *upper;
6784 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6786 if (&upper->list == &dev->adj_list.upper)
6789 *iter = &upper->list;
6790 *ignore = upper->ignore;
6795 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6796 struct list_head **iter)
6798 struct netdev_adjacent *upper;
6800 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6802 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6804 if (&upper->list == &dev->adj_list.upper)
6807 *iter = &upper->list;
6812 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6813 int (*fn)(struct net_device *dev,
6814 struct netdev_nested_priv *priv),
6815 struct netdev_nested_priv *priv)
6817 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6818 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6823 iter = &dev->adj_list.upper;
6827 ret = fn(now, priv);
6834 udev = __netdev_next_upper_dev(now, &iter, &ignore);
6841 niter = &udev->adj_list.upper;
6842 dev_stack[cur] = now;
6843 iter_stack[cur++] = iter;
6850 next = dev_stack[--cur];
6851 niter = iter_stack[cur];
6861 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6862 int (*fn)(struct net_device *dev,
6863 struct netdev_nested_priv *priv),
6864 struct netdev_nested_priv *priv)
6866 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6867 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6871 iter = &dev->adj_list.upper;
6875 ret = fn(now, priv);
6882 udev = netdev_next_upper_dev_rcu(now, &iter);
6887 niter = &udev->adj_list.upper;
6888 dev_stack[cur] = now;
6889 iter_stack[cur++] = iter;
6896 next = dev_stack[--cur];
6897 niter = iter_stack[cur];
6906 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6908 static bool __netdev_has_upper_dev(struct net_device *dev,
6909 struct net_device *upper_dev)
6911 struct netdev_nested_priv priv = {
6913 .data = (void *)upper_dev,
6918 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
6923 * netdev_lower_get_next_private - Get the next ->private from the
6924 * lower neighbour list
6926 * @iter: list_head ** of the current position
6928 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6929 * list, starting from iter position. The caller must hold either hold the
6930 * RTNL lock or its own locking that guarantees that the neighbour lower
6931 * list will remain unchanged.
6933 void *netdev_lower_get_next_private(struct net_device *dev,
6934 struct list_head **iter)
6936 struct netdev_adjacent *lower;
6938 lower = list_entry(*iter, struct netdev_adjacent, list);
6940 if (&lower->list == &dev->adj_list.lower)
6943 *iter = lower->list.next;
6945 return lower->private;
6947 EXPORT_SYMBOL(netdev_lower_get_next_private);
6950 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6951 * lower neighbour list, RCU
6954 * @iter: list_head ** of the current position
6956 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6957 * list, starting from iter position. The caller must hold RCU read lock.
6959 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6960 struct list_head **iter)
6962 struct netdev_adjacent *lower;
6964 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
6966 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6968 if (&lower->list == &dev->adj_list.lower)
6971 *iter = &lower->list;
6973 return lower->private;
6975 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6978 * netdev_lower_get_next - Get the next device from the lower neighbour
6981 * @iter: list_head ** of the current position
6983 * Gets the next netdev_adjacent from the dev's lower neighbour
6984 * list, starting from iter position. The caller must hold RTNL lock or
6985 * its own locking that guarantees that the neighbour lower
6986 * list will remain unchanged.
6988 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6990 struct netdev_adjacent *lower;
6992 lower = list_entry(*iter, struct netdev_adjacent, list);
6994 if (&lower->list == &dev->adj_list.lower)
6997 *iter = lower->list.next;
7001 EXPORT_SYMBOL(netdev_lower_get_next);
7003 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7004 struct list_head **iter)
7006 struct netdev_adjacent *lower;
7008 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7010 if (&lower->list == &dev->adj_list.lower)
7013 *iter = &lower->list;
7018 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7019 struct list_head **iter,
7022 struct netdev_adjacent *lower;
7024 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7026 if (&lower->list == &dev->adj_list.lower)
7029 *iter = &lower->list;
7030 *ignore = lower->ignore;
7035 int netdev_walk_all_lower_dev(struct net_device *dev,
7036 int (*fn)(struct net_device *dev,
7037 struct netdev_nested_priv *priv),
7038 struct netdev_nested_priv *priv)
7040 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7041 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7045 iter = &dev->adj_list.lower;
7049 ret = fn(now, priv);
7056 ldev = netdev_next_lower_dev(now, &iter);
7061 niter = &ldev->adj_list.lower;
7062 dev_stack[cur] = now;
7063 iter_stack[cur++] = iter;
7070 next = dev_stack[--cur];
7071 niter = iter_stack[cur];
7080 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7082 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7083 int (*fn)(struct net_device *dev,
7084 struct netdev_nested_priv *priv),
7085 struct netdev_nested_priv *priv)
7087 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7088 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7093 iter = &dev->adj_list.lower;
7097 ret = fn(now, priv);
7104 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7111 niter = &ldev->adj_list.lower;
7112 dev_stack[cur] = now;
7113 iter_stack[cur++] = iter;
7120 next = dev_stack[--cur];
7121 niter = iter_stack[cur];
7131 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7132 struct list_head **iter)
7134 struct netdev_adjacent *lower;
7136 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7137 if (&lower->list == &dev->adj_list.lower)
7140 *iter = &lower->list;
7144 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7146 static u8 __netdev_upper_depth(struct net_device *dev)
7148 struct net_device *udev;
7149 struct list_head *iter;
7153 for (iter = &dev->adj_list.upper,
7154 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7156 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7159 if (max_depth < udev->upper_level)
7160 max_depth = udev->upper_level;
7166 static u8 __netdev_lower_depth(struct net_device *dev)
7168 struct net_device *ldev;
7169 struct list_head *iter;
7173 for (iter = &dev->adj_list.lower,
7174 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7176 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7179 if (max_depth < ldev->lower_level)
7180 max_depth = ldev->lower_level;
7186 static int __netdev_update_upper_level(struct net_device *dev,
7187 struct netdev_nested_priv *__unused)
7189 dev->upper_level = __netdev_upper_depth(dev) + 1;
7193 #ifdef CONFIG_LOCKDEP
7194 static LIST_HEAD(net_unlink_list);
7196 static void net_unlink_todo(struct net_device *dev)
7198 if (list_empty(&dev->unlink_list))
7199 list_add_tail(&dev->unlink_list, &net_unlink_list);
7203 static int __netdev_update_lower_level(struct net_device *dev,
7204 struct netdev_nested_priv *priv)
7206 dev->lower_level = __netdev_lower_depth(dev) + 1;
7208 #ifdef CONFIG_LOCKDEP
7212 if (priv->flags & NESTED_SYNC_IMM)
7213 dev->nested_level = dev->lower_level - 1;
7214 if (priv->flags & NESTED_SYNC_TODO)
7215 net_unlink_todo(dev);
7220 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7221 int (*fn)(struct net_device *dev,
7222 struct netdev_nested_priv *priv),
7223 struct netdev_nested_priv *priv)
7225 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7226 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7230 iter = &dev->adj_list.lower;
7234 ret = fn(now, priv);
7241 ldev = netdev_next_lower_dev_rcu(now, &iter);
7246 niter = &ldev->adj_list.lower;
7247 dev_stack[cur] = now;
7248 iter_stack[cur++] = iter;
7255 next = dev_stack[--cur];
7256 niter = iter_stack[cur];
7265 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7268 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7269 * lower neighbour list, RCU
7273 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7274 * list. The caller must hold RCU read lock.
7276 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7278 struct netdev_adjacent *lower;
7280 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7281 struct netdev_adjacent, list);
7283 return lower->private;
7286 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7289 * netdev_master_upper_dev_get_rcu - Get master upper device
7292 * Find a master upper device and return pointer to it or NULL in case
7293 * it's not there. The caller must hold the RCU read lock.
7295 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7297 struct netdev_adjacent *upper;
7299 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7300 struct netdev_adjacent, list);
7301 if (upper && likely(upper->master))
7305 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7307 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7308 struct net_device *adj_dev,
7309 struct list_head *dev_list)
7311 char linkname[IFNAMSIZ+7];
7313 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7314 "upper_%s" : "lower_%s", adj_dev->name);
7315 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7318 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7320 struct list_head *dev_list)
7322 char linkname[IFNAMSIZ+7];
7324 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7325 "upper_%s" : "lower_%s", name);
7326 sysfs_remove_link(&(dev->dev.kobj), linkname);
7329 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7330 struct net_device *adj_dev,
7331 struct list_head *dev_list)
7333 return (dev_list == &dev->adj_list.upper ||
7334 dev_list == &dev->adj_list.lower) &&
7335 net_eq(dev_net(dev), dev_net(adj_dev));
7338 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7339 struct net_device *adj_dev,
7340 struct list_head *dev_list,
7341 void *private, bool master)
7343 struct netdev_adjacent *adj;
7346 adj = __netdev_find_adj(adj_dev, dev_list);
7350 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7351 dev->name, adj_dev->name, adj->ref_nr);
7356 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7361 adj->master = master;
7363 adj->private = private;
7364 adj->ignore = false;
7365 dev_hold_track(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7367 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7368 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7370 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7371 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7376 /* Ensure that master link is always the first item in list. */
7378 ret = sysfs_create_link(&(dev->dev.kobj),
7379 &(adj_dev->dev.kobj), "master");
7381 goto remove_symlinks;
7383 list_add_rcu(&adj->list, dev_list);
7385 list_add_tail_rcu(&adj->list, dev_list);
7391 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7392 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7394 dev_put_track(adj_dev, &adj->dev_tracker);
7400 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7401 struct net_device *adj_dev,
7403 struct list_head *dev_list)
7405 struct netdev_adjacent *adj;
7407 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7408 dev->name, adj_dev->name, ref_nr);
7410 adj = __netdev_find_adj(adj_dev, dev_list);
7413 pr_err("Adjacency does not exist for device %s from %s\n",
7414 dev->name, adj_dev->name);
7419 if (adj->ref_nr > ref_nr) {
7420 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7421 dev->name, adj_dev->name, ref_nr,
7422 adj->ref_nr - ref_nr);
7423 adj->ref_nr -= ref_nr;
7428 sysfs_remove_link(&(dev->dev.kobj), "master");
7430 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7431 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7433 list_del_rcu(&adj->list);
7434 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7435 adj_dev->name, dev->name, adj_dev->name);
7436 dev_put_track(adj_dev, &adj->dev_tracker);
7437 kfree_rcu(adj, rcu);
7440 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7441 struct net_device *upper_dev,
7442 struct list_head *up_list,
7443 struct list_head *down_list,
7444 void *private, bool master)
7448 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7453 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7456 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7463 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7464 struct net_device *upper_dev,
7466 struct list_head *up_list,
7467 struct list_head *down_list)
7469 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7470 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7473 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7474 struct net_device *upper_dev,
7475 void *private, bool master)
7477 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7478 &dev->adj_list.upper,
7479 &upper_dev->adj_list.lower,
7483 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7484 struct net_device *upper_dev)
7486 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7487 &dev->adj_list.upper,
7488 &upper_dev->adj_list.lower);
7491 static int __netdev_upper_dev_link(struct net_device *dev,
7492 struct net_device *upper_dev, bool master,
7493 void *upper_priv, void *upper_info,
7494 struct netdev_nested_priv *priv,
7495 struct netlink_ext_ack *extack)
7497 struct netdev_notifier_changeupper_info changeupper_info = {
7502 .upper_dev = upper_dev,
7505 .upper_info = upper_info,
7507 struct net_device *master_dev;
7512 if (dev == upper_dev)
7515 /* To prevent loops, check if dev is not upper device to upper_dev. */
7516 if (__netdev_has_upper_dev(upper_dev, dev))
7519 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7523 if (__netdev_has_upper_dev(dev, upper_dev))
7526 master_dev = __netdev_master_upper_dev_get(dev);
7528 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7531 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7532 &changeupper_info.info);
7533 ret = notifier_to_errno(ret);
7537 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7542 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7543 &changeupper_info.info);
7544 ret = notifier_to_errno(ret);
7548 __netdev_update_upper_level(dev, NULL);
7549 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7551 __netdev_update_lower_level(upper_dev, priv);
7552 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7558 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7564 * netdev_upper_dev_link - Add a link to the upper device
7566 * @upper_dev: new upper device
7567 * @extack: netlink extended ack
7569 * Adds a link to device which is upper to this one. The caller must hold
7570 * the RTNL lock. On a failure a negative errno code is returned.
7571 * On success the reference counts are adjusted and the function
7574 int netdev_upper_dev_link(struct net_device *dev,
7575 struct net_device *upper_dev,
7576 struct netlink_ext_ack *extack)
7578 struct netdev_nested_priv priv = {
7579 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7583 return __netdev_upper_dev_link(dev, upper_dev, false,
7584 NULL, NULL, &priv, extack);
7586 EXPORT_SYMBOL(netdev_upper_dev_link);
7589 * netdev_master_upper_dev_link - Add a master link to the upper device
7591 * @upper_dev: new upper device
7592 * @upper_priv: upper device private
7593 * @upper_info: upper info to be passed down via notifier
7594 * @extack: netlink extended ack
7596 * Adds a link to device which is upper to this one. In this case, only
7597 * one master upper device can be linked, although other non-master devices
7598 * might be linked as well. The caller must hold the RTNL lock.
7599 * On a failure a negative errno code is returned. On success the reference
7600 * counts are adjusted and the function returns zero.
7602 int netdev_master_upper_dev_link(struct net_device *dev,
7603 struct net_device *upper_dev,
7604 void *upper_priv, void *upper_info,
7605 struct netlink_ext_ack *extack)
7607 struct netdev_nested_priv priv = {
7608 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7612 return __netdev_upper_dev_link(dev, upper_dev, true,
7613 upper_priv, upper_info, &priv, extack);
7615 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7617 static void __netdev_upper_dev_unlink(struct net_device *dev,
7618 struct net_device *upper_dev,
7619 struct netdev_nested_priv *priv)
7621 struct netdev_notifier_changeupper_info changeupper_info = {
7625 .upper_dev = upper_dev,
7631 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7633 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7634 &changeupper_info.info);
7636 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7638 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7639 &changeupper_info.info);
7641 __netdev_update_upper_level(dev, NULL);
7642 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7644 __netdev_update_lower_level(upper_dev, priv);
7645 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7650 * netdev_upper_dev_unlink - Removes a link to upper device
7652 * @upper_dev: new upper device
7654 * Removes a link to device which is upper to this one. The caller must hold
7657 void netdev_upper_dev_unlink(struct net_device *dev,
7658 struct net_device *upper_dev)
7660 struct netdev_nested_priv priv = {
7661 .flags = NESTED_SYNC_TODO,
7665 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7667 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7669 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7670 struct net_device *lower_dev,
7673 struct netdev_adjacent *adj;
7675 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7679 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7684 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7685 struct net_device *lower_dev)
7687 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7690 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7691 struct net_device *lower_dev)
7693 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7696 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7697 struct net_device *new_dev,
7698 struct net_device *dev,
7699 struct netlink_ext_ack *extack)
7701 struct netdev_nested_priv priv = {
7710 if (old_dev && new_dev != old_dev)
7711 netdev_adjacent_dev_disable(dev, old_dev);
7712 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7715 if (old_dev && new_dev != old_dev)
7716 netdev_adjacent_dev_enable(dev, old_dev);
7722 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7724 void netdev_adjacent_change_commit(struct net_device *old_dev,
7725 struct net_device *new_dev,
7726 struct net_device *dev)
7728 struct netdev_nested_priv priv = {
7729 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7733 if (!new_dev || !old_dev)
7736 if (new_dev == old_dev)
7739 netdev_adjacent_dev_enable(dev, old_dev);
7740 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7742 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7744 void netdev_adjacent_change_abort(struct net_device *old_dev,
7745 struct net_device *new_dev,
7746 struct net_device *dev)
7748 struct netdev_nested_priv priv = {
7756 if (old_dev && new_dev != old_dev)
7757 netdev_adjacent_dev_enable(dev, old_dev);
7759 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7761 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7764 * netdev_bonding_info_change - Dispatch event about slave change
7766 * @bonding_info: info to dispatch
7768 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7769 * The caller must hold the RTNL lock.
7771 void netdev_bonding_info_change(struct net_device *dev,
7772 struct netdev_bonding_info *bonding_info)
7774 struct netdev_notifier_bonding_info info = {
7778 memcpy(&info.bonding_info, bonding_info,
7779 sizeof(struct netdev_bonding_info));
7780 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7783 EXPORT_SYMBOL(netdev_bonding_info_change);
7785 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
7786 struct netlink_ext_ack *extack)
7788 struct netdev_notifier_offload_xstats_info info = {
7790 .info.extack = extack,
7791 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7796 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
7798 if (!dev->offload_xstats_l3)
7801 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
7802 NETDEV_OFFLOAD_XSTATS_DISABLE,
7804 err = notifier_to_errno(rc);
7811 kfree(dev->offload_xstats_l3);
7812 dev->offload_xstats_l3 = NULL;
7816 int netdev_offload_xstats_enable(struct net_device *dev,
7817 enum netdev_offload_xstats_type type,
7818 struct netlink_ext_ack *extack)
7822 if (netdev_offload_xstats_enabled(dev, type))
7826 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7827 return netdev_offload_xstats_enable_l3(dev, extack);
7833 EXPORT_SYMBOL(netdev_offload_xstats_enable);
7835 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
7837 struct netdev_notifier_offload_xstats_info info = {
7839 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7842 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
7844 kfree(dev->offload_xstats_l3);
7845 dev->offload_xstats_l3 = NULL;
7848 int netdev_offload_xstats_disable(struct net_device *dev,
7849 enum netdev_offload_xstats_type type)
7853 if (!netdev_offload_xstats_enabled(dev, type))
7857 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7858 netdev_offload_xstats_disable_l3(dev);
7865 EXPORT_SYMBOL(netdev_offload_xstats_disable);
7867 static void netdev_offload_xstats_disable_all(struct net_device *dev)
7869 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
7872 static struct rtnl_hw_stats64 *
7873 netdev_offload_xstats_get_ptr(const struct net_device *dev,
7874 enum netdev_offload_xstats_type type)
7877 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7878 return dev->offload_xstats_l3;
7885 bool netdev_offload_xstats_enabled(const struct net_device *dev,
7886 enum netdev_offload_xstats_type type)
7890 return netdev_offload_xstats_get_ptr(dev, type);
7892 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
7894 struct netdev_notifier_offload_xstats_ru {
7898 struct netdev_notifier_offload_xstats_rd {
7899 struct rtnl_hw_stats64 stats;
7903 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
7904 const struct rtnl_hw_stats64 *src)
7906 dest->rx_packets += src->rx_packets;
7907 dest->tx_packets += src->tx_packets;
7908 dest->rx_bytes += src->rx_bytes;
7909 dest->tx_bytes += src->tx_bytes;
7910 dest->rx_errors += src->rx_errors;
7911 dest->tx_errors += src->tx_errors;
7912 dest->rx_dropped += src->rx_dropped;
7913 dest->tx_dropped += src->tx_dropped;
7914 dest->multicast += src->multicast;
7917 static int netdev_offload_xstats_get_used(struct net_device *dev,
7918 enum netdev_offload_xstats_type type,
7920 struct netlink_ext_ack *extack)
7922 struct netdev_notifier_offload_xstats_ru report_used = {};
7923 struct netdev_notifier_offload_xstats_info info = {
7925 .info.extack = extack,
7927 .report_used = &report_used,
7931 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
7932 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
7934 *p_used = report_used.used;
7935 return notifier_to_errno(rc);
7938 static int netdev_offload_xstats_get_stats(struct net_device *dev,
7939 enum netdev_offload_xstats_type type,
7940 struct rtnl_hw_stats64 *p_stats,
7942 struct netlink_ext_ack *extack)
7944 struct netdev_notifier_offload_xstats_rd report_delta = {};
7945 struct netdev_notifier_offload_xstats_info info = {
7947 .info.extack = extack,
7949 .report_delta = &report_delta,
7951 struct rtnl_hw_stats64 *stats;
7954 stats = netdev_offload_xstats_get_ptr(dev, type);
7955 if (WARN_ON(!stats))
7958 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
7961 /* Cache whatever we got, even if there was an error, otherwise the
7962 * successful stats retrievals would get lost.
7964 netdev_hw_stats64_add(stats, &report_delta.stats);
7968 *p_used = report_delta.used;
7970 return notifier_to_errno(rc);
7973 int netdev_offload_xstats_get(struct net_device *dev,
7974 enum netdev_offload_xstats_type type,
7975 struct rtnl_hw_stats64 *p_stats, bool *p_used,
7976 struct netlink_ext_ack *extack)
7981 return netdev_offload_xstats_get_stats(dev, type, p_stats,
7984 return netdev_offload_xstats_get_used(dev, type, p_used,
7987 EXPORT_SYMBOL(netdev_offload_xstats_get);
7990 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
7991 const struct rtnl_hw_stats64 *stats)
7993 report_delta->used = true;
7994 netdev_hw_stats64_add(&report_delta->stats, stats);
7996 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
7999 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8001 report_used->used = true;
8003 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8005 void netdev_offload_xstats_push_delta(struct net_device *dev,
8006 enum netdev_offload_xstats_type type,
8007 const struct rtnl_hw_stats64 *p_stats)
8009 struct rtnl_hw_stats64 *stats;
8013 stats = netdev_offload_xstats_get_ptr(dev, type);
8014 if (WARN_ON(!stats))
8017 netdev_hw_stats64_add(stats, p_stats);
8019 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8022 * netdev_get_xmit_slave - Get the xmit slave of master device
8025 * @all_slaves: assume all the slaves are active
8027 * The reference counters are not incremented so the caller must be
8028 * careful with locks. The caller must hold RCU lock.
8029 * %NULL is returned if no slave is found.
8032 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8033 struct sk_buff *skb,
8036 const struct net_device_ops *ops = dev->netdev_ops;
8038 if (!ops->ndo_get_xmit_slave)
8040 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8042 EXPORT_SYMBOL(netdev_get_xmit_slave);
8044 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8047 const struct net_device_ops *ops = dev->netdev_ops;
8049 if (!ops->ndo_sk_get_lower_dev)
8051 return ops->ndo_sk_get_lower_dev(dev, sk);
8055 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8059 * %NULL is returned if no lower device is found.
8062 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8065 struct net_device *lower;
8067 lower = netdev_sk_get_lower_dev(dev, sk);
8070 lower = netdev_sk_get_lower_dev(dev, sk);
8075 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8077 static void netdev_adjacent_add_links(struct net_device *dev)
8079 struct netdev_adjacent *iter;
8081 struct net *net = dev_net(dev);
8083 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8084 if (!net_eq(net, dev_net(iter->dev)))
8086 netdev_adjacent_sysfs_add(iter->dev, dev,
8087 &iter->dev->adj_list.lower);
8088 netdev_adjacent_sysfs_add(dev, iter->dev,
8089 &dev->adj_list.upper);
8092 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8093 if (!net_eq(net, dev_net(iter->dev)))
8095 netdev_adjacent_sysfs_add(iter->dev, dev,
8096 &iter->dev->adj_list.upper);
8097 netdev_adjacent_sysfs_add(dev, iter->dev,
8098 &dev->adj_list.lower);
8102 static void netdev_adjacent_del_links(struct net_device *dev)
8104 struct netdev_adjacent *iter;
8106 struct net *net = dev_net(dev);
8108 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8109 if (!net_eq(net, dev_net(iter->dev)))
8111 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8112 &iter->dev->adj_list.lower);
8113 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8114 &dev->adj_list.upper);
8117 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8118 if (!net_eq(net, dev_net(iter->dev)))
8120 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8121 &iter->dev->adj_list.upper);
8122 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8123 &dev->adj_list.lower);
8127 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8129 struct netdev_adjacent *iter;
8131 struct net *net = dev_net(dev);
8133 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8134 if (!net_eq(net, dev_net(iter->dev)))
8136 netdev_adjacent_sysfs_del(iter->dev, oldname,
8137 &iter->dev->adj_list.lower);
8138 netdev_adjacent_sysfs_add(iter->dev, dev,
8139 &iter->dev->adj_list.lower);
8142 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8143 if (!net_eq(net, dev_net(iter->dev)))
8145 netdev_adjacent_sysfs_del(iter->dev, oldname,
8146 &iter->dev->adj_list.upper);
8147 netdev_adjacent_sysfs_add(iter->dev, dev,
8148 &iter->dev->adj_list.upper);
8152 void *netdev_lower_dev_get_private(struct net_device *dev,
8153 struct net_device *lower_dev)
8155 struct netdev_adjacent *lower;
8159 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8163 return lower->private;
8165 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8169 * netdev_lower_state_changed - Dispatch event about lower device state change
8170 * @lower_dev: device
8171 * @lower_state_info: state to dispatch
8173 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8174 * The caller must hold the RTNL lock.
8176 void netdev_lower_state_changed(struct net_device *lower_dev,
8177 void *lower_state_info)
8179 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8180 .info.dev = lower_dev,
8184 changelowerstate_info.lower_state_info = lower_state_info;
8185 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8186 &changelowerstate_info.info);
8188 EXPORT_SYMBOL(netdev_lower_state_changed);
8190 static void dev_change_rx_flags(struct net_device *dev, int flags)
8192 const struct net_device_ops *ops = dev->netdev_ops;
8194 if (ops->ndo_change_rx_flags)
8195 ops->ndo_change_rx_flags(dev, flags);
8198 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8200 unsigned int old_flags = dev->flags;
8206 dev->flags |= IFF_PROMISC;
8207 dev->promiscuity += inc;
8208 if (dev->promiscuity == 0) {
8211 * If inc causes overflow, untouch promisc and return error.
8214 dev->flags &= ~IFF_PROMISC;
8216 dev->promiscuity -= inc;
8217 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8221 if (dev->flags != old_flags) {
8222 pr_info("device %s %s promiscuous mode\n",
8224 dev->flags & IFF_PROMISC ? "entered" : "left");
8225 if (audit_enabled) {
8226 current_uid_gid(&uid, &gid);
8227 audit_log(audit_context(), GFP_ATOMIC,
8228 AUDIT_ANOM_PROMISCUOUS,
8229 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8230 dev->name, (dev->flags & IFF_PROMISC),
8231 (old_flags & IFF_PROMISC),
8232 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8233 from_kuid(&init_user_ns, uid),
8234 from_kgid(&init_user_ns, gid),
8235 audit_get_sessionid(current));
8238 dev_change_rx_flags(dev, IFF_PROMISC);
8241 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
8246 * dev_set_promiscuity - update promiscuity count on a device
8250 * Add or remove promiscuity from a device. While the count in the device
8251 * remains above zero the interface remains promiscuous. Once it hits zero
8252 * the device reverts back to normal filtering operation. A negative inc
8253 * value is used to drop promiscuity on the device.
8254 * Return 0 if successful or a negative errno code on error.
8256 int dev_set_promiscuity(struct net_device *dev, int inc)
8258 unsigned int old_flags = dev->flags;
8261 err = __dev_set_promiscuity(dev, inc, true);
8264 if (dev->flags != old_flags)
8265 dev_set_rx_mode(dev);
8268 EXPORT_SYMBOL(dev_set_promiscuity);
8270 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8272 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8276 dev->flags |= IFF_ALLMULTI;
8277 dev->allmulti += inc;
8278 if (dev->allmulti == 0) {
8281 * If inc causes overflow, untouch allmulti and return error.
8284 dev->flags &= ~IFF_ALLMULTI;
8286 dev->allmulti -= inc;
8287 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8291 if (dev->flags ^ old_flags) {
8292 dev_change_rx_flags(dev, IFF_ALLMULTI);
8293 dev_set_rx_mode(dev);
8295 __dev_notify_flags(dev, old_flags,
8296 dev->gflags ^ old_gflags);
8302 * dev_set_allmulti - update allmulti count on a device
8306 * Add or remove reception of all multicast frames to a device. While the
8307 * count in the device remains above zero the interface remains listening
8308 * to all interfaces. Once it hits zero the device reverts back to normal
8309 * filtering operation. A negative @inc value is used to drop the counter
8310 * when releasing a resource needing all multicasts.
8311 * Return 0 if successful or a negative errno code on error.
8314 int dev_set_allmulti(struct net_device *dev, int inc)
8316 return __dev_set_allmulti(dev, inc, true);
8318 EXPORT_SYMBOL(dev_set_allmulti);
8321 * Upload unicast and multicast address lists to device and
8322 * configure RX filtering. When the device doesn't support unicast
8323 * filtering it is put in promiscuous mode while unicast addresses
8326 void __dev_set_rx_mode(struct net_device *dev)
8328 const struct net_device_ops *ops = dev->netdev_ops;
8330 /* dev_open will call this function so the list will stay sane. */
8331 if (!(dev->flags&IFF_UP))
8334 if (!netif_device_present(dev))
8337 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8338 /* Unicast addresses changes may only happen under the rtnl,
8339 * therefore calling __dev_set_promiscuity here is safe.
8341 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8342 __dev_set_promiscuity(dev, 1, false);
8343 dev->uc_promisc = true;
8344 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8345 __dev_set_promiscuity(dev, -1, false);
8346 dev->uc_promisc = false;
8350 if (ops->ndo_set_rx_mode)
8351 ops->ndo_set_rx_mode(dev);
8354 void dev_set_rx_mode(struct net_device *dev)
8356 netif_addr_lock_bh(dev);
8357 __dev_set_rx_mode(dev);
8358 netif_addr_unlock_bh(dev);
8362 * dev_get_flags - get flags reported to userspace
8365 * Get the combination of flag bits exported through APIs to userspace.
8367 unsigned int dev_get_flags(const struct net_device *dev)
8371 flags = (dev->flags & ~(IFF_PROMISC |
8376 (dev->gflags & (IFF_PROMISC |
8379 if (netif_running(dev)) {
8380 if (netif_oper_up(dev))
8381 flags |= IFF_RUNNING;
8382 if (netif_carrier_ok(dev))
8383 flags |= IFF_LOWER_UP;
8384 if (netif_dormant(dev))
8385 flags |= IFF_DORMANT;
8390 EXPORT_SYMBOL(dev_get_flags);
8392 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8393 struct netlink_ext_ack *extack)
8395 unsigned int old_flags = dev->flags;
8401 * Set the flags on our device.
8404 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8405 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8407 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8411 * Load in the correct multicast list now the flags have changed.
8414 if ((old_flags ^ flags) & IFF_MULTICAST)
8415 dev_change_rx_flags(dev, IFF_MULTICAST);
8417 dev_set_rx_mode(dev);
8420 * Have we downed the interface. We handle IFF_UP ourselves
8421 * according to user attempts to set it, rather than blindly
8426 if ((old_flags ^ flags) & IFF_UP) {
8427 if (old_flags & IFF_UP)
8430 ret = __dev_open(dev, extack);
8433 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8434 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8435 unsigned int old_flags = dev->flags;
8437 dev->gflags ^= IFF_PROMISC;
8439 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8440 if (dev->flags != old_flags)
8441 dev_set_rx_mode(dev);
8444 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8445 * is important. Some (broken) drivers set IFF_PROMISC, when
8446 * IFF_ALLMULTI is requested not asking us and not reporting.
8448 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8449 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8451 dev->gflags ^= IFF_ALLMULTI;
8452 __dev_set_allmulti(dev, inc, false);
8458 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8459 unsigned int gchanges)
8461 unsigned int changes = dev->flags ^ old_flags;
8464 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8466 if (changes & IFF_UP) {
8467 if (dev->flags & IFF_UP)
8468 call_netdevice_notifiers(NETDEV_UP, dev);
8470 call_netdevice_notifiers(NETDEV_DOWN, dev);
8473 if (dev->flags & IFF_UP &&
8474 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8475 struct netdev_notifier_change_info change_info = {
8479 .flags_changed = changes,
8482 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8487 * dev_change_flags - change device settings
8489 * @flags: device state flags
8490 * @extack: netlink extended ack
8492 * Change settings on device based state flags. The flags are
8493 * in the userspace exported format.
8495 int dev_change_flags(struct net_device *dev, unsigned int flags,
8496 struct netlink_ext_ack *extack)
8499 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8501 ret = __dev_change_flags(dev, flags, extack);
8505 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8506 __dev_notify_flags(dev, old_flags, changes);
8509 EXPORT_SYMBOL(dev_change_flags);
8511 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8513 const struct net_device_ops *ops = dev->netdev_ops;
8515 if (ops->ndo_change_mtu)
8516 return ops->ndo_change_mtu(dev, new_mtu);
8518 /* Pairs with all the lockless reads of dev->mtu in the stack */
8519 WRITE_ONCE(dev->mtu, new_mtu);
8522 EXPORT_SYMBOL(__dev_set_mtu);
8524 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8525 struct netlink_ext_ack *extack)
8527 /* MTU must be positive, and in range */
8528 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8529 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8533 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8534 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8541 * dev_set_mtu_ext - Change maximum transfer unit
8543 * @new_mtu: new transfer unit
8544 * @extack: netlink extended ack
8546 * Change the maximum transfer size of the network device.
8548 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8549 struct netlink_ext_ack *extack)
8553 if (new_mtu == dev->mtu)
8556 err = dev_validate_mtu(dev, new_mtu, extack);
8560 if (!netif_device_present(dev))
8563 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8564 err = notifier_to_errno(err);
8568 orig_mtu = dev->mtu;
8569 err = __dev_set_mtu(dev, new_mtu);
8572 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8574 err = notifier_to_errno(err);
8576 /* setting mtu back and notifying everyone again,
8577 * so that they have a chance to revert changes.
8579 __dev_set_mtu(dev, orig_mtu);
8580 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8587 int dev_set_mtu(struct net_device *dev, int new_mtu)
8589 struct netlink_ext_ack extack;
8592 memset(&extack, 0, sizeof(extack));
8593 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8594 if (err && extack._msg)
8595 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8598 EXPORT_SYMBOL(dev_set_mtu);
8601 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8603 * @new_len: new tx queue length
8605 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8607 unsigned int orig_len = dev->tx_queue_len;
8610 if (new_len != (unsigned int)new_len)
8613 if (new_len != orig_len) {
8614 dev->tx_queue_len = new_len;
8615 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8616 res = notifier_to_errno(res);
8619 res = dev_qdisc_change_tx_queue_len(dev);
8627 netdev_err(dev, "refused to change device tx_queue_len\n");
8628 dev->tx_queue_len = orig_len;
8633 * dev_set_group - Change group this device belongs to
8635 * @new_group: group this device should belong to
8637 void dev_set_group(struct net_device *dev, int new_group)
8639 dev->group = new_group;
8641 EXPORT_SYMBOL(dev_set_group);
8644 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8646 * @addr: new address
8647 * @extack: netlink extended ack
8649 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8650 struct netlink_ext_ack *extack)
8652 struct netdev_notifier_pre_changeaddr_info info = {
8654 .info.extack = extack,
8659 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8660 return notifier_to_errno(rc);
8662 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8665 * dev_set_mac_address - Change Media Access Control Address
8668 * @extack: netlink extended ack
8670 * Change the hardware (MAC) address of the device
8672 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8673 struct netlink_ext_ack *extack)
8675 const struct net_device_ops *ops = dev->netdev_ops;
8678 if (!ops->ndo_set_mac_address)
8680 if (sa->sa_family != dev->type)
8682 if (!netif_device_present(dev))
8684 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8687 err = ops->ndo_set_mac_address(dev, sa);
8690 dev->addr_assign_type = NET_ADDR_SET;
8691 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8692 add_device_randomness(dev->dev_addr, dev->addr_len);
8695 EXPORT_SYMBOL(dev_set_mac_address);
8697 static DECLARE_RWSEM(dev_addr_sem);
8699 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8700 struct netlink_ext_ack *extack)
8704 down_write(&dev_addr_sem);
8705 ret = dev_set_mac_address(dev, sa, extack);
8706 up_write(&dev_addr_sem);
8709 EXPORT_SYMBOL(dev_set_mac_address_user);
8711 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8713 size_t size = sizeof(sa->sa_data);
8714 struct net_device *dev;
8717 down_read(&dev_addr_sem);
8720 dev = dev_get_by_name_rcu(net, dev_name);
8726 memset(sa->sa_data, 0, size);
8728 memcpy(sa->sa_data, dev->dev_addr,
8729 min_t(size_t, size, dev->addr_len));
8730 sa->sa_family = dev->type;
8734 up_read(&dev_addr_sem);
8737 EXPORT_SYMBOL(dev_get_mac_address);
8740 * dev_change_carrier - Change device carrier
8742 * @new_carrier: new value
8744 * Change device carrier
8746 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8748 const struct net_device_ops *ops = dev->netdev_ops;
8750 if (!ops->ndo_change_carrier)
8752 if (!netif_device_present(dev))
8754 return ops->ndo_change_carrier(dev, new_carrier);
8756 EXPORT_SYMBOL(dev_change_carrier);
8759 * dev_get_phys_port_id - Get device physical port ID
8763 * Get device physical port ID
8765 int dev_get_phys_port_id(struct net_device *dev,
8766 struct netdev_phys_item_id *ppid)
8768 const struct net_device_ops *ops = dev->netdev_ops;
8770 if (!ops->ndo_get_phys_port_id)
8772 return ops->ndo_get_phys_port_id(dev, ppid);
8774 EXPORT_SYMBOL(dev_get_phys_port_id);
8777 * dev_get_phys_port_name - Get device physical port name
8780 * @len: limit of bytes to copy to name
8782 * Get device physical port name
8784 int dev_get_phys_port_name(struct net_device *dev,
8785 char *name, size_t len)
8787 const struct net_device_ops *ops = dev->netdev_ops;
8790 if (ops->ndo_get_phys_port_name) {
8791 err = ops->ndo_get_phys_port_name(dev, name, len);
8792 if (err != -EOPNOTSUPP)
8795 return devlink_compat_phys_port_name_get(dev, name, len);
8797 EXPORT_SYMBOL(dev_get_phys_port_name);
8800 * dev_get_port_parent_id - Get the device's port parent identifier
8801 * @dev: network device
8802 * @ppid: pointer to a storage for the port's parent identifier
8803 * @recurse: allow/disallow recursion to lower devices
8805 * Get the devices's port parent identifier
8807 int dev_get_port_parent_id(struct net_device *dev,
8808 struct netdev_phys_item_id *ppid,
8811 const struct net_device_ops *ops = dev->netdev_ops;
8812 struct netdev_phys_item_id first = { };
8813 struct net_device *lower_dev;
8814 struct list_head *iter;
8817 if (ops->ndo_get_port_parent_id) {
8818 err = ops->ndo_get_port_parent_id(dev, ppid);
8819 if (err != -EOPNOTSUPP)
8823 err = devlink_compat_switch_id_get(dev, ppid);
8824 if (!recurse || err != -EOPNOTSUPP)
8827 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8828 err = dev_get_port_parent_id(lower_dev, ppid, true);
8833 else if (memcmp(&first, ppid, sizeof(*ppid)))
8839 EXPORT_SYMBOL(dev_get_port_parent_id);
8842 * netdev_port_same_parent_id - Indicate if two network devices have
8843 * the same port parent identifier
8844 * @a: first network device
8845 * @b: second network device
8847 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8849 struct netdev_phys_item_id a_id = { };
8850 struct netdev_phys_item_id b_id = { };
8852 if (dev_get_port_parent_id(a, &a_id, true) ||
8853 dev_get_port_parent_id(b, &b_id, true))
8856 return netdev_phys_item_id_same(&a_id, &b_id);
8858 EXPORT_SYMBOL(netdev_port_same_parent_id);
8861 * dev_change_proto_down - set carrier according to proto_down.
8864 * @proto_down: new value
8866 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8868 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
8870 if (!netif_device_present(dev))
8873 netif_carrier_off(dev);
8875 netif_carrier_on(dev);
8876 dev->proto_down = proto_down;
8879 EXPORT_SYMBOL(dev_change_proto_down);
8882 * dev_change_proto_down_reason - proto down reason
8885 * @mask: proto down mask
8886 * @value: proto down value
8888 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8894 dev->proto_down_reason = value;
8896 for_each_set_bit(b, &mask, 32) {
8897 if (value & (1 << b))
8898 dev->proto_down_reason |= BIT(b);
8900 dev->proto_down_reason &= ~BIT(b);
8904 EXPORT_SYMBOL(dev_change_proto_down_reason);
8906 struct bpf_xdp_link {
8907 struct bpf_link link;
8908 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8912 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8914 if (flags & XDP_FLAGS_HW_MODE)
8916 if (flags & XDP_FLAGS_DRV_MODE)
8917 return XDP_MODE_DRV;
8918 if (flags & XDP_FLAGS_SKB_MODE)
8919 return XDP_MODE_SKB;
8920 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
8923 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
8927 return generic_xdp_install;
8930 return dev->netdev_ops->ndo_bpf;
8936 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
8937 enum bpf_xdp_mode mode)
8939 return dev->xdp_state[mode].link;
8942 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
8943 enum bpf_xdp_mode mode)
8945 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
8948 return link->link.prog;
8949 return dev->xdp_state[mode].prog;
8952 u8 dev_xdp_prog_count(struct net_device *dev)
8957 for (i = 0; i < __MAX_XDP_MODE; i++)
8958 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
8962 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
8964 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
8966 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
8968 return prog ? prog->aux->id : 0;
8971 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
8972 struct bpf_xdp_link *link)
8974 dev->xdp_state[mode].link = link;
8975 dev->xdp_state[mode].prog = NULL;
8978 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
8979 struct bpf_prog *prog)
8981 dev->xdp_state[mode].link = NULL;
8982 dev->xdp_state[mode].prog = prog;
8985 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
8986 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
8987 u32 flags, struct bpf_prog *prog)
8989 struct netdev_bpf xdp;
8992 memset(&xdp, 0, sizeof(xdp));
8993 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
8994 xdp.extack = extack;
8998 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
8999 * "moved" into driver), so they don't increment it on their own, but
9000 * they do decrement refcnt when program is detached or replaced.
9001 * Given net_device also owns link/prog, we need to bump refcnt here
9002 * to prevent drivers from underflowing it.
9006 err = bpf_op(dev, &xdp);
9013 if (mode != XDP_MODE_HW)
9014 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9019 static void dev_xdp_uninstall(struct net_device *dev)
9021 struct bpf_xdp_link *link;
9022 struct bpf_prog *prog;
9023 enum bpf_xdp_mode mode;
9028 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9029 prog = dev_xdp_prog(dev, mode);
9033 bpf_op = dev_xdp_bpf_op(dev, mode);
9037 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9039 /* auto-detach link from net device */
9040 link = dev_xdp_link(dev, mode);
9046 dev_xdp_set_link(dev, mode, NULL);
9050 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9051 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9052 struct bpf_prog *old_prog, u32 flags)
9054 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9055 struct bpf_prog *cur_prog;
9056 struct net_device *upper;
9057 struct list_head *iter;
9058 enum bpf_xdp_mode mode;
9064 /* either link or prog attachment, never both */
9065 if (link && (new_prog || old_prog))
9067 /* link supports only XDP mode flags */
9068 if (link && (flags & ~XDP_FLAGS_MODES)) {
9069 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9072 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9073 if (num_modes > 1) {
9074 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9077 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9078 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9079 NL_SET_ERR_MSG(extack,
9080 "More than one program loaded, unset mode is ambiguous");
9083 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9084 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9085 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9089 mode = dev_xdp_mode(dev, flags);
9090 /* can't replace attached link */
9091 if (dev_xdp_link(dev, mode)) {
9092 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9096 /* don't allow if an upper device already has a program */
9097 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9098 if (dev_xdp_prog_count(upper) > 0) {
9099 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9104 cur_prog = dev_xdp_prog(dev, mode);
9105 /* can't replace attached prog with link */
9106 if (link && cur_prog) {
9107 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9110 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9111 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9115 /* put effective new program into new_prog */
9117 new_prog = link->link.prog;
9120 bool offload = mode == XDP_MODE_HW;
9121 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9122 ? XDP_MODE_DRV : XDP_MODE_SKB;
9124 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9125 NL_SET_ERR_MSG(extack, "XDP program already attached");
9128 if (!offload && dev_xdp_prog(dev, other_mode)) {
9129 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9132 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
9133 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
9136 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9137 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9140 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9141 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9146 /* don't call drivers if the effective program didn't change */
9147 if (new_prog != cur_prog) {
9148 bpf_op = dev_xdp_bpf_op(dev, mode);
9150 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9154 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9160 dev_xdp_set_link(dev, mode, link);
9162 dev_xdp_set_prog(dev, mode, new_prog);
9164 bpf_prog_put(cur_prog);
9169 static int dev_xdp_attach_link(struct net_device *dev,
9170 struct netlink_ext_ack *extack,
9171 struct bpf_xdp_link *link)
9173 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9176 static int dev_xdp_detach_link(struct net_device *dev,
9177 struct netlink_ext_ack *extack,
9178 struct bpf_xdp_link *link)
9180 enum bpf_xdp_mode mode;
9185 mode = dev_xdp_mode(dev, link->flags);
9186 if (dev_xdp_link(dev, mode) != link)
9189 bpf_op = dev_xdp_bpf_op(dev, mode);
9190 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9191 dev_xdp_set_link(dev, mode, NULL);
9195 static void bpf_xdp_link_release(struct bpf_link *link)
9197 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9201 /* if racing with net_device's tear down, xdp_link->dev might be
9202 * already NULL, in which case link was already auto-detached
9204 if (xdp_link->dev) {
9205 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9206 xdp_link->dev = NULL;
9212 static int bpf_xdp_link_detach(struct bpf_link *link)
9214 bpf_xdp_link_release(link);
9218 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9220 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9225 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9226 struct seq_file *seq)
9228 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9233 ifindex = xdp_link->dev->ifindex;
9236 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9239 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9240 struct bpf_link_info *info)
9242 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9247 ifindex = xdp_link->dev->ifindex;
9250 info->xdp.ifindex = ifindex;
9254 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9255 struct bpf_prog *old_prog)
9257 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9258 enum bpf_xdp_mode mode;
9264 /* link might have been auto-released already, so fail */
9265 if (!xdp_link->dev) {
9270 if (old_prog && link->prog != old_prog) {
9274 old_prog = link->prog;
9275 if (old_prog->type != new_prog->type ||
9276 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9281 if (old_prog == new_prog) {
9282 /* no-op, don't disturb drivers */
9283 bpf_prog_put(new_prog);
9287 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9288 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9289 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9290 xdp_link->flags, new_prog);
9294 old_prog = xchg(&link->prog, new_prog);
9295 bpf_prog_put(old_prog);
9302 static const struct bpf_link_ops bpf_xdp_link_lops = {
9303 .release = bpf_xdp_link_release,
9304 .dealloc = bpf_xdp_link_dealloc,
9305 .detach = bpf_xdp_link_detach,
9306 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9307 .fill_link_info = bpf_xdp_link_fill_link_info,
9308 .update_prog = bpf_xdp_link_update,
9311 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9313 struct net *net = current->nsproxy->net_ns;
9314 struct bpf_link_primer link_primer;
9315 struct bpf_xdp_link *link;
9316 struct net_device *dev;
9320 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9326 link = kzalloc(sizeof(*link), GFP_USER);
9332 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9334 link->flags = attr->link_create.flags;
9336 err = bpf_link_prime(&link->link, &link_primer);
9342 err = dev_xdp_attach_link(dev, NULL, link);
9347 bpf_link_cleanup(&link_primer);
9351 fd = bpf_link_settle(&link_primer);
9352 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9365 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9367 * @extack: netlink extended ack
9368 * @fd: new program fd or negative value to clear
9369 * @expected_fd: old program fd that userspace expects to replace or clear
9370 * @flags: xdp-related flags
9372 * Set or clear a bpf program for a device
9374 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9375 int fd, int expected_fd, u32 flags)
9377 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9378 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9384 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9385 mode != XDP_MODE_SKB);
9386 if (IS_ERR(new_prog))
9387 return PTR_ERR(new_prog);
9390 if (expected_fd >= 0) {
9391 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9392 mode != XDP_MODE_SKB);
9393 if (IS_ERR(old_prog)) {
9394 err = PTR_ERR(old_prog);
9400 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9403 if (err && new_prog)
9404 bpf_prog_put(new_prog);
9406 bpf_prog_put(old_prog);
9411 * dev_new_index - allocate an ifindex
9412 * @net: the applicable net namespace
9414 * Returns a suitable unique value for a new device interface
9415 * number. The caller must hold the rtnl semaphore or the
9416 * dev_base_lock to be sure it remains unique.
9418 static int dev_new_index(struct net *net)
9420 int ifindex = net->ifindex;
9425 if (!__dev_get_by_index(net, ifindex))
9426 return net->ifindex = ifindex;
9430 /* Delayed registration/unregisteration */
9431 static LIST_HEAD(net_todo_list);
9432 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9434 static void net_set_todo(struct net_device *dev)
9436 list_add_tail(&dev->todo_list, &net_todo_list);
9437 atomic_inc(&dev_net(dev)->dev_unreg_count);
9440 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9441 struct net_device *upper, netdev_features_t features)
9443 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9444 netdev_features_t feature;
9447 for_each_netdev_feature(upper_disables, feature_bit) {
9448 feature = __NETIF_F_BIT(feature_bit);
9449 if (!(upper->wanted_features & feature)
9450 && (features & feature)) {
9451 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9452 &feature, upper->name);
9453 features &= ~feature;
9460 static void netdev_sync_lower_features(struct net_device *upper,
9461 struct net_device *lower, netdev_features_t features)
9463 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9464 netdev_features_t feature;
9467 for_each_netdev_feature(upper_disables, feature_bit) {
9468 feature = __NETIF_F_BIT(feature_bit);
9469 if (!(features & feature) && (lower->features & feature)) {
9470 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9471 &feature, lower->name);
9472 lower->wanted_features &= ~feature;
9473 __netdev_update_features(lower);
9475 if (unlikely(lower->features & feature))
9476 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9477 &feature, lower->name);
9479 netdev_features_change(lower);
9484 static netdev_features_t netdev_fix_features(struct net_device *dev,
9485 netdev_features_t features)
9487 /* Fix illegal checksum combinations */
9488 if ((features & NETIF_F_HW_CSUM) &&
9489 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9490 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9491 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9494 /* TSO requires that SG is present as well. */
9495 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9496 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9497 features &= ~NETIF_F_ALL_TSO;
9500 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9501 !(features & NETIF_F_IP_CSUM)) {
9502 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9503 features &= ~NETIF_F_TSO;
9504 features &= ~NETIF_F_TSO_ECN;
9507 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9508 !(features & NETIF_F_IPV6_CSUM)) {
9509 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9510 features &= ~NETIF_F_TSO6;
9513 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9514 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9515 features &= ~NETIF_F_TSO_MANGLEID;
9517 /* TSO ECN requires that TSO is present as well. */
9518 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9519 features &= ~NETIF_F_TSO_ECN;
9521 /* Software GSO depends on SG. */
9522 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9523 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9524 features &= ~NETIF_F_GSO;
9527 /* GSO partial features require GSO partial be set */
9528 if ((features & dev->gso_partial_features) &&
9529 !(features & NETIF_F_GSO_PARTIAL)) {
9531 "Dropping partially supported GSO features since no GSO partial.\n");
9532 features &= ~dev->gso_partial_features;
9535 if (!(features & NETIF_F_RXCSUM)) {
9536 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9537 * successfully merged by hardware must also have the
9538 * checksum verified by hardware. If the user does not
9539 * want to enable RXCSUM, logically, we should disable GRO_HW.
9541 if (features & NETIF_F_GRO_HW) {
9542 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9543 features &= ~NETIF_F_GRO_HW;
9547 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9548 if (features & NETIF_F_RXFCS) {
9549 if (features & NETIF_F_LRO) {
9550 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9551 features &= ~NETIF_F_LRO;
9554 if (features & NETIF_F_GRO_HW) {
9555 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9556 features &= ~NETIF_F_GRO_HW;
9560 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9561 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9562 features &= ~NETIF_F_LRO;
9565 if (features & NETIF_F_HW_TLS_TX) {
9566 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9567 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9568 bool hw_csum = features & NETIF_F_HW_CSUM;
9570 if (!ip_csum && !hw_csum) {
9571 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9572 features &= ~NETIF_F_HW_TLS_TX;
9576 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9577 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9578 features &= ~NETIF_F_HW_TLS_RX;
9584 int __netdev_update_features(struct net_device *dev)
9586 struct net_device *upper, *lower;
9587 netdev_features_t features;
9588 struct list_head *iter;
9593 features = netdev_get_wanted_features(dev);
9595 if (dev->netdev_ops->ndo_fix_features)
9596 features = dev->netdev_ops->ndo_fix_features(dev, features);
9598 /* driver might be less strict about feature dependencies */
9599 features = netdev_fix_features(dev, features);
9601 /* some features can't be enabled if they're off on an upper device */
9602 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9603 features = netdev_sync_upper_features(dev, upper, features);
9605 if (dev->features == features)
9608 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9609 &dev->features, &features);
9611 if (dev->netdev_ops->ndo_set_features)
9612 err = dev->netdev_ops->ndo_set_features(dev, features);
9616 if (unlikely(err < 0)) {
9618 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9619 err, &features, &dev->features);
9620 /* return non-0 since some features might have changed and
9621 * it's better to fire a spurious notification than miss it
9627 /* some features must be disabled on lower devices when disabled
9628 * on an upper device (think: bonding master or bridge)
9630 netdev_for_each_lower_dev(dev, lower, iter)
9631 netdev_sync_lower_features(dev, lower, features);
9634 netdev_features_t diff = features ^ dev->features;
9636 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9637 /* udp_tunnel_{get,drop}_rx_info both need
9638 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9639 * device, or they won't do anything.
9640 * Thus we need to update dev->features
9641 * *before* calling udp_tunnel_get_rx_info,
9642 * but *after* calling udp_tunnel_drop_rx_info.
9644 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9645 dev->features = features;
9646 udp_tunnel_get_rx_info(dev);
9648 udp_tunnel_drop_rx_info(dev);
9652 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9653 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9654 dev->features = features;
9655 err |= vlan_get_rx_ctag_filter_info(dev);
9657 vlan_drop_rx_ctag_filter_info(dev);
9661 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9662 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9663 dev->features = features;
9664 err |= vlan_get_rx_stag_filter_info(dev);
9666 vlan_drop_rx_stag_filter_info(dev);
9670 dev->features = features;
9673 return err < 0 ? 0 : 1;
9677 * netdev_update_features - recalculate device features
9678 * @dev: the device to check
9680 * Recalculate dev->features set and send notifications if it
9681 * has changed. Should be called after driver or hardware dependent
9682 * conditions might have changed that influence the features.
9684 void netdev_update_features(struct net_device *dev)
9686 if (__netdev_update_features(dev))
9687 netdev_features_change(dev);
9689 EXPORT_SYMBOL(netdev_update_features);
9692 * netdev_change_features - recalculate device features
9693 * @dev: the device to check
9695 * Recalculate dev->features set and send notifications even
9696 * if they have not changed. Should be called instead of
9697 * netdev_update_features() if also dev->vlan_features might
9698 * have changed to allow the changes to be propagated to stacked
9701 void netdev_change_features(struct net_device *dev)
9703 __netdev_update_features(dev);
9704 netdev_features_change(dev);
9706 EXPORT_SYMBOL(netdev_change_features);
9709 * netif_stacked_transfer_operstate - transfer operstate
9710 * @rootdev: the root or lower level device to transfer state from
9711 * @dev: the device to transfer operstate to
9713 * Transfer operational state from root to device. This is normally
9714 * called when a stacking relationship exists between the root
9715 * device and the device(a leaf device).
9717 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9718 struct net_device *dev)
9720 if (rootdev->operstate == IF_OPER_DORMANT)
9721 netif_dormant_on(dev);
9723 netif_dormant_off(dev);
9725 if (rootdev->operstate == IF_OPER_TESTING)
9726 netif_testing_on(dev);
9728 netif_testing_off(dev);
9730 if (netif_carrier_ok(rootdev))
9731 netif_carrier_on(dev);
9733 netif_carrier_off(dev);
9735 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9737 static int netif_alloc_rx_queues(struct net_device *dev)
9739 unsigned int i, count = dev->num_rx_queues;
9740 struct netdev_rx_queue *rx;
9741 size_t sz = count * sizeof(*rx);
9746 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9752 for (i = 0; i < count; i++) {
9755 /* XDP RX-queue setup */
9756 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9763 /* Rollback successful reg's and free other resources */
9765 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9771 static void netif_free_rx_queues(struct net_device *dev)
9773 unsigned int i, count = dev->num_rx_queues;
9775 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9779 for (i = 0; i < count; i++)
9780 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9785 static void netdev_init_one_queue(struct net_device *dev,
9786 struct netdev_queue *queue, void *_unused)
9788 /* Initialize queue lock */
9789 spin_lock_init(&queue->_xmit_lock);
9790 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9791 queue->xmit_lock_owner = -1;
9792 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9795 dql_init(&queue->dql, HZ);
9799 static void netif_free_tx_queues(struct net_device *dev)
9804 static int netif_alloc_netdev_queues(struct net_device *dev)
9806 unsigned int count = dev->num_tx_queues;
9807 struct netdev_queue *tx;
9808 size_t sz = count * sizeof(*tx);
9810 if (count < 1 || count > 0xffff)
9813 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9819 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9820 spin_lock_init(&dev->tx_global_lock);
9825 void netif_tx_stop_all_queues(struct net_device *dev)
9829 for (i = 0; i < dev->num_tx_queues; i++) {
9830 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9832 netif_tx_stop_queue(txq);
9835 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9838 * register_netdevice - register a network device
9839 * @dev: device to register
9841 * Take a completed network device structure and add it to the kernel
9842 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9843 * chain. 0 is returned on success. A negative errno code is returned
9844 * on a failure to set up the device, or if the name is a duplicate.
9846 * Callers must hold the rtnl semaphore. You may want
9847 * register_netdev() instead of this.
9850 * The locking appears insufficient to guarantee two parallel registers
9851 * will not get the same name.
9854 int register_netdevice(struct net_device *dev)
9857 struct net *net = dev_net(dev);
9859 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9860 NETDEV_FEATURE_COUNT);
9861 BUG_ON(dev_boot_phase);
9866 /* When net_device's are persistent, this will be fatal. */
9867 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9870 ret = ethtool_check_ops(dev->ethtool_ops);
9874 spin_lock_init(&dev->addr_list_lock);
9875 netdev_set_addr_lockdep_class(dev);
9877 ret = dev_get_valid_name(net, dev, dev->name);
9882 dev->name_node = netdev_name_node_head_alloc(dev);
9883 if (!dev->name_node)
9886 /* Init, if this function is available */
9887 if (dev->netdev_ops->ndo_init) {
9888 ret = dev->netdev_ops->ndo_init(dev);
9896 if (((dev->hw_features | dev->features) &
9897 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9898 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9899 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9900 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
9907 dev->ifindex = dev_new_index(net);
9908 else if (__dev_get_by_index(net, dev->ifindex))
9911 /* Transfer changeable features to wanted_features and enable
9912 * software offloads (GSO and GRO).
9914 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
9915 dev->features |= NETIF_F_SOFT_FEATURES;
9917 if (dev->udp_tunnel_nic_info) {
9918 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9919 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9922 dev->wanted_features = dev->features & dev->hw_features;
9924 if (!(dev->flags & IFF_LOOPBACK))
9925 dev->hw_features |= NETIF_F_NOCACHE_COPY;
9927 /* If IPv4 TCP segmentation offload is supported we should also
9928 * allow the device to enable segmenting the frame with the option
9929 * of ignoring a static IP ID value. This doesn't enable the
9930 * feature itself but allows the user to enable it later.
9932 if (dev->hw_features & NETIF_F_TSO)
9933 dev->hw_features |= NETIF_F_TSO_MANGLEID;
9934 if (dev->vlan_features & NETIF_F_TSO)
9935 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
9936 if (dev->mpls_features & NETIF_F_TSO)
9937 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
9938 if (dev->hw_enc_features & NETIF_F_TSO)
9939 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9941 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
9943 dev->vlan_features |= NETIF_F_HIGHDMA;
9945 /* Make NETIF_F_SG inheritable to tunnel devices.
9947 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
9949 /* Make NETIF_F_SG inheritable to MPLS.
9951 dev->mpls_features |= NETIF_F_SG;
9953 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
9954 ret = notifier_to_errno(ret);
9958 ret = netdev_register_kobject(dev);
9960 dev->reg_state = NETREG_UNREGISTERED;
9963 dev->reg_state = NETREG_REGISTERED;
9965 __netdev_update_features(dev);
9968 * Default initial state at registry is that the
9969 * device is present.
9972 set_bit(__LINK_STATE_PRESENT, &dev->state);
9974 linkwatch_init_dev(dev);
9976 dev_init_scheduler(dev);
9978 dev_hold_track(dev, &dev->dev_registered_tracker, GFP_KERNEL);
9979 list_netdevice(dev);
9981 add_device_randomness(dev->dev_addr, dev->addr_len);
9983 /* If the device has permanent device address, driver should
9984 * set dev_addr and also addr_assign_type should be set to
9985 * NET_ADDR_PERM (default value).
9987 if (dev->addr_assign_type == NET_ADDR_PERM)
9988 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
9990 /* Notify protocols, that a new device appeared. */
9991 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
9992 ret = notifier_to_errno(ret);
9994 /* Expect explicit free_netdev() on failure */
9995 dev->needs_free_netdev = false;
9996 unregister_netdevice_queue(dev, NULL);
10000 * Prevent userspace races by waiting until the network
10001 * device is fully setup before sending notifications.
10003 if (!dev->rtnl_link_ops ||
10004 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10005 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10011 if (dev->netdev_ops->ndo_uninit)
10012 dev->netdev_ops->ndo_uninit(dev);
10013 if (dev->priv_destructor)
10014 dev->priv_destructor(dev);
10016 netdev_name_node_free(dev->name_node);
10019 EXPORT_SYMBOL(register_netdevice);
10022 * init_dummy_netdev - init a dummy network device for NAPI
10023 * @dev: device to init
10025 * This takes a network device structure and initialize the minimum
10026 * amount of fields so it can be used to schedule NAPI polls without
10027 * registering a full blown interface. This is to be used by drivers
10028 * that need to tie several hardware interfaces to a single NAPI
10029 * poll scheduler due to HW limitations.
10031 int init_dummy_netdev(struct net_device *dev)
10033 /* Clear everything. Note we don't initialize spinlocks
10034 * are they aren't supposed to be taken by any of the
10035 * NAPI code and this dummy netdev is supposed to be
10036 * only ever used for NAPI polls
10038 memset(dev, 0, sizeof(struct net_device));
10040 /* make sure we BUG if trying to hit standard
10041 * register/unregister code path
10043 dev->reg_state = NETREG_DUMMY;
10045 /* NAPI wants this */
10046 INIT_LIST_HEAD(&dev->napi_list);
10048 /* a dummy interface is started by default */
10049 set_bit(__LINK_STATE_PRESENT, &dev->state);
10050 set_bit(__LINK_STATE_START, &dev->state);
10052 /* napi_busy_loop stats accounting wants this */
10053 dev_net_set(dev, &init_net);
10055 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10056 * because users of this 'device' dont need to change
10062 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10066 * register_netdev - register a network device
10067 * @dev: device to register
10069 * Take a completed network device structure and add it to the kernel
10070 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10071 * chain. 0 is returned on success. A negative errno code is returned
10072 * on a failure to set up the device, or if the name is a duplicate.
10074 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10075 * and expands the device name if you passed a format string to
10078 int register_netdev(struct net_device *dev)
10082 if (rtnl_lock_killable())
10084 err = register_netdevice(dev);
10088 EXPORT_SYMBOL(register_netdev);
10090 int netdev_refcnt_read(const struct net_device *dev)
10092 #ifdef CONFIG_PCPU_DEV_REFCNT
10095 for_each_possible_cpu(i)
10096 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10099 return refcount_read(&dev->dev_refcnt);
10102 EXPORT_SYMBOL(netdev_refcnt_read);
10104 int netdev_unregister_timeout_secs __read_mostly = 10;
10106 #define WAIT_REFS_MIN_MSECS 1
10107 #define WAIT_REFS_MAX_MSECS 250
10109 * netdev_wait_allrefs_any - wait until all references are gone.
10110 * @list: list of net_devices to wait on
10112 * This is called when unregistering network devices.
10114 * Any protocol or device that holds a reference should register
10115 * for netdevice notification, and cleanup and put back the
10116 * reference if they receive an UNREGISTER event.
10117 * We can get stuck here if buggy protocols don't correctly
10120 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10122 unsigned long rebroadcast_time, warning_time;
10123 struct net_device *dev;
10126 rebroadcast_time = warning_time = jiffies;
10128 list_for_each_entry(dev, list, todo_list)
10129 if (netdev_refcnt_read(dev) == 1)
10133 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10136 /* Rebroadcast unregister notification */
10137 list_for_each_entry(dev, list, todo_list)
10138 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10144 list_for_each_entry(dev, list, todo_list)
10145 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10147 /* We must not have linkwatch events
10148 * pending on unregister. If this
10149 * happens, we simply run the queue
10150 * unscheduled, resulting in a noop
10153 linkwatch_run_queue();
10159 rebroadcast_time = jiffies;
10164 wait = WAIT_REFS_MIN_MSECS;
10167 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10170 list_for_each_entry(dev, list, todo_list)
10171 if (netdev_refcnt_read(dev) == 1)
10174 if (time_after(jiffies, warning_time +
10175 netdev_unregister_timeout_secs * HZ)) {
10176 list_for_each_entry(dev, list, todo_list) {
10177 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10178 dev->name, netdev_refcnt_read(dev));
10179 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10182 warning_time = jiffies;
10187 /* The sequence is:
10191 * register_netdevice(x1);
10192 * register_netdevice(x2);
10194 * unregister_netdevice(y1);
10195 * unregister_netdevice(y2);
10201 * We are invoked by rtnl_unlock().
10202 * This allows us to deal with problems:
10203 * 1) We can delete sysfs objects which invoke hotplug
10204 * without deadlocking with linkwatch via keventd.
10205 * 2) Since we run with the RTNL semaphore not held, we can sleep
10206 * safely in order to wait for the netdev refcnt to drop to zero.
10208 * We must not return until all unregister events added during
10209 * the interval the lock was held have been completed.
10211 void netdev_run_todo(void)
10213 struct net_device *dev, *tmp;
10214 struct list_head list;
10215 #ifdef CONFIG_LOCKDEP
10216 struct list_head unlink_list;
10218 list_replace_init(&net_unlink_list, &unlink_list);
10220 while (!list_empty(&unlink_list)) {
10221 struct net_device *dev = list_first_entry(&unlink_list,
10224 list_del_init(&dev->unlink_list);
10225 dev->nested_level = dev->lower_level - 1;
10229 /* Snapshot list, allow later requests */
10230 list_replace_init(&net_todo_list, &list);
10234 /* Wait for rcu callbacks to finish before next phase */
10235 if (!list_empty(&list))
10238 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10239 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10240 netdev_WARN(dev, "run_todo but not unregistering\n");
10241 list_del(&dev->todo_list);
10245 dev->reg_state = NETREG_UNREGISTERED;
10246 linkwatch_forget_dev(dev);
10249 while (!list_empty(&list)) {
10250 dev = netdev_wait_allrefs_any(&list);
10251 list_del(&dev->todo_list);
10254 BUG_ON(netdev_refcnt_read(dev) != 1);
10255 BUG_ON(!list_empty(&dev->ptype_all));
10256 BUG_ON(!list_empty(&dev->ptype_specific));
10257 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10258 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10259 #if IS_ENABLED(CONFIG_DECNET)
10260 WARN_ON(dev->dn_ptr);
10262 if (dev->priv_destructor)
10263 dev->priv_destructor(dev);
10264 if (dev->needs_free_netdev)
10267 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count))
10268 wake_up(&netdev_unregistering_wq);
10270 /* Free network device */
10271 kobject_put(&dev->dev.kobj);
10275 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10276 * all the same fields in the same order as net_device_stats, with only
10277 * the type differing, but rtnl_link_stats64 may have additional fields
10278 * at the end for newer counters.
10280 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10281 const struct net_device_stats *netdev_stats)
10283 #if BITS_PER_LONG == 64
10284 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
10285 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
10286 /* zero out counters that only exist in rtnl_link_stats64 */
10287 memset((char *)stats64 + sizeof(*netdev_stats), 0,
10288 sizeof(*stats64) - sizeof(*netdev_stats));
10290 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
10291 const unsigned long *src = (const unsigned long *)netdev_stats;
10292 u64 *dst = (u64 *)stats64;
10294 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10295 for (i = 0; i < n; i++)
10297 /* zero out counters that only exist in rtnl_link_stats64 */
10298 memset((char *)stats64 + n * sizeof(u64), 0,
10299 sizeof(*stats64) - n * sizeof(u64));
10302 EXPORT_SYMBOL(netdev_stats_to_stats64);
10304 struct net_device_core_stats __percpu *netdev_core_stats_alloc(struct net_device *dev)
10306 struct net_device_core_stats __percpu *p;
10308 p = alloc_percpu_gfp(struct net_device_core_stats,
10309 GFP_ATOMIC | __GFP_NOWARN);
10311 if (p && cmpxchg(&dev->core_stats, NULL, p))
10314 /* This READ_ONCE() pairs with the cmpxchg() above */
10315 return READ_ONCE(dev->core_stats);
10317 EXPORT_SYMBOL(netdev_core_stats_alloc);
10320 * dev_get_stats - get network device statistics
10321 * @dev: device to get statistics from
10322 * @storage: place to store stats
10324 * Get network statistics from device. Return @storage.
10325 * The device driver may provide its own method by setting
10326 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10327 * otherwise the internal statistics structure is used.
10329 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10330 struct rtnl_link_stats64 *storage)
10332 const struct net_device_ops *ops = dev->netdev_ops;
10333 const struct net_device_core_stats __percpu *p;
10335 if (ops->ndo_get_stats64) {
10336 memset(storage, 0, sizeof(*storage));
10337 ops->ndo_get_stats64(dev, storage);
10338 } else if (ops->ndo_get_stats) {
10339 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10341 netdev_stats_to_stats64(storage, &dev->stats);
10344 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10345 p = READ_ONCE(dev->core_stats);
10347 const struct net_device_core_stats *core_stats;
10350 for_each_possible_cpu(i) {
10351 core_stats = per_cpu_ptr(p, i);
10352 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10353 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10354 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10359 EXPORT_SYMBOL(dev_get_stats);
10362 * dev_fetch_sw_netstats - get per-cpu network device statistics
10363 * @s: place to store stats
10364 * @netstats: per-cpu network stats to read from
10366 * Read per-cpu network statistics and populate the related fields in @s.
10368 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10369 const struct pcpu_sw_netstats __percpu *netstats)
10373 for_each_possible_cpu(cpu) {
10374 const struct pcpu_sw_netstats *stats;
10375 struct pcpu_sw_netstats tmp;
10376 unsigned int start;
10378 stats = per_cpu_ptr(netstats, cpu);
10380 start = u64_stats_fetch_begin_irq(&stats->syncp);
10381 tmp.rx_packets = stats->rx_packets;
10382 tmp.rx_bytes = stats->rx_bytes;
10383 tmp.tx_packets = stats->tx_packets;
10384 tmp.tx_bytes = stats->tx_bytes;
10385 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
10387 s->rx_packets += tmp.rx_packets;
10388 s->rx_bytes += tmp.rx_bytes;
10389 s->tx_packets += tmp.tx_packets;
10390 s->tx_bytes += tmp.tx_bytes;
10393 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10396 * dev_get_tstats64 - ndo_get_stats64 implementation
10397 * @dev: device to get statistics from
10398 * @s: place to store stats
10400 * Populate @s from dev->stats and dev->tstats. Can be used as
10401 * ndo_get_stats64() callback.
10403 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10405 netdev_stats_to_stats64(s, &dev->stats);
10406 dev_fetch_sw_netstats(s, dev->tstats);
10408 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10410 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10412 struct netdev_queue *queue = dev_ingress_queue(dev);
10414 #ifdef CONFIG_NET_CLS_ACT
10417 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10420 netdev_init_one_queue(dev, queue, NULL);
10421 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10422 queue->qdisc_sleeping = &noop_qdisc;
10423 rcu_assign_pointer(dev->ingress_queue, queue);
10428 static const struct ethtool_ops default_ethtool_ops;
10430 void netdev_set_default_ethtool_ops(struct net_device *dev,
10431 const struct ethtool_ops *ops)
10433 if (dev->ethtool_ops == &default_ethtool_ops)
10434 dev->ethtool_ops = ops;
10436 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10438 void netdev_freemem(struct net_device *dev)
10440 char *addr = (char *)dev - dev->padded;
10446 * alloc_netdev_mqs - allocate network device
10447 * @sizeof_priv: size of private data to allocate space for
10448 * @name: device name format string
10449 * @name_assign_type: origin of device name
10450 * @setup: callback to initialize device
10451 * @txqs: the number of TX subqueues to allocate
10452 * @rxqs: the number of RX subqueues to allocate
10454 * Allocates a struct net_device with private data area for driver use
10455 * and performs basic initialization. Also allocates subqueue structs
10456 * for each queue on the device.
10458 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10459 unsigned char name_assign_type,
10460 void (*setup)(struct net_device *),
10461 unsigned int txqs, unsigned int rxqs)
10463 struct net_device *dev;
10464 unsigned int alloc_size;
10465 struct net_device *p;
10467 BUG_ON(strlen(name) >= sizeof(dev->name));
10470 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10475 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10479 alloc_size = sizeof(struct net_device);
10481 /* ensure 32-byte alignment of private area */
10482 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10483 alloc_size += sizeof_priv;
10485 /* ensure 32-byte alignment of whole construct */
10486 alloc_size += NETDEV_ALIGN - 1;
10488 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10492 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10493 dev->padded = (char *)dev - (char *)p;
10495 ref_tracker_dir_init(&dev->refcnt_tracker, 128);
10496 #ifdef CONFIG_PCPU_DEV_REFCNT
10497 dev->pcpu_refcnt = alloc_percpu(int);
10498 if (!dev->pcpu_refcnt)
10502 refcount_set(&dev->dev_refcnt, 1);
10505 if (dev_addr_init(dev))
10511 dev_net_set(dev, &init_net);
10513 dev->gso_max_size = GSO_MAX_SIZE;
10514 dev->gso_max_segs = GSO_MAX_SEGS;
10515 dev->gro_max_size = GRO_MAX_SIZE;
10516 dev->upper_level = 1;
10517 dev->lower_level = 1;
10518 #ifdef CONFIG_LOCKDEP
10519 dev->nested_level = 0;
10520 INIT_LIST_HEAD(&dev->unlink_list);
10523 INIT_LIST_HEAD(&dev->napi_list);
10524 INIT_LIST_HEAD(&dev->unreg_list);
10525 INIT_LIST_HEAD(&dev->close_list);
10526 INIT_LIST_HEAD(&dev->link_watch_list);
10527 INIT_LIST_HEAD(&dev->adj_list.upper);
10528 INIT_LIST_HEAD(&dev->adj_list.lower);
10529 INIT_LIST_HEAD(&dev->ptype_all);
10530 INIT_LIST_HEAD(&dev->ptype_specific);
10531 INIT_LIST_HEAD(&dev->net_notifier_list);
10532 #ifdef CONFIG_NET_SCHED
10533 hash_init(dev->qdisc_hash);
10535 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10538 if (!dev->tx_queue_len) {
10539 dev->priv_flags |= IFF_NO_QUEUE;
10540 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10543 dev->num_tx_queues = txqs;
10544 dev->real_num_tx_queues = txqs;
10545 if (netif_alloc_netdev_queues(dev))
10548 dev->num_rx_queues = rxqs;
10549 dev->real_num_rx_queues = rxqs;
10550 if (netif_alloc_rx_queues(dev))
10553 strcpy(dev->name, name);
10554 dev->name_assign_type = name_assign_type;
10555 dev->group = INIT_NETDEV_GROUP;
10556 if (!dev->ethtool_ops)
10557 dev->ethtool_ops = &default_ethtool_ops;
10559 nf_hook_netdev_init(dev);
10568 #ifdef CONFIG_PCPU_DEV_REFCNT
10569 free_percpu(dev->pcpu_refcnt);
10572 netdev_freemem(dev);
10575 EXPORT_SYMBOL(alloc_netdev_mqs);
10578 * free_netdev - free network device
10581 * This function does the last stage of destroying an allocated device
10582 * interface. The reference to the device object is released. If this
10583 * is the last reference then it will be freed.Must be called in process
10586 void free_netdev(struct net_device *dev)
10588 struct napi_struct *p, *n;
10592 /* When called immediately after register_netdevice() failed the unwind
10593 * handling may still be dismantling the device. Handle that case by
10594 * deferring the free.
10596 if (dev->reg_state == NETREG_UNREGISTERING) {
10598 dev->needs_free_netdev = true;
10602 netif_free_tx_queues(dev);
10603 netif_free_rx_queues(dev);
10605 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10607 /* Flush device addresses */
10608 dev_addr_flush(dev);
10610 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10613 ref_tracker_dir_exit(&dev->refcnt_tracker);
10614 #ifdef CONFIG_PCPU_DEV_REFCNT
10615 free_percpu(dev->pcpu_refcnt);
10616 dev->pcpu_refcnt = NULL;
10618 free_percpu(dev->core_stats);
10619 dev->core_stats = NULL;
10620 free_percpu(dev->xdp_bulkq);
10621 dev->xdp_bulkq = NULL;
10623 /* Compatibility with error handling in drivers */
10624 if (dev->reg_state == NETREG_UNINITIALIZED) {
10625 netdev_freemem(dev);
10629 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10630 dev->reg_state = NETREG_RELEASED;
10632 /* will free via device release */
10633 put_device(&dev->dev);
10635 EXPORT_SYMBOL(free_netdev);
10638 * synchronize_net - Synchronize with packet receive processing
10640 * Wait for packets currently being received to be done.
10641 * Does not block later packets from starting.
10643 void synchronize_net(void)
10646 if (rtnl_is_locked())
10647 synchronize_rcu_expedited();
10651 EXPORT_SYMBOL(synchronize_net);
10654 * unregister_netdevice_queue - remove device from the kernel
10658 * This function shuts down a device interface and removes it
10659 * from the kernel tables.
10660 * If head not NULL, device is queued to be unregistered later.
10662 * Callers must hold the rtnl semaphore. You may want
10663 * unregister_netdev() instead of this.
10666 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10671 list_move_tail(&dev->unreg_list, head);
10675 list_add(&dev->unreg_list, &single);
10676 unregister_netdevice_many(&single);
10679 EXPORT_SYMBOL(unregister_netdevice_queue);
10682 * unregister_netdevice_many - unregister many devices
10683 * @head: list of devices
10685 * Note: As most callers use a stack allocated list_head,
10686 * we force a list_del() to make sure stack wont be corrupted later.
10688 void unregister_netdevice_many(struct list_head *head)
10690 struct net_device *dev, *tmp;
10691 LIST_HEAD(close_head);
10693 BUG_ON(dev_boot_phase);
10696 if (list_empty(head))
10699 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10700 /* Some devices call without registering
10701 * for initialization unwind. Remove those
10702 * devices and proceed with the remaining.
10704 if (dev->reg_state == NETREG_UNINITIALIZED) {
10705 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10709 list_del(&dev->unreg_list);
10712 dev->dismantle = true;
10713 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10716 /* If device is running, close it first. */
10717 list_for_each_entry(dev, head, unreg_list)
10718 list_add_tail(&dev->close_list, &close_head);
10719 dev_close_many(&close_head, true);
10721 list_for_each_entry(dev, head, unreg_list) {
10722 /* And unlink it from device chain. */
10723 unlist_netdevice(dev);
10725 dev->reg_state = NETREG_UNREGISTERING;
10727 flush_all_backlogs();
10731 list_for_each_entry(dev, head, unreg_list) {
10732 struct sk_buff *skb = NULL;
10734 /* Shutdown queueing discipline. */
10737 dev_xdp_uninstall(dev);
10739 netdev_offload_xstats_disable_all(dev);
10741 /* Notify protocols, that we are about to destroy
10742 * this device. They should clean all the things.
10744 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10746 if (!dev->rtnl_link_ops ||
10747 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10748 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10749 GFP_KERNEL, NULL, 0);
10752 * Flush the unicast and multicast chains
10757 netdev_name_node_alt_flush(dev);
10758 netdev_name_node_free(dev->name_node);
10760 if (dev->netdev_ops->ndo_uninit)
10761 dev->netdev_ops->ndo_uninit(dev);
10764 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
10766 /* Notifier chain MUST detach us all upper devices. */
10767 WARN_ON(netdev_has_any_upper_dev(dev));
10768 WARN_ON(netdev_has_any_lower_dev(dev));
10770 /* Remove entries from kobject tree */
10771 netdev_unregister_kobject(dev);
10773 /* Remove XPS queueing entries */
10774 netif_reset_xps_queues_gt(dev, 0);
10780 list_for_each_entry(dev, head, unreg_list) {
10781 dev_put_track(dev, &dev->dev_registered_tracker);
10787 EXPORT_SYMBOL(unregister_netdevice_many);
10790 * unregister_netdev - remove device from the kernel
10793 * This function shuts down a device interface and removes it
10794 * from the kernel tables.
10796 * This is just a wrapper for unregister_netdevice that takes
10797 * the rtnl semaphore. In general you want to use this and not
10798 * unregister_netdevice.
10800 void unregister_netdev(struct net_device *dev)
10803 unregister_netdevice(dev);
10806 EXPORT_SYMBOL(unregister_netdev);
10809 * __dev_change_net_namespace - move device to different nethost namespace
10811 * @net: network namespace
10812 * @pat: If not NULL name pattern to try if the current device name
10813 * is already taken in the destination network namespace.
10814 * @new_ifindex: If not zero, specifies device index in the target
10817 * This function shuts down a device interface and moves it
10818 * to a new network namespace. On success 0 is returned, on
10819 * a failure a netagive errno code is returned.
10821 * Callers must hold the rtnl semaphore.
10824 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
10825 const char *pat, int new_ifindex)
10827 struct net *net_old = dev_net(dev);
10832 /* Don't allow namespace local devices to be moved. */
10834 if (dev->features & NETIF_F_NETNS_LOCAL)
10837 /* Ensure the device has been registrered */
10838 if (dev->reg_state != NETREG_REGISTERED)
10841 /* Get out if there is nothing todo */
10843 if (net_eq(net_old, net))
10846 /* Pick the destination device name, and ensure
10847 * we can use it in the destination network namespace.
10850 if (netdev_name_in_use(net, dev->name)) {
10851 /* We get here if we can't use the current device name */
10854 err = dev_get_valid_name(net, dev, pat);
10859 /* Check that new_ifindex isn't used yet. */
10861 if (new_ifindex && __dev_get_by_index(net, new_ifindex))
10865 * And now a mini version of register_netdevice unregister_netdevice.
10868 /* If device is running close it first. */
10871 /* And unlink it from device chain */
10872 unlist_netdevice(dev);
10876 /* Shutdown queueing discipline. */
10879 /* Notify protocols, that we are about to destroy
10880 * this device. They should clean all the things.
10882 * Note that dev->reg_state stays at NETREG_REGISTERED.
10883 * This is wanted because this way 8021q and macvlan know
10884 * the device is just moving and can keep their slaves up.
10886 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10889 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10890 /* If there is an ifindex conflict assign a new one */
10891 if (!new_ifindex) {
10892 if (__dev_get_by_index(net, dev->ifindex))
10893 new_ifindex = dev_new_index(net);
10895 new_ifindex = dev->ifindex;
10898 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10902 * Flush the unicast and multicast chains
10907 /* Send a netdev-removed uevent to the old namespace */
10908 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10909 netdev_adjacent_del_links(dev);
10911 /* Move per-net netdevice notifiers that are following the netdevice */
10912 move_netdevice_notifiers_dev_net(dev, net);
10914 /* Actually switch the network namespace */
10915 dev_net_set(dev, net);
10916 dev->ifindex = new_ifindex;
10918 /* Send a netdev-add uevent to the new namespace */
10919 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10920 netdev_adjacent_add_links(dev);
10922 /* Fixup kobjects */
10923 err = device_rename(&dev->dev, dev->name);
10926 /* Adapt owner in case owning user namespace of target network
10927 * namespace is different from the original one.
10929 err = netdev_change_owner(dev, net_old, net);
10932 /* Add the device back in the hashes */
10933 list_netdevice(dev);
10935 /* Notify protocols, that a new device appeared. */
10936 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10939 * Prevent userspace races by waiting until the network
10940 * device is fully setup before sending notifications.
10942 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10949 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
10951 static int dev_cpu_dead(unsigned int oldcpu)
10953 struct sk_buff **list_skb;
10954 struct sk_buff *skb;
10956 struct softnet_data *sd, *oldsd, *remsd = NULL;
10958 local_irq_disable();
10959 cpu = smp_processor_id();
10960 sd = &per_cpu(softnet_data, cpu);
10961 oldsd = &per_cpu(softnet_data, oldcpu);
10963 /* Find end of our completion_queue. */
10964 list_skb = &sd->completion_queue;
10966 list_skb = &(*list_skb)->next;
10967 /* Append completion queue from offline CPU. */
10968 *list_skb = oldsd->completion_queue;
10969 oldsd->completion_queue = NULL;
10971 /* Append output queue from offline CPU. */
10972 if (oldsd->output_queue) {
10973 *sd->output_queue_tailp = oldsd->output_queue;
10974 sd->output_queue_tailp = oldsd->output_queue_tailp;
10975 oldsd->output_queue = NULL;
10976 oldsd->output_queue_tailp = &oldsd->output_queue;
10978 /* Append NAPI poll list from offline CPU, with one exception :
10979 * process_backlog() must be called by cpu owning percpu backlog.
10980 * We properly handle process_queue & input_pkt_queue later.
10982 while (!list_empty(&oldsd->poll_list)) {
10983 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10984 struct napi_struct,
10987 list_del_init(&napi->poll_list);
10988 if (napi->poll == process_backlog)
10991 ____napi_schedule(sd, napi);
10994 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10995 local_irq_enable();
10998 remsd = oldsd->rps_ipi_list;
10999 oldsd->rps_ipi_list = NULL;
11001 /* send out pending IPI's on offline CPU */
11002 net_rps_send_ipi(remsd);
11004 /* Process offline CPU's input_pkt_queue */
11005 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11007 input_queue_head_incr(oldsd);
11009 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11011 input_queue_head_incr(oldsd);
11018 * netdev_increment_features - increment feature set by one
11019 * @all: current feature set
11020 * @one: new feature set
11021 * @mask: mask feature set
11023 * Computes a new feature set after adding a device with feature set
11024 * @one to the master device with current feature set @all. Will not
11025 * enable anything that is off in @mask. Returns the new feature set.
11027 netdev_features_t netdev_increment_features(netdev_features_t all,
11028 netdev_features_t one, netdev_features_t mask)
11030 if (mask & NETIF_F_HW_CSUM)
11031 mask |= NETIF_F_CSUM_MASK;
11032 mask |= NETIF_F_VLAN_CHALLENGED;
11034 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11035 all &= one | ~NETIF_F_ALL_FOR_ALL;
11037 /* If one device supports hw checksumming, set for all. */
11038 if (all & NETIF_F_HW_CSUM)
11039 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11043 EXPORT_SYMBOL(netdev_increment_features);
11045 static struct hlist_head * __net_init netdev_create_hash(void)
11048 struct hlist_head *hash;
11050 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11052 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11053 INIT_HLIST_HEAD(&hash[i]);
11058 /* Initialize per network namespace state */
11059 static int __net_init netdev_init(struct net *net)
11061 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11062 8 * sizeof_field(struct napi_struct, gro_bitmask));
11064 INIT_LIST_HEAD(&net->dev_base_head);
11066 net->dev_name_head = netdev_create_hash();
11067 if (net->dev_name_head == NULL)
11070 net->dev_index_head = netdev_create_hash();
11071 if (net->dev_index_head == NULL)
11074 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11079 kfree(net->dev_name_head);
11085 * netdev_drivername - network driver for the device
11086 * @dev: network device
11088 * Determine network driver for device.
11090 const char *netdev_drivername(const struct net_device *dev)
11092 const struct device_driver *driver;
11093 const struct device *parent;
11094 const char *empty = "";
11096 parent = dev->dev.parent;
11100 driver = parent->driver;
11101 if (driver && driver->name)
11102 return driver->name;
11106 static void __netdev_printk(const char *level, const struct net_device *dev,
11107 struct va_format *vaf)
11109 if (dev && dev->dev.parent) {
11110 dev_printk_emit(level[1] - '0',
11113 dev_driver_string(dev->dev.parent),
11114 dev_name(dev->dev.parent),
11115 netdev_name(dev), netdev_reg_state(dev),
11118 printk("%s%s%s: %pV",
11119 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11121 printk("%s(NULL net_device): %pV", level, vaf);
11125 void netdev_printk(const char *level, const struct net_device *dev,
11126 const char *format, ...)
11128 struct va_format vaf;
11131 va_start(args, format);
11136 __netdev_printk(level, dev, &vaf);
11140 EXPORT_SYMBOL(netdev_printk);
11142 #define define_netdev_printk_level(func, level) \
11143 void func(const struct net_device *dev, const char *fmt, ...) \
11145 struct va_format vaf; \
11148 va_start(args, fmt); \
11153 __netdev_printk(level, dev, &vaf); \
11157 EXPORT_SYMBOL(func);
11159 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11160 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11161 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11162 define_netdev_printk_level(netdev_err, KERN_ERR);
11163 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11164 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11165 define_netdev_printk_level(netdev_info, KERN_INFO);
11167 static void __net_exit netdev_exit(struct net *net)
11169 kfree(net->dev_name_head);
11170 kfree(net->dev_index_head);
11171 if (net != &init_net)
11172 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11175 static struct pernet_operations __net_initdata netdev_net_ops = {
11176 .init = netdev_init,
11177 .exit = netdev_exit,
11180 static void __net_exit default_device_exit_net(struct net *net)
11182 struct net_device *dev, *aux;
11184 * Push all migratable network devices back to the
11185 * initial network namespace
11188 for_each_netdev_safe(net, dev, aux) {
11190 char fb_name[IFNAMSIZ];
11192 /* Ignore unmoveable devices (i.e. loopback) */
11193 if (dev->features & NETIF_F_NETNS_LOCAL)
11196 /* Leave virtual devices for the generic cleanup */
11197 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11200 /* Push remaining network devices to init_net */
11201 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11202 if (netdev_name_in_use(&init_net, fb_name))
11203 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11204 err = dev_change_net_namespace(dev, &init_net, fb_name);
11206 pr_emerg("%s: failed to move %s to init_net: %d\n",
11207 __func__, dev->name, err);
11213 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11215 /* At exit all network devices most be removed from a network
11216 * namespace. Do this in the reverse order of registration.
11217 * Do this across as many network namespaces as possible to
11218 * improve batching efficiency.
11220 struct net_device *dev;
11222 LIST_HEAD(dev_kill_list);
11225 list_for_each_entry(net, net_list, exit_list) {
11226 default_device_exit_net(net);
11230 list_for_each_entry(net, net_list, exit_list) {
11231 for_each_netdev_reverse(net, dev) {
11232 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11233 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11235 unregister_netdevice_queue(dev, &dev_kill_list);
11238 unregister_netdevice_many(&dev_kill_list);
11242 static struct pernet_operations __net_initdata default_device_ops = {
11243 .exit_batch = default_device_exit_batch,
11247 * Initialize the DEV module. At boot time this walks the device list and
11248 * unhooks any devices that fail to initialise (normally hardware not
11249 * present) and leaves us with a valid list of present and active devices.
11254 * This is called single threaded during boot, so no need
11255 * to take the rtnl semaphore.
11257 static int __init net_dev_init(void)
11259 int i, rc = -ENOMEM;
11261 BUG_ON(!dev_boot_phase);
11263 if (dev_proc_init())
11266 if (netdev_kobject_init())
11269 INIT_LIST_HEAD(&ptype_all);
11270 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11271 INIT_LIST_HEAD(&ptype_base[i]);
11273 if (register_pernet_subsys(&netdev_net_ops))
11277 * Initialise the packet receive queues.
11280 for_each_possible_cpu(i) {
11281 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11282 struct softnet_data *sd = &per_cpu(softnet_data, i);
11284 INIT_WORK(flush, flush_backlog);
11286 skb_queue_head_init(&sd->input_pkt_queue);
11287 skb_queue_head_init(&sd->process_queue);
11288 #ifdef CONFIG_XFRM_OFFLOAD
11289 skb_queue_head_init(&sd->xfrm_backlog);
11291 INIT_LIST_HEAD(&sd->poll_list);
11292 sd->output_queue_tailp = &sd->output_queue;
11294 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11298 init_gro_hash(&sd->backlog);
11299 sd->backlog.poll = process_backlog;
11300 sd->backlog.weight = weight_p;
11303 dev_boot_phase = 0;
11305 /* The loopback device is special if any other network devices
11306 * is present in a network namespace the loopback device must
11307 * be present. Since we now dynamically allocate and free the
11308 * loopback device ensure this invariant is maintained by
11309 * keeping the loopback device as the first device on the
11310 * list of network devices. Ensuring the loopback devices
11311 * is the first device that appears and the last network device
11314 if (register_pernet_device(&loopback_net_ops))
11317 if (register_pernet_device(&default_device_ops))
11320 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11321 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11323 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11324 NULL, dev_cpu_dead);
11331 subsys_initcall(net_dev_init);