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>
155 #include "net-sysfs.h"
158 static DEFINE_SPINLOCK(ptype_lock);
159 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
160 struct list_head ptype_all __read_mostly; /* Taps */
162 static int netif_rx_internal(struct sk_buff *skb);
163 static int call_netdevice_notifiers_extack(unsigned long val,
164 struct net_device *dev,
165 struct netlink_ext_ack *extack);
166 static struct napi_struct *napi_by_id(unsigned int napi_id);
169 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
172 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
174 * Writers must hold the rtnl semaphore while they loop through the
175 * dev_base_head list, and hold dev_base_lock for writing when they do the
176 * actual updates. This allows pure readers to access the list even
177 * while a writer is preparing to update it.
179 * To put it another way, dev_base_lock is held for writing only to
180 * protect against pure readers; the rtnl semaphore provides the
181 * protection against other writers.
183 * See, for example usages, register_netdevice() and
184 * unregister_netdevice(), which must be called with the rtnl
187 DEFINE_RWLOCK(dev_base_lock);
188 EXPORT_SYMBOL(dev_base_lock);
190 static DEFINE_MUTEX(ifalias_mutex);
192 /* protects napi_hash addition/deletion and napi_gen_id */
193 static DEFINE_SPINLOCK(napi_hash_lock);
195 static unsigned int napi_gen_id = NR_CPUS;
196 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
198 static DECLARE_RWSEM(devnet_rename_sem);
200 static inline void dev_base_seq_inc(struct net *net)
202 while (++net->dev_base_seq == 0)
206 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
208 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
210 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
213 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
215 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
218 static inline void rps_lock_irqsave(struct softnet_data *sd,
219 unsigned long *flags)
221 if (IS_ENABLED(CONFIG_RPS))
222 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
223 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
224 local_irq_save(*flags);
227 static inline void rps_lock_irq_disable(struct softnet_data *sd)
229 if (IS_ENABLED(CONFIG_RPS))
230 spin_lock_irq(&sd->input_pkt_queue.lock);
231 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
235 static inline void rps_unlock_irq_restore(struct softnet_data *sd,
236 unsigned long *flags)
238 if (IS_ENABLED(CONFIG_RPS))
239 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
240 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
241 local_irq_restore(*flags);
244 static inline void rps_unlock_irq_enable(struct softnet_data *sd)
246 if (IS_ENABLED(CONFIG_RPS))
247 spin_unlock_irq(&sd->input_pkt_queue.lock);
248 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
252 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
255 struct netdev_name_node *name_node;
257 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
260 INIT_HLIST_NODE(&name_node->hlist);
261 name_node->dev = dev;
262 name_node->name = name;
266 static struct netdev_name_node *
267 netdev_name_node_head_alloc(struct net_device *dev)
269 struct netdev_name_node *name_node;
271 name_node = netdev_name_node_alloc(dev, dev->name);
274 INIT_LIST_HEAD(&name_node->list);
278 static void netdev_name_node_free(struct netdev_name_node *name_node)
283 static void netdev_name_node_add(struct net *net,
284 struct netdev_name_node *name_node)
286 hlist_add_head_rcu(&name_node->hlist,
287 dev_name_hash(net, name_node->name));
290 static void netdev_name_node_del(struct netdev_name_node *name_node)
292 hlist_del_rcu(&name_node->hlist);
295 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
298 struct hlist_head *head = dev_name_hash(net, name);
299 struct netdev_name_node *name_node;
301 hlist_for_each_entry(name_node, head, hlist)
302 if (!strcmp(name_node->name, name))
307 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
310 struct hlist_head *head = dev_name_hash(net, name);
311 struct netdev_name_node *name_node;
313 hlist_for_each_entry_rcu(name_node, head, hlist)
314 if (!strcmp(name_node->name, name))
319 bool netdev_name_in_use(struct net *net, const char *name)
321 return netdev_name_node_lookup(net, name);
323 EXPORT_SYMBOL(netdev_name_in_use);
325 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
327 struct netdev_name_node *name_node;
328 struct net *net = dev_net(dev);
330 name_node = netdev_name_node_lookup(net, name);
333 name_node = netdev_name_node_alloc(dev, name);
336 netdev_name_node_add(net, name_node);
337 /* The node that holds dev->name acts as a head of per-device list. */
338 list_add_tail(&name_node->list, &dev->name_node->list);
343 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
345 list_del(&name_node->list);
346 netdev_name_node_del(name_node);
347 kfree(name_node->name);
348 netdev_name_node_free(name_node);
351 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
353 struct netdev_name_node *name_node;
354 struct net *net = dev_net(dev);
356 name_node = netdev_name_node_lookup(net, name);
359 /* lookup might have found our primary name or a name belonging
362 if (name_node == dev->name_node || name_node->dev != dev)
365 __netdev_name_node_alt_destroy(name_node);
370 static void netdev_name_node_alt_flush(struct net_device *dev)
372 struct netdev_name_node *name_node, *tmp;
374 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
375 __netdev_name_node_alt_destroy(name_node);
378 /* Device list insertion */
379 static void list_netdevice(struct net_device *dev)
381 struct net *net = dev_net(dev);
385 write_lock(&dev_base_lock);
386 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
387 netdev_name_node_add(net, dev->name_node);
388 hlist_add_head_rcu(&dev->index_hlist,
389 dev_index_hash(net, dev->ifindex));
390 write_unlock(&dev_base_lock);
392 dev_base_seq_inc(net);
395 /* Device list removal
396 * caller must respect a RCU grace period before freeing/reusing dev
398 static void unlist_netdevice(struct net_device *dev, bool lock)
402 /* 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);
409 write_unlock(&dev_base_lock);
411 dev_base_seq_inc(dev_net(dev));
418 static RAW_NOTIFIER_HEAD(netdev_chain);
421 * Device drivers call our routines to queue packets here. We empty the
422 * queue in the local softnet handler.
425 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
426 EXPORT_PER_CPU_SYMBOL(softnet_data);
428 #ifdef CONFIG_LOCKDEP
430 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
431 * according to dev->type
433 static const unsigned short netdev_lock_type[] = {
434 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
435 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
436 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
437 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
438 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
439 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
440 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
441 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
442 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
443 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
444 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
445 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
446 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
447 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
448 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
450 static const char *const netdev_lock_name[] = {
451 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
452 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
453 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
454 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
455 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
456 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
457 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
458 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
459 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
460 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
461 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
462 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
463 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
464 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
465 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
467 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
468 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
470 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
474 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
475 if (netdev_lock_type[i] == dev_type)
477 /* the last key is used by default */
478 return ARRAY_SIZE(netdev_lock_type) - 1;
481 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
482 unsigned short dev_type)
486 i = netdev_lock_pos(dev_type);
487 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
488 netdev_lock_name[i]);
491 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
495 i = netdev_lock_pos(dev->type);
496 lockdep_set_class_and_name(&dev->addr_list_lock,
497 &netdev_addr_lock_key[i],
498 netdev_lock_name[i]);
501 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
502 unsigned short dev_type)
506 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
511 /*******************************************************************************
513 * Protocol management and registration routines
515 *******************************************************************************/
519 * Add a protocol ID to the list. Now that the input handler is
520 * smarter we can dispense with all the messy stuff that used to be
523 * BEWARE!!! Protocol handlers, mangling input packets,
524 * MUST BE last in hash buckets and checking protocol handlers
525 * MUST start from promiscuous ptype_all chain in net_bh.
526 * It is true now, do not change it.
527 * Explanation follows: if protocol handler, mangling packet, will
528 * be the first on list, it is not able to sense, that packet
529 * is cloned and should be copied-on-write, so that it will
530 * change it and subsequent readers will get broken packet.
534 static inline struct list_head *ptype_head(const struct packet_type *pt)
536 if (pt->type == htons(ETH_P_ALL))
537 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
539 return pt->dev ? &pt->dev->ptype_specific :
540 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
544 * dev_add_pack - add packet handler
545 * @pt: packet type declaration
547 * Add a protocol handler to the networking stack. The passed &packet_type
548 * is linked into kernel lists and may not be freed until it has been
549 * removed from the kernel lists.
551 * This call does not sleep therefore it can not
552 * guarantee all CPU's that are in middle of receiving packets
553 * will see the new packet type (until the next received packet).
556 void dev_add_pack(struct packet_type *pt)
558 struct list_head *head = ptype_head(pt);
560 spin_lock(&ptype_lock);
561 list_add_rcu(&pt->list, head);
562 spin_unlock(&ptype_lock);
564 EXPORT_SYMBOL(dev_add_pack);
567 * __dev_remove_pack - remove packet handler
568 * @pt: packet type declaration
570 * Remove a protocol handler that was previously added to the kernel
571 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
572 * from the kernel lists and can be freed or reused once this function
575 * The packet type might still be in use by receivers
576 * and must not be freed until after all the CPU's have gone
577 * through a quiescent state.
579 void __dev_remove_pack(struct packet_type *pt)
581 struct list_head *head = ptype_head(pt);
582 struct packet_type *pt1;
584 spin_lock(&ptype_lock);
586 list_for_each_entry(pt1, head, list) {
588 list_del_rcu(&pt->list);
593 pr_warn("dev_remove_pack: %p not found\n", pt);
595 spin_unlock(&ptype_lock);
597 EXPORT_SYMBOL(__dev_remove_pack);
600 * dev_remove_pack - remove packet handler
601 * @pt: packet type declaration
603 * Remove a protocol handler that was previously added to the kernel
604 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
605 * from the kernel lists and can be freed or reused once this function
608 * This call sleeps to guarantee that no CPU is looking at the packet
611 void dev_remove_pack(struct packet_type *pt)
613 __dev_remove_pack(pt);
617 EXPORT_SYMBOL(dev_remove_pack);
620 /*******************************************************************************
622 * Device Interface Subroutines
624 *******************************************************************************/
627 * dev_get_iflink - get 'iflink' value of a interface
628 * @dev: targeted interface
630 * Indicates the ifindex the interface is linked to.
631 * Physical interfaces have the same 'ifindex' and 'iflink' values.
634 int dev_get_iflink(const struct net_device *dev)
636 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
637 return dev->netdev_ops->ndo_get_iflink(dev);
641 EXPORT_SYMBOL(dev_get_iflink);
644 * dev_fill_metadata_dst - Retrieve tunnel egress information.
645 * @dev: targeted interface
648 * For better visibility of tunnel traffic OVS needs to retrieve
649 * egress tunnel information for a packet. Following API allows
650 * user to get this info.
652 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
654 struct ip_tunnel_info *info;
656 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
659 info = skb_tunnel_info_unclone(skb);
662 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
665 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
667 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
669 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
671 int k = stack->num_paths++;
673 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
676 return &stack->path[k];
679 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
680 struct net_device_path_stack *stack)
682 const struct net_device *last_dev;
683 struct net_device_path_ctx ctx = {
686 struct net_device_path *path;
689 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
690 stack->num_paths = 0;
691 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
693 path = dev_fwd_path(stack);
697 memset(path, 0, sizeof(struct net_device_path));
698 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
702 if (WARN_ON_ONCE(last_dev == ctx.dev))
709 path = dev_fwd_path(stack);
712 path->type = DEV_PATH_ETHERNET;
717 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
720 * __dev_get_by_name - find a device by its name
721 * @net: the applicable net namespace
722 * @name: name to find
724 * Find an interface by name. Must be called under RTNL semaphore
725 * or @dev_base_lock. If the name is found a pointer to the device
726 * is returned. If the name is not found then %NULL is returned. The
727 * reference counters are not incremented so the caller must be
728 * careful with locks.
731 struct net_device *__dev_get_by_name(struct net *net, const char *name)
733 struct netdev_name_node *node_name;
735 node_name = netdev_name_node_lookup(net, name);
736 return node_name ? node_name->dev : NULL;
738 EXPORT_SYMBOL(__dev_get_by_name);
741 * dev_get_by_name_rcu - find a device by its name
742 * @net: the applicable net namespace
743 * @name: name to find
745 * Find an interface by name.
746 * If the name is found a pointer to the device is returned.
747 * If the name is not found then %NULL is returned.
748 * The reference counters are not incremented so the caller must be
749 * careful with locks. The caller must hold RCU lock.
752 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
754 struct netdev_name_node *node_name;
756 node_name = netdev_name_node_lookup_rcu(net, name);
757 return node_name ? node_name->dev : NULL;
759 EXPORT_SYMBOL(dev_get_by_name_rcu);
761 /* Deprecated for new users, call netdev_get_by_name() instead */
762 struct net_device *dev_get_by_name(struct net *net, const char *name)
764 struct net_device *dev;
767 dev = dev_get_by_name_rcu(net, name);
772 EXPORT_SYMBOL(dev_get_by_name);
775 * netdev_get_by_name() - find a device by its name
776 * @net: the applicable net namespace
777 * @name: name to find
778 * @tracker: tracking object for the acquired reference
779 * @gfp: allocation flags for the tracker
781 * Find an interface by name. This can be called from any
782 * context and does its own locking. The returned handle has
783 * the usage count incremented and the caller must use netdev_put() to
784 * release it when it is no longer needed. %NULL is returned if no
785 * matching device is found.
787 struct net_device *netdev_get_by_name(struct net *net, const char *name,
788 netdevice_tracker *tracker, gfp_t gfp)
790 struct net_device *dev;
792 dev = dev_get_by_name(net, name);
794 netdev_tracker_alloc(dev, tracker, gfp);
797 EXPORT_SYMBOL(netdev_get_by_name);
800 * __dev_get_by_index - find a device by its ifindex
801 * @net: the applicable net namespace
802 * @ifindex: index of device
804 * Search for an interface by index. Returns %NULL if the device
805 * is not found or a pointer to the device. The device has not
806 * had its reference counter increased so the caller must be careful
807 * about locking. The caller must hold either the RTNL semaphore
811 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
813 struct net_device *dev;
814 struct hlist_head *head = dev_index_hash(net, ifindex);
816 hlist_for_each_entry(dev, head, index_hlist)
817 if (dev->ifindex == ifindex)
822 EXPORT_SYMBOL(__dev_get_by_index);
825 * dev_get_by_index_rcu - find a device by its ifindex
826 * @net: the applicable net namespace
827 * @ifindex: index of device
829 * Search for an interface by index. Returns %NULL if the device
830 * is not found or a pointer to the device. The device has not
831 * had its reference counter increased so the caller must be careful
832 * about locking. The caller must hold RCU lock.
835 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
837 struct net_device *dev;
838 struct hlist_head *head = dev_index_hash(net, ifindex);
840 hlist_for_each_entry_rcu(dev, head, index_hlist)
841 if (dev->ifindex == ifindex)
846 EXPORT_SYMBOL(dev_get_by_index_rcu);
848 /* Deprecated for new users, call netdev_get_by_index() instead */
849 struct net_device *dev_get_by_index(struct net *net, int ifindex)
851 struct net_device *dev;
854 dev = dev_get_by_index_rcu(net, ifindex);
859 EXPORT_SYMBOL(dev_get_by_index);
862 * netdev_get_by_index() - find a device by its ifindex
863 * @net: the applicable net namespace
864 * @ifindex: index of device
865 * @tracker: tracking object for the acquired reference
866 * @gfp: allocation flags for the tracker
868 * Search for an interface by index. Returns NULL if the device
869 * is not found or a pointer to the device. The device returned has
870 * had a reference added and the pointer is safe until the user calls
871 * netdev_put() to indicate they have finished with it.
873 struct net_device *netdev_get_by_index(struct net *net, int ifindex,
874 netdevice_tracker *tracker, gfp_t gfp)
876 struct net_device *dev;
878 dev = dev_get_by_index(net, ifindex);
880 netdev_tracker_alloc(dev, tracker, gfp);
883 EXPORT_SYMBOL(netdev_get_by_index);
886 * dev_get_by_napi_id - find a device by napi_id
887 * @napi_id: ID of the NAPI struct
889 * Search for an interface by NAPI ID. Returns %NULL if the device
890 * is not found or a pointer to the device. The device has not had
891 * its reference counter increased so the caller must be careful
892 * about locking. The caller must hold RCU lock.
895 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
897 struct napi_struct *napi;
899 WARN_ON_ONCE(!rcu_read_lock_held());
901 if (napi_id < MIN_NAPI_ID)
904 napi = napi_by_id(napi_id);
906 return napi ? napi->dev : NULL;
908 EXPORT_SYMBOL(dev_get_by_napi_id);
911 * netdev_get_name - get a netdevice name, knowing its ifindex.
912 * @net: network namespace
913 * @name: a pointer to the buffer where the name will be stored.
914 * @ifindex: the ifindex of the interface to get the name from.
916 int netdev_get_name(struct net *net, char *name, int ifindex)
918 struct net_device *dev;
921 down_read(&devnet_rename_sem);
924 dev = dev_get_by_index_rcu(net, ifindex);
930 strcpy(name, dev->name);
935 up_read(&devnet_rename_sem);
940 * dev_getbyhwaddr_rcu - find a device by its hardware address
941 * @net: the applicable net namespace
942 * @type: media type of device
943 * @ha: hardware address
945 * Search for an interface by MAC address. Returns NULL if the device
946 * is not found or a pointer to the device.
947 * The caller must hold RCU or RTNL.
948 * The returned device has not had its ref count increased
949 * and the caller must therefore be careful about locking
953 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
956 struct net_device *dev;
958 for_each_netdev_rcu(net, dev)
959 if (dev->type == type &&
960 !memcmp(dev->dev_addr, ha, dev->addr_len))
965 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
967 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
969 struct net_device *dev, *ret = NULL;
972 for_each_netdev_rcu(net, dev)
973 if (dev->type == type) {
981 EXPORT_SYMBOL(dev_getfirstbyhwtype);
984 * __dev_get_by_flags - find any device with given flags
985 * @net: the applicable net namespace
986 * @if_flags: IFF_* values
987 * @mask: bitmask of bits in if_flags to check
989 * Search for any interface with the given flags. Returns NULL if a device
990 * is not found or a pointer to the device. Must be called inside
991 * rtnl_lock(), and result refcount is unchanged.
994 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
997 struct net_device *dev, *ret;
1002 for_each_netdev(net, dev) {
1003 if (((dev->flags ^ if_flags) & mask) == 0) {
1010 EXPORT_SYMBOL(__dev_get_by_flags);
1013 * dev_valid_name - check if name is okay for network device
1014 * @name: name string
1016 * Network device names need to be valid file names to
1017 * allow sysfs to work. We also disallow any kind of
1020 bool dev_valid_name(const char *name)
1024 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1026 if (!strcmp(name, ".") || !strcmp(name, ".."))
1030 if (*name == '/' || *name == ':' || isspace(*name))
1036 EXPORT_SYMBOL(dev_valid_name);
1039 * __dev_alloc_name - allocate a name for a device
1040 * @net: network namespace to allocate the device name in
1041 * @name: name format string
1042 * @buf: scratch buffer and result name string
1044 * Passed a format string - eg "lt%d" it will try and find a suitable
1045 * id. It scans list of devices to build up a free map, then chooses
1046 * the first empty slot. The caller must hold the dev_base or rtnl lock
1047 * while allocating the name and adding the device in order to avoid
1049 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1050 * Returns the number of the unit assigned or a negative errno code.
1053 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1057 const int max_netdevices = 8*PAGE_SIZE;
1058 unsigned long *inuse;
1059 struct net_device *d;
1061 if (!dev_valid_name(name))
1064 p = strchr(name, '%');
1067 * Verify the string as this thing may have come from
1068 * the user. There must be either one "%d" and no other "%"
1071 if (p[1] != 'd' || strchr(p + 2, '%'))
1074 /* Use one page as a bit array of possible slots */
1075 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1079 for_each_netdev(net, d) {
1080 struct netdev_name_node *name_node;
1081 list_for_each_entry(name_node, &d->name_node->list, list) {
1082 if (!sscanf(name_node->name, name, &i))
1084 if (i < 0 || i >= max_netdevices)
1087 /* avoid cases where sscanf is not exact inverse of printf */
1088 snprintf(buf, IFNAMSIZ, name, i);
1089 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1090 __set_bit(i, inuse);
1092 if (!sscanf(d->name, name, &i))
1094 if (i < 0 || i >= max_netdevices)
1097 /* avoid cases where sscanf is not exact inverse of printf */
1098 snprintf(buf, IFNAMSIZ, name, i);
1099 if (!strncmp(buf, d->name, IFNAMSIZ))
1100 __set_bit(i, inuse);
1103 i = find_first_zero_bit(inuse, max_netdevices);
1104 free_page((unsigned long) inuse);
1107 snprintf(buf, IFNAMSIZ, name, i);
1108 if (!netdev_name_in_use(net, buf))
1111 /* It is possible to run out of possible slots
1112 * when the name is long and there isn't enough space left
1113 * for the digits, or if all bits are used.
1118 static int dev_alloc_name_ns(struct net *net,
1119 struct net_device *dev,
1126 ret = __dev_alloc_name(net, name, buf);
1128 strscpy(dev->name, buf, IFNAMSIZ);
1133 * dev_alloc_name - allocate a name for a device
1135 * @name: name format string
1137 * Passed a format string - eg "lt%d" it will try and find a suitable
1138 * id. It scans list of devices to build up a free map, then chooses
1139 * the first empty slot. The caller must hold the dev_base or rtnl lock
1140 * while allocating the name and adding the device in order to avoid
1142 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1143 * Returns the number of the unit assigned or a negative errno code.
1146 int dev_alloc_name(struct net_device *dev, const char *name)
1148 return dev_alloc_name_ns(dev_net(dev), dev, name);
1150 EXPORT_SYMBOL(dev_alloc_name);
1152 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1157 if (!dev_valid_name(name))
1160 if (strchr(name, '%'))
1161 return dev_alloc_name_ns(net, dev, name);
1162 else if (netdev_name_in_use(net, name))
1164 else if (dev->name != name)
1165 strscpy(dev->name, name, IFNAMSIZ);
1171 * dev_change_name - change name of a device
1173 * @newname: name (or format string) must be at least IFNAMSIZ
1175 * Change name of a device, can pass format strings "eth%d".
1178 int dev_change_name(struct net_device *dev, const char *newname)
1180 unsigned char old_assign_type;
1181 char oldname[IFNAMSIZ];
1187 BUG_ON(!dev_net(dev));
1191 down_write(&devnet_rename_sem);
1193 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1194 up_write(&devnet_rename_sem);
1198 memcpy(oldname, dev->name, IFNAMSIZ);
1200 err = dev_get_valid_name(net, dev, newname);
1202 up_write(&devnet_rename_sem);
1206 if (oldname[0] && !strchr(oldname, '%'))
1207 netdev_info(dev, "renamed from %s%s\n", oldname,
1208 dev->flags & IFF_UP ? " (while UP)" : "");
1210 old_assign_type = dev->name_assign_type;
1211 dev->name_assign_type = NET_NAME_RENAMED;
1214 ret = device_rename(&dev->dev, dev->name);
1216 memcpy(dev->name, oldname, IFNAMSIZ);
1217 dev->name_assign_type = old_assign_type;
1218 up_write(&devnet_rename_sem);
1222 up_write(&devnet_rename_sem);
1224 netdev_adjacent_rename_links(dev, oldname);
1226 write_lock(&dev_base_lock);
1227 netdev_name_node_del(dev->name_node);
1228 write_unlock(&dev_base_lock);
1232 write_lock(&dev_base_lock);
1233 netdev_name_node_add(net, dev->name_node);
1234 write_unlock(&dev_base_lock);
1236 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1237 ret = notifier_to_errno(ret);
1240 /* err >= 0 after dev_alloc_name() or stores the first errno */
1243 down_write(&devnet_rename_sem);
1244 memcpy(dev->name, oldname, IFNAMSIZ);
1245 memcpy(oldname, newname, IFNAMSIZ);
1246 dev->name_assign_type = old_assign_type;
1247 old_assign_type = NET_NAME_RENAMED;
1250 netdev_err(dev, "name change rollback failed: %d\n",
1259 * dev_set_alias - change ifalias of a device
1261 * @alias: name up to IFALIASZ
1262 * @len: limit of bytes to copy from info
1264 * Set ifalias for a device,
1266 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1268 struct dev_ifalias *new_alias = NULL;
1270 if (len >= IFALIASZ)
1274 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1278 memcpy(new_alias->ifalias, alias, len);
1279 new_alias->ifalias[len] = 0;
1282 mutex_lock(&ifalias_mutex);
1283 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1284 mutex_is_locked(&ifalias_mutex));
1285 mutex_unlock(&ifalias_mutex);
1288 kfree_rcu(new_alias, rcuhead);
1292 EXPORT_SYMBOL(dev_set_alias);
1295 * dev_get_alias - get ifalias of a device
1297 * @name: buffer to store name of ifalias
1298 * @len: size of buffer
1300 * get ifalias for a device. Caller must make sure dev cannot go
1301 * away, e.g. rcu read lock or own a reference count to device.
1303 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1305 const struct dev_ifalias *alias;
1309 alias = rcu_dereference(dev->ifalias);
1311 ret = snprintf(name, len, "%s", alias->ifalias);
1318 * netdev_features_change - device changes features
1319 * @dev: device to cause notification
1321 * Called to indicate a device has changed features.
1323 void netdev_features_change(struct net_device *dev)
1325 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1327 EXPORT_SYMBOL(netdev_features_change);
1330 * netdev_state_change - device changes state
1331 * @dev: device to cause notification
1333 * Called to indicate a device has changed state. This function calls
1334 * the notifier chains for netdev_chain and sends a NEWLINK message
1335 * to the routing socket.
1337 void netdev_state_change(struct net_device *dev)
1339 if (dev->flags & IFF_UP) {
1340 struct netdev_notifier_change_info change_info = {
1344 call_netdevice_notifiers_info(NETDEV_CHANGE,
1346 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1349 EXPORT_SYMBOL(netdev_state_change);
1352 * __netdev_notify_peers - notify network peers about existence of @dev,
1353 * to be called when rtnl lock is already held.
1354 * @dev: network device
1356 * Generate traffic such that interested network peers are aware of
1357 * @dev, such as by generating a gratuitous ARP. This may be used when
1358 * a device wants to inform the rest of the network about some sort of
1359 * reconfiguration such as a failover event or virtual machine
1362 void __netdev_notify_peers(struct net_device *dev)
1365 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1366 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1368 EXPORT_SYMBOL(__netdev_notify_peers);
1371 * netdev_notify_peers - notify network peers about existence of @dev
1372 * @dev: network device
1374 * Generate traffic such that interested network peers are aware of
1375 * @dev, such as by generating a gratuitous ARP. This may be used when
1376 * a device wants to inform the rest of the network about some sort of
1377 * reconfiguration such as a failover event or virtual machine
1380 void netdev_notify_peers(struct net_device *dev)
1383 __netdev_notify_peers(dev);
1386 EXPORT_SYMBOL(netdev_notify_peers);
1388 static int napi_threaded_poll(void *data);
1390 static int napi_kthread_create(struct napi_struct *n)
1394 /* Create and wake up the kthread once to put it in
1395 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1396 * warning and work with loadavg.
1398 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1399 n->dev->name, n->napi_id);
1400 if (IS_ERR(n->thread)) {
1401 err = PTR_ERR(n->thread);
1402 pr_err("kthread_run failed with err %d\n", err);
1409 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1411 const struct net_device_ops *ops = dev->netdev_ops;
1415 dev_addr_check(dev);
1417 if (!netif_device_present(dev)) {
1418 /* may be detached because parent is runtime-suspended */
1419 if (dev->dev.parent)
1420 pm_runtime_resume(dev->dev.parent);
1421 if (!netif_device_present(dev))
1425 /* Block netpoll from trying to do any rx path servicing.
1426 * If we don't do this there is a chance ndo_poll_controller
1427 * or ndo_poll may be running while we open the device
1429 netpoll_poll_disable(dev);
1431 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1432 ret = notifier_to_errno(ret);
1436 set_bit(__LINK_STATE_START, &dev->state);
1438 if (ops->ndo_validate_addr)
1439 ret = ops->ndo_validate_addr(dev);
1441 if (!ret && ops->ndo_open)
1442 ret = ops->ndo_open(dev);
1444 netpoll_poll_enable(dev);
1447 clear_bit(__LINK_STATE_START, &dev->state);
1449 dev->flags |= IFF_UP;
1450 dev_set_rx_mode(dev);
1452 add_device_randomness(dev->dev_addr, dev->addr_len);
1459 * dev_open - prepare an interface for use.
1460 * @dev: device to open
1461 * @extack: netlink extended ack
1463 * Takes a device from down to up state. The device's private open
1464 * function is invoked and then the multicast lists are loaded. Finally
1465 * the device is moved into the up state and a %NETDEV_UP message is
1466 * sent to the netdev notifier chain.
1468 * Calling this function on an active interface is a nop. On a failure
1469 * a negative errno code is returned.
1471 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1475 if (dev->flags & IFF_UP)
1478 ret = __dev_open(dev, extack);
1482 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1483 call_netdevice_notifiers(NETDEV_UP, dev);
1487 EXPORT_SYMBOL(dev_open);
1489 static void __dev_close_many(struct list_head *head)
1491 struct net_device *dev;
1496 list_for_each_entry(dev, head, close_list) {
1497 /* Temporarily disable netpoll until the interface is down */
1498 netpoll_poll_disable(dev);
1500 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1502 clear_bit(__LINK_STATE_START, &dev->state);
1504 /* Synchronize to scheduled poll. We cannot touch poll list, it
1505 * can be even on different cpu. So just clear netif_running().
1507 * dev->stop() will invoke napi_disable() on all of it's
1508 * napi_struct instances on this device.
1510 smp_mb__after_atomic(); /* Commit netif_running(). */
1513 dev_deactivate_many(head);
1515 list_for_each_entry(dev, head, close_list) {
1516 const struct net_device_ops *ops = dev->netdev_ops;
1519 * Call the device specific close. This cannot fail.
1520 * Only if device is UP
1522 * We allow it to be called even after a DETACH hot-plug
1528 dev->flags &= ~IFF_UP;
1529 netpoll_poll_enable(dev);
1533 static void __dev_close(struct net_device *dev)
1537 list_add(&dev->close_list, &single);
1538 __dev_close_many(&single);
1542 void dev_close_many(struct list_head *head, bool unlink)
1544 struct net_device *dev, *tmp;
1546 /* Remove the devices that don't need to be closed */
1547 list_for_each_entry_safe(dev, tmp, head, close_list)
1548 if (!(dev->flags & IFF_UP))
1549 list_del_init(&dev->close_list);
1551 __dev_close_many(head);
1553 list_for_each_entry_safe(dev, tmp, head, close_list) {
1554 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1555 call_netdevice_notifiers(NETDEV_DOWN, dev);
1557 list_del_init(&dev->close_list);
1560 EXPORT_SYMBOL(dev_close_many);
1563 * dev_close - shutdown an interface.
1564 * @dev: device to shutdown
1566 * This function moves an active device into down state. A
1567 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1568 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1571 void dev_close(struct net_device *dev)
1573 if (dev->flags & IFF_UP) {
1576 list_add(&dev->close_list, &single);
1577 dev_close_many(&single, true);
1581 EXPORT_SYMBOL(dev_close);
1585 * dev_disable_lro - disable Large Receive Offload on a device
1588 * Disable Large Receive Offload (LRO) on a net device. Must be
1589 * called under RTNL. This is needed if received packets may be
1590 * forwarded to another interface.
1592 void dev_disable_lro(struct net_device *dev)
1594 struct net_device *lower_dev;
1595 struct list_head *iter;
1597 dev->wanted_features &= ~NETIF_F_LRO;
1598 netdev_update_features(dev);
1600 if (unlikely(dev->features & NETIF_F_LRO))
1601 netdev_WARN(dev, "failed to disable LRO!\n");
1603 netdev_for_each_lower_dev(dev, lower_dev, iter)
1604 dev_disable_lro(lower_dev);
1606 EXPORT_SYMBOL(dev_disable_lro);
1609 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1612 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1613 * called under RTNL. This is needed if Generic XDP is installed on
1616 static void dev_disable_gro_hw(struct net_device *dev)
1618 dev->wanted_features &= ~NETIF_F_GRO_HW;
1619 netdev_update_features(dev);
1621 if (unlikely(dev->features & NETIF_F_GRO_HW))
1622 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1625 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1628 case NETDEV_##val: \
1629 return "NETDEV_" __stringify(val);
1631 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1632 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1633 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1634 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1635 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1636 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1637 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1638 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1639 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1640 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1641 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1645 return "UNKNOWN_NETDEV_EVENT";
1647 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1649 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1650 struct net_device *dev)
1652 struct netdev_notifier_info info = {
1656 return nb->notifier_call(nb, val, &info);
1659 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1660 struct net_device *dev)
1664 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1665 err = notifier_to_errno(err);
1669 if (!(dev->flags & IFF_UP))
1672 call_netdevice_notifier(nb, NETDEV_UP, dev);
1676 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1677 struct net_device *dev)
1679 if (dev->flags & IFF_UP) {
1680 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1682 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1684 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1687 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1690 struct net_device *dev;
1693 for_each_netdev(net, dev) {
1694 err = call_netdevice_register_notifiers(nb, dev);
1701 for_each_netdev_continue_reverse(net, dev)
1702 call_netdevice_unregister_notifiers(nb, dev);
1706 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1709 struct net_device *dev;
1711 for_each_netdev(net, dev)
1712 call_netdevice_unregister_notifiers(nb, dev);
1715 static int dev_boot_phase = 1;
1718 * register_netdevice_notifier - register a network notifier block
1721 * Register a notifier to be called when network device events occur.
1722 * The notifier passed is linked into the kernel structures and must
1723 * not be reused until it has been unregistered. A negative errno code
1724 * is returned on a failure.
1726 * When registered all registration and up events are replayed
1727 * to the new notifier to allow device to have a race free
1728 * view of the network device list.
1731 int register_netdevice_notifier(struct notifier_block *nb)
1736 /* Close race with setup_net() and cleanup_net() */
1737 down_write(&pernet_ops_rwsem);
1739 err = raw_notifier_chain_register(&netdev_chain, nb);
1745 err = call_netdevice_register_net_notifiers(nb, net);
1752 up_write(&pernet_ops_rwsem);
1756 for_each_net_continue_reverse(net)
1757 call_netdevice_unregister_net_notifiers(nb, net);
1759 raw_notifier_chain_unregister(&netdev_chain, nb);
1762 EXPORT_SYMBOL(register_netdevice_notifier);
1765 * unregister_netdevice_notifier - unregister a network notifier block
1768 * Unregister a notifier previously registered by
1769 * register_netdevice_notifier(). The notifier is unlinked into the
1770 * kernel structures and may then be reused. A negative errno code
1771 * is returned on a failure.
1773 * After unregistering unregister and down device events are synthesized
1774 * for all devices on the device list to the removed notifier to remove
1775 * the need for special case cleanup code.
1778 int unregister_netdevice_notifier(struct notifier_block *nb)
1783 /* Close race with setup_net() and cleanup_net() */
1784 down_write(&pernet_ops_rwsem);
1786 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1791 call_netdevice_unregister_net_notifiers(nb, net);
1795 up_write(&pernet_ops_rwsem);
1798 EXPORT_SYMBOL(unregister_netdevice_notifier);
1800 static int __register_netdevice_notifier_net(struct net *net,
1801 struct notifier_block *nb,
1802 bool ignore_call_fail)
1806 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1812 err = call_netdevice_register_net_notifiers(nb, net);
1813 if (err && !ignore_call_fail)
1814 goto chain_unregister;
1819 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1823 static int __unregister_netdevice_notifier_net(struct net *net,
1824 struct notifier_block *nb)
1828 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1832 call_netdevice_unregister_net_notifiers(nb, net);
1837 * register_netdevice_notifier_net - register a per-netns network notifier block
1838 * @net: network namespace
1841 * Register a notifier to be called when network device events occur.
1842 * The notifier passed is linked into the kernel structures and must
1843 * not be reused until it has been unregistered. A negative errno code
1844 * is returned on a failure.
1846 * When registered all registration and up events are replayed
1847 * to the new notifier to allow device to have a race free
1848 * view of the network device list.
1851 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1856 err = __register_netdevice_notifier_net(net, nb, false);
1860 EXPORT_SYMBOL(register_netdevice_notifier_net);
1863 * unregister_netdevice_notifier_net - unregister a per-netns
1864 * network notifier block
1865 * @net: network namespace
1868 * Unregister a notifier previously registered by
1869 * register_netdevice_notifier_net(). The notifier is unlinked from the
1870 * kernel structures and may then be reused. A negative errno code
1871 * is returned on a failure.
1873 * After unregistering unregister and down device events are synthesized
1874 * for all devices on the device list to the removed notifier to remove
1875 * the need for special case cleanup code.
1878 int unregister_netdevice_notifier_net(struct net *net,
1879 struct notifier_block *nb)
1884 err = __unregister_netdevice_notifier_net(net, nb);
1888 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1890 static void __move_netdevice_notifier_net(struct net *src_net,
1891 struct net *dst_net,
1892 struct notifier_block *nb)
1894 __unregister_netdevice_notifier_net(src_net, nb);
1895 __register_netdevice_notifier_net(dst_net, nb, true);
1898 int register_netdevice_notifier_dev_net(struct net_device *dev,
1899 struct notifier_block *nb,
1900 struct netdev_net_notifier *nn)
1905 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1908 list_add(&nn->list, &dev->net_notifier_list);
1913 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1915 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1916 struct notifier_block *nb,
1917 struct netdev_net_notifier *nn)
1922 list_del(&nn->list);
1923 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1927 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1929 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1932 struct netdev_net_notifier *nn;
1934 list_for_each_entry(nn, &dev->net_notifier_list, list)
1935 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
1939 * call_netdevice_notifiers_info - call all network notifier blocks
1940 * @val: value passed unmodified to notifier function
1941 * @info: notifier information data
1943 * Call all network notifier blocks. Parameters and return value
1944 * are as for raw_notifier_call_chain().
1947 int call_netdevice_notifiers_info(unsigned long val,
1948 struct netdev_notifier_info *info)
1950 struct net *net = dev_net(info->dev);
1955 /* Run per-netns notifier block chain first, then run the global one.
1956 * Hopefully, one day, the global one is going to be removed after
1957 * all notifier block registrators get converted to be per-netns.
1959 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1960 if (ret & NOTIFY_STOP_MASK)
1962 return raw_notifier_call_chain(&netdev_chain, val, info);
1966 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
1967 * for and rollback on error
1968 * @val_up: value passed unmodified to notifier function
1969 * @val_down: value passed unmodified to the notifier function when
1970 * recovering from an error on @val_up
1971 * @info: notifier information data
1973 * Call all per-netns network notifier blocks, but not notifier blocks on
1974 * the global notifier chain. Parameters and return value are as for
1975 * raw_notifier_call_chain_robust().
1979 call_netdevice_notifiers_info_robust(unsigned long val_up,
1980 unsigned long val_down,
1981 struct netdev_notifier_info *info)
1983 struct net *net = dev_net(info->dev);
1987 return raw_notifier_call_chain_robust(&net->netdev_chain,
1988 val_up, val_down, info);
1991 static int call_netdevice_notifiers_extack(unsigned long val,
1992 struct net_device *dev,
1993 struct netlink_ext_ack *extack)
1995 struct netdev_notifier_info info = {
2000 return call_netdevice_notifiers_info(val, &info);
2004 * call_netdevice_notifiers - call all network notifier blocks
2005 * @val: value passed unmodified to notifier function
2006 * @dev: net_device pointer passed unmodified to notifier function
2008 * Call all network notifier blocks. Parameters and return value
2009 * are as for raw_notifier_call_chain().
2012 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2014 return call_netdevice_notifiers_extack(val, dev, NULL);
2016 EXPORT_SYMBOL(call_netdevice_notifiers);
2019 * call_netdevice_notifiers_mtu - call all network notifier blocks
2020 * @val: value passed unmodified to notifier function
2021 * @dev: net_device pointer passed unmodified to notifier function
2022 * @arg: additional u32 argument passed to the notifier function
2024 * Call all network notifier blocks. Parameters and return value
2025 * are as for raw_notifier_call_chain().
2027 static int call_netdevice_notifiers_mtu(unsigned long val,
2028 struct net_device *dev, u32 arg)
2030 struct netdev_notifier_info_ext info = {
2035 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2037 return call_netdevice_notifiers_info(val, &info.info);
2040 #ifdef CONFIG_NET_INGRESS
2041 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2043 void net_inc_ingress_queue(void)
2045 static_branch_inc(&ingress_needed_key);
2047 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2049 void net_dec_ingress_queue(void)
2051 static_branch_dec(&ingress_needed_key);
2053 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2056 #ifdef CONFIG_NET_EGRESS
2057 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2059 void net_inc_egress_queue(void)
2061 static_branch_inc(&egress_needed_key);
2063 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2065 void net_dec_egress_queue(void)
2067 static_branch_dec(&egress_needed_key);
2069 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2072 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2073 EXPORT_SYMBOL(netstamp_needed_key);
2074 #ifdef CONFIG_JUMP_LABEL
2075 static atomic_t netstamp_needed_deferred;
2076 static atomic_t netstamp_wanted;
2077 static void netstamp_clear(struct work_struct *work)
2079 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2082 wanted = atomic_add_return(deferred, &netstamp_wanted);
2084 static_branch_enable(&netstamp_needed_key);
2086 static_branch_disable(&netstamp_needed_key);
2088 static DECLARE_WORK(netstamp_work, netstamp_clear);
2091 void net_enable_timestamp(void)
2093 #ifdef CONFIG_JUMP_LABEL
2094 int wanted = atomic_read(&netstamp_wanted);
2096 while (wanted > 0) {
2097 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2100 atomic_inc(&netstamp_needed_deferred);
2101 schedule_work(&netstamp_work);
2103 static_branch_inc(&netstamp_needed_key);
2106 EXPORT_SYMBOL(net_enable_timestamp);
2108 void net_disable_timestamp(void)
2110 #ifdef CONFIG_JUMP_LABEL
2111 int wanted = atomic_read(&netstamp_wanted);
2113 while (wanted > 1) {
2114 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2117 atomic_dec(&netstamp_needed_deferred);
2118 schedule_work(&netstamp_work);
2120 static_branch_dec(&netstamp_needed_key);
2123 EXPORT_SYMBOL(net_disable_timestamp);
2125 static inline void net_timestamp_set(struct sk_buff *skb)
2128 skb->mono_delivery_time = 0;
2129 if (static_branch_unlikely(&netstamp_needed_key))
2130 skb->tstamp = ktime_get_real();
2133 #define net_timestamp_check(COND, SKB) \
2134 if (static_branch_unlikely(&netstamp_needed_key)) { \
2135 if ((COND) && !(SKB)->tstamp) \
2136 (SKB)->tstamp = ktime_get_real(); \
2139 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2141 return __is_skb_forwardable(dev, skb, true);
2143 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2145 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2148 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2151 skb->protocol = eth_type_trans(skb, dev);
2152 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2158 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2160 return __dev_forward_skb2(dev, skb, true);
2162 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2165 * dev_forward_skb - loopback an skb to another netif
2167 * @dev: destination network device
2168 * @skb: buffer to forward
2171 * NET_RX_SUCCESS (no congestion)
2172 * NET_RX_DROP (packet was dropped, but freed)
2174 * dev_forward_skb can be used for injecting an skb from the
2175 * start_xmit function of one device into the receive queue
2176 * of another device.
2178 * The receiving device may be in another namespace, so
2179 * we have to clear all information in the skb that could
2180 * impact namespace isolation.
2182 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2184 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2186 EXPORT_SYMBOL_GPL(dev_forward_skb);
2188 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2190 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2193 static inline int deliver_skb(struct sk_buff *skb,
2194 struct packet_type *pt_prev,
2195 struct net_device *orig_dev)
2197 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2199 refcount_inc(&skb->users);
2200 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2203 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2204 struct packet_type **pt,
2205 struct net_device *orig_dev,
2207 struct list_head *ptype_list)
2209 struct packet_type *ptype, *pt_prev = *pt;
2211 list_for_each_entry_rcu(ptype, ptype_list, list) {
2212 if (ptype->type != type)
2215 deliver_skb(skb, pt_prev, orig_dev);
2221 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2223 if (!ptype->af_packet_priv || !skb->sk)
2226 if (ptype->id_match)
2227 return ptype->id_match(ptype, skb->sk);
2228 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2235 * dev_nit_active - return true if any network interface taps are in use
2237 * @dev: network device to check for the presence of taps
2239 bool dev_nit_active(struct net_device *dev)
2241 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2243 EXPORT_SYMBOL_GPL(dev_nit_active);
2246 * Support routine. Sends outgoing frames to any network
2247 * taps currently in use.
2250 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2252 struct packet_type *ptype;
2253 struct sk_buff *skb2 = NULL;
2254 struct packet_type *pt_prev = NULL;
2255 struct list_head *ptype_list = &ptype_all;
2259 list_for_each_entry_rcu(ptype, ptype_list, list) {
2260 if (ptype->ignore_outgoing)
2263 /* Never send packets back to the socket
2266 if (skb_loop_sk(ptype, skb))
2270 deliver_skb(skb2, pt_prev, skb->dev);
2275 /* need to clone skb, done only once */
2276 skb2 = skb_clone(skb, GFP_ATOMIC);
2280 net_timestamp_set(skb2);
2282 /* skb->nh should be correctly
2283 * set by sender, so that the second statement is
2284 * just protection against buggy protocols.
2286 skb_reset_mac_header(skb2);
2288 if (skb_network_header(skb2) < skb2->data ||
2289 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2290 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2291 ntohs(skb2->protocol),
2293 skb_reset_network_header(skb2);
2296 skb2->transport_header = skb2->network_header;
2297 skb2->pkt_type = PACKET_OUTGOING;
2301 if (ptype_list == &ptype_all) {
2302 ptype_list = &dev->ptype_all;
2307 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2308 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2314 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2317 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2318 * @dev: Network device
2319 * @txq: number of queues available
2321 * If real_num_tx_queues is changed the tc mappings may no longer be
2322 * valid. To resolve this verify the tc mapping remains valid and if
2323 * not NULL the mapping. With no priorities mapping to this
2324 * offset/count pair it will no longer be used. In the worst case TC0
2325 * is invalid nothing can be done so disable priority mappings. If is
2326 * expected that drivers will fix this mapping if they can before
2327 * calling netif_set_real_num_tx_queues.
2329 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2332 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2334 /* If TC0 is invalidated disable TC mapping */
2335 if (tc->offset + tc->count > txq) {
2336 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2341 /* Invalidated prio to tc mappings set to TC0 */
2342 for (i = 1; i < TC_BITMASK + 1; i++) {
2343 int q = netdev_get_prio_tc_map(dev, i);
2345 tc = &dev->tc_to_txq[q];
2346 if (tc->offset + tc->count > txq) {
2347 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",
2349 netdev_set_prio_tc_map(dev, i, 0);
2354 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2357 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2360 /* walk through the TCs and see if it falls into any of them */
2361 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2362 if ((txq - tc->offset) < tc->count)
2366 /* didn't find it, just return -1 to indicate no match */
2372 EXPORT_SYMBOL(netdev_txq_to_tc);
2375 static struct static_key xps_needed __read_mostly;
2376 static struct static_key xps_rxqs_needed __read_mostly;
2377 static DEFINE_MUTEX(xps_map_mutex);
2378 #define xmap_dereference(P) \
2379 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2381 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2382 struct xps_dev_maps *old_maps, int tci, u16 index)
2384 struct xps_map *map = NULL;
2388 map = xmap_dereference(dev_maps->attr_map[tci]);
2392 for (pos = map->len; pos--;) {
2393 if (map->queues[pos] != index)
2397 map->queues[pos] = map->queues[--map->len];
2402 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2403 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2404 kfree_rcu(map, rcu);
2411 static bool remove_xps_queue_cpu(struct net_device *dev,
2412 struct xps_dev_maps *dev_maps,
2413 int cpu, u16 offset, u16 count)
2415 int num_tc = dev_maps->num_tc;
2416 bool active = false;
2419 for (tci = cpu * num_tc; num_tc--; tci++) {
2422 for (i = count, j = offset; i--; j++) {
2423 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2433 static void reset_xps_maps(struct net_device *dev,
2434 struct xps_dev_maps *dev_maps,
2435 enum xps_map_type type)
2437 static_key_slow_dec_cpuslocked(&xps_needed);
2438 if (type == XPS_RXQS)
2439 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2441 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2443 kfree_rcu(dev_maps, rcu);
2446 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2447 u16 offset, u16 count)
2449 struct xps_dev_maps *dev_maps;
2450 bool active = false;
2453 dev_maps = xmap_dereference(dev->xps_maps[type]);
2457 for (j = 0; j < dev_maps->nr_ids; j++)
2458 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2460 reset_xps_maps(dev, dev_maps, type);
2462 if (type == XPS_CPUS) {
2463 for (i = offset + (count - 1); count--; i--)
2464 netdev_queue_numa_node_write(
2465 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2469 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2472 if (!static_key_false(&xps_needed))
2476 mutex_lock(&xps_map_mutex);
2478 if (static_key_false(&xps_rxqs_needed))
2479 clean_xps_maps(dev, XPS_RXQS, offset, count);
2481 clean_xps_maps(dev, XPS_CPUS, offset, count);
2483 mutex_unlock(&xps_map_mutex);
2487 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2489 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2492 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2493 u16 index, bool is_rxqs_map)
2495 struct xps_map *new_map;
2496 int alloc_len = XPS_MIN_MAP_ALLOC;
2499 for (pos = 0; map && pos < map->len; pos++) {
2500 if (map->queues[pos] != index)
2505 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2507 if (pos < map->alloc_len)
2510 alloc_len = map->alloc_len * 2;
2513 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2517 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2519 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2520 cpu_to_node(attr_index));
2524 for (i = 0; i < pos; i++)
2525 new_map->queues[i] = map->queues[i];
2526 new_map->alloc_len = alloc_len;
2532 /* Copy xps maps at a given index */
2533 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2534 struct xps_dev_maps *new_dev_maps, int index,
2535 int tc, bool skip_tc)
2537 int i, tci = index * dev_maps->num_tc;
2538 struct xps_map *map;
2540 /* copy maps belonging to foreign traffic classes */
2541 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2542 if (i == tc && skip_tc)
2545 /* fill in the new device map from the old device map */
2546 map = xmap_dereference(dev_maps->attr_map[tci]);
2547 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2551 /* Must be called under cpus_read_lock */
2552 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2553 u16 index, enum xps_map_type type)
2555 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2556 const unsigned long *online_mask = NULL;
2557 bool active = false, copy = false;
2558 int i, j, tci, numa_node_id = -2;
2559 int maps_sz, num_tc = 1, tc = 0;
2560 struct xps_map *map, *new_map;
2561 unsigned int nr_ids;
2563 WARN_ON_ONCE(index >= dev->num_tx_queues);
2566 /* Do not allow XPS on subordinate device directly */
2567 num_tc = dev->num_tc;
2571 /* If queue belongs to subordinate dev use its map */
2572 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2574 tc = netdev_txq_to_tc(dev, index);
2579 mutex_lock(&xps_map_mutex);
2581 dev_maps = xmap_dereference(dev->xps_maps[type]);
2582 if (type == XPS_RXQS) {
2583 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2584 nr_ids = dev->num_rx_queues;
2586 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2587 if (num_possible_cpus() > 1)
2588 online_mask = cpumask_bits(cpu_online_mask);
2589 nr_ids = nr_cpu_ids;
2592 if (maps_sz < L1_CACHE_BYTES)
2593 maps_sz = L1_CACHE_BYTES;
2595 /* The old dev_maps could be larger or smaller than the one we're
2596 * setting up now, as dev->num_tc or nr_ids could have been updated in
2597 * between. We could try to be smart, but let's be safe instead and only
2598 * copy foreign traffic classes if the two map sizes match.
2601 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2604 /* allocate memory for queue storage */
2605 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2607 if (!new_dev_maps) {
2608 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2609 if (!new_dev_maps) {
2610 mutex_unlock(&xps_map_mutex);
2614 new_dev_maps->nr_ids = nr_ids;
2615 new_dev_maps->num_tc = num_tc;
2618 tci = j * num_tc + tc;
2619 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2621 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2625 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2629 goto out_no_new_maps;
2632 /* Increment static keys at most once per type */
2633 static_key_slow_inc_cpuslocked(&xps_needed);
2634 if (type == XPS_RXQS)
2635 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2638 for (j = 0; j < nr_ids; j++) {
2639 bool skip_tc = false;
2641 tci = j * num_tc + tc;
2642 if (netif_attr_test_mask(j, mask, nr_ids) &&
2643 netif_attr_test_online(j, online_mask, nr_ids)) {
2644 /* add tx-queue to CPU/rx-queue maps */
2649 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2650 while ((pos < map->len) && (map->queues[pos] != index))
2653 if (pos == map->len)
2654 map->queues[map->len++] = index;
2656 if (type == XPS_CPUS) {
2657 if (numa_node_id == -2)
2658 numa_node_id = cpu_to_node(j);
2659 else if (numa_node_id != cpu_to_node(j))
2666 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2670 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2672 /* Cleanup old maps */
2674 goto out_no_old_maps;
2676 for (j = 0; j < dev_maps->nr_ids; j++) {
2677 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2678 map = xmap_dereference(dev_maps->attr_map[tci]);
2683 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2688 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2689 kfree_rcu(map, rcu);
2693 old_dev_maps = dev_maps;
2696 dev_maps = new_dev_maps;
2700 if (type == XPS_CPUS)
2701 /* update Tx queue numa node */
2702 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2703 (numa_node_id >= 0) ?
2704 numa_node_id : NUMA_NO_NODE);
2709 /* removes tx-queue from unused CPUs/rx-queues */
2710 for (j = 0; j < dev_maps->nr_ids; j++) {
2711 tci = j * dev_maps->num_tc;
2713 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2715 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2716 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2719 active |= remove_xps_queue(dev_maps,
2720 copy ? old_dev_maps : NULL,
2726 kfree_rcu(old_dev_maps, rcu);
2728 /* free map if not active */
2730 reset_xps_maps(dev, dev_maps, type);
2733 mutex_unlock(&xps_map_mutex);
2737 /* remove any maps that we added */
2738 for (j = 0; j < nr_ids; j++) {
2739 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2740 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2742 xmap_dereference(dev_maps->attr_map[tci]) :
2744 if (new_map && new_map != map)
2749 mutex_unlock(&xps_map_mutex);
2751 kfree(new_dev_maps);
2754 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2756 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2762 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2767 EXPORT_SYMBOL(netif_set_xps_queue);
2770 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2772 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2774 /* Unbind any subordinate channels */
2775 while (txq-- != &dev->_tx[0]) {
2777 netdev_unbind_sb_channel(dev, txq->sb_dev);
2781 void netdev_reset_tc(struct net_device *dev)
2784 netif_reset_xps_queues_gt(dev, 0);
2786 netdev_unbind_all_sb_channels(dev);
2788 /* Reset TC configuration of device */
2790 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2791 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2793 EXPORT_SYMBOL(netdev_reset_tc);
2795 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2797 if (tc >= dev->num_tc)
2801 netif_reset_xps_queues(dev, offset, count);
2803 dev->tc_to_txq[tc].count = count;
2804 dev->tc_to_txq[tc].offset = offset;
2807 EXPORT_SYMBOL(netdev_set_tc_queue);
2809 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2811 if (num_tc > TC_MAX_QUEUE)
2815 netif_reset_xps_queues_gt(dev, 0);
2817 netdev_unbind_all_sb_channels(dev);
2819 dev->num_tc = num_tc;
2822 EXPORT_SYMBOL(netdev_set_num_tc);
2824 void netdev_unbind_sb_channel(struct net_device *dev,
2825 struct net_device *sb_dev)
2827 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2830 netif_reset_xps_queues_gt(sb_dev, 0);
2832 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2833 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2835 while (txq-- != &dev->_tx[0]) {
2836 if (txq->sb_dev == sb_dev)
2840 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2842 int netdev_bind_sb_channel_queue(struct net_device *dev,
2843 struct net_device *sb_dev,
2844 u8 tc, u16 count, u16 offset)
2846 /* Make certain the sb_dev and dev are already configured */
2847 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2850 /* We cannot hand out queues we don't have */
2851 if ((offset + count) > dev->real_num_tx_queues)
2854 /* Record the mapping */
2855 sb_dev->tc_to_txq[tc].count = count;
2856 sb_dev->tc_to_txq[tc].offset = offset;
2858 /* Provide a way for Tx queue to find the tc_to_txq map or
2859 * XPS map for itself.
2862 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2866 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2868 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2870 /* Do not use a multiqueue device to represent a subordinate channel */
2871 if (netif_is_multiqueue(dev))
2874 /* We allow channels 1 - 32767 to be used for subordinate channels.
2875 * Channel 0 is meant to be "native" mode and used only to represent
2876 * the main root device. We allow writing 0 to reset the device back
2877 * to normal mode after being used as a subordinate channel.
2879 if (channel > S16_MAX)
2882 dev->num_tc = -channel;
2886 EXPORT_SYMBOL(netdev_set_sb_channel);
2889 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2890 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2892 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2897 disabling = txq < dev->real_num_tx_queues;
2899 if (txq < 1 || txq > dev->num_tx_queues)
2902 if (dev->reg_state == NETREG_REGISTERED ||
2903 dev->reg_state == NETREG_UNREGISTERING) {
2906 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2912 netif_setup_tc(dev, txq);
2914 dev_qdisc_change_real_num_tx(dev, txq);
2916 dev->real_num_tx_queues = txq;
2920 qdisc_reset_all_tx_gt(dev, txq);
2922 netif_reset_xps_queues_gt(dev, txq);
2926 dev->real_num_tx_queues = txq;
2931 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2935 * netif_set_real_num_rx_queues - set actual number of RX queues used
2936 * @dev: Network device
2937 * @rxq: Actual number of RX queues
2939 * This must be called either with the rtnl_lock held or before
2940 * registration of the net device. Returns 0 on success, or a
2941 * negative error code. If called before registration, it always
2944 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2948 if (rxq < 1 || rxq > dev->num_rx_queues)
2951 if (dev->reg_state == NETREG_REGISTERED) {
2954 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2960 dev->real_num_rx_queues = rxq;
2963 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2967 * netif_set_real_num_queues - set actual number of RX and TX queues used
2968 * @dev: Network device
2969 * @txq: Actual number of TX queues
2970 * @rxq: Actual number of RX queues
2972 * Set the real number of both TX and RX queues.
2973 * Does nothing if the number of queues is already correct.
2975 int netif_set_real_num_queues(struct net_device *dev,
2976 unsigned int txq, unsigned int rxq)
2978 unsigned int old_rxq = dev->real_num_rx_queues;
2981 if (txq < 1 || txq > dev->num_tx_queues ||
2982 rxq < 1 || rxq > dev->num_rx_queues)
2985 /* Start from increases, so the error path only does decreases -
2986 * decreases can't fail.
2988 if (rxq > dev->real_num_rx_queues) {
2989 err = netif_set_real_num_rx_queues(dev, rxq);
2993 if (txq > dev->real_num_tx_queues) {
2994 err = netif_set_real_num_tx_queues(dev, txq);
2998 if (rxq < dev->real_num_rx_queues)
2999 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3000 if (txq < dev->real_num_tx_queues)
3001 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3005 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3008 EXPORT_SYMBOL(netif_set_real_num_queues);
3011 * netif_set_tso_max_size() - set the max size of TSO frames supported
3012 * @dev: netdev to update
3013 * @size: max skb->len of a TSO frame
3015 * Set the limit on the size of TSO super-frames the device can handle.
3016 * Unless explicitly set the stack will assume the value of
3017 * %GSO_LEGACY_MAX_SIZE.
3019 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3021 dev->tso_max_size = min(GSO_MAX_SIZE, size);
3022 if (size < READ_ONCE(dev->gso_max_size))
3023 netif_set_gso_max_size(dev, size);
3024 if (size < READ_ONCE(dev->gso_ipv4_max_size))
3025 netif_set_gso_ipv4_max_size(dev, size);
3027 EXPORT_SYMBOL(netif_set_tso_max_size);
3030 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3031 * @dev: netdev to update
3032 * @segs: max number of TCP segments
3034 * Set the limit on the number of TCP segments the device can generate from
3035 * a single TSO super-frame.
3036 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3038 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3040 dev->tso_max_segs = segs;
3041 if (segs < READ_ONCE(dev->gso_max_segs))
3042 netif_set_gso_max_segs(dev, segs);
3044 EXPORT_SYMBOL(netif_set_tso_max_segs);
3047 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3048 * @to: netdev to update
3049 * @from: netdev from which to copy the limits
3051 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3053 netif_set_tso_max_size(to, from->tso_max_size);
3054 netif_set_tso_max_segs(to, from->tso_max_segs);
3056 EXPORT_SYMBOL(netif_inherit_tso_max);
3059 * netif_get_num_default_rss_queues - default number of RSS queues
3061 * Default value is the number of physical cores if there are only 1 or 2, or
3062 * divided by 2 if there are more.
3064 int netif_get_num_default_rss_queues(void)
3069 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3072 cpumask_copy(cpus, cpu_online_mask);
3073 for_each_cpu(cpu, cpus) {
3075 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3077 free_cpumask_var(cpus);
3079 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3081 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3083 static void __netif_reschedule(struct Qdisc *q)
3085 struct softnet_data *sd;
3086 unsigned long flags;
3088 local_irq_save(flags);
3089 sd = this_cpu_ptr(&softnet_data);
3090 q->next_sched = NULL;
3091 *sd->output_queue_tailp = q;
3092 sd->output_queue_tailp = &q->next_sched;
3093 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3094 local_irq_restore(flags);
3097 void __netif_schedule(struct Qdisc *q)
3099 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3100 __netif_reschedule(q);
3102 EXPORT_SYMBOL(__netif_schedule);
3104 struct dev_kfree_skb_cb {
3105 enum skb_drop_reason reason;
3108 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3110 return (struct dev_kfree_skb_cb *)skb->cb;
3113 void netif_schedule_queue(struct netdev_queue *txq)
3116 if (!netif_xmit_stopped(txq)) {
3117 struct Qdisc *q = rcu_dereference(txq->qdisc);
3119 __netif_schedule(q);
3123 EXPORT_SYMBOL(netif_schedule_queue);
3125 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3127 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3131 q = rcu_dereference(dev_queue->qdisc);
3132 __netif_schedule(q);
3136 EXPORT_SYMBOL(netif_tx_wake_queue);
3138 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3140 unsigned long flags;
3145 if (likely(refcount_read(&skb->users) == 1)) {
3147 refcount_set(&skb->users, 0);
3148 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3151 get_kfree_skb_cb(skb)->reason = reason;
3152 local_irq_save(flags);
3153 skb->next = __this_cpu_read(softnet_data.completion_queue);
3154 __this_cpu_write(softnet_data.completion_queue, skb);
3155 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3156 local_irq_restore(flags);
3158 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3160 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3162 if (in_hardirq() || irqs_disabled())
3163 dev_kfree_skb_irq_reason(skb, reason);
3165 kfree_skb_reason(skb, reason);
3167 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3171 * netif_device_detach - mark device as removed
3172 * @dev: network device
3174 * Mark device as removed from system and therefore no longer available.
3176 void netif_device_detach(struct net_device *dev)
3178 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3179 netif_running(dev)) {
3180 netif_tx_stop_all_queues(dev);
3183 EXPORT_SYMBOL(netif_device_detach);
3186 * netif_device_attach - mark device as attached
3187 * @dev: network device
3189 * Mark device as attached from system and restart if needed.
3191 void netif_device_attach(struct net_device *dev)
3193 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3194 netif_running(dev)) {
3195 netif_tx_wake_all_queues(dev);
3196 __netdev_watchdog_up(dev);
3199 EXPORT_SYMBOL(netif_device_attach);
3202 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3203 * to be used as a distribution range.
3205 static u16 skb_tx_hash(const struct net_device *dev,
3206 const struct net_device *sb_dev,
3207 struct sk_buff *skb)
3211 u16 qcount = dev->real_num_tx_queues;
3214 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3216 qoffset = sb_dev->tc_to_txq[tc].offset;
3217 qcount = sb_dev->tc_to_txq[tc].count;
3218 if (unlikely(!qcount)) {
3219 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3220 sb_dev->name, qoffset, tc);
3222 qcount = dev->real_num_tx_queues;
3226 if (skb_rx_queue_recorded(skb)) {
3227 DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3228 hash = skb_get_rx_queue(skb);
3229 if (hash >= qoffset)
3231 while (unlikely(hash >= qcount))
3233 return hash + qoffset;
3236 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3239 void skb_warn_bad_offload(const struct sk_buff *skb)
3241 static const netdev_features_t null_features;
3242 struct net_device *dev = skb->dev;
3243 const char *name = "";
3245 if (!net_ratelimit())
3249 if (dev->dev.parent)
3250 name = dev_driver_string(dev->dev.parent);
3252 name = netdev_name(dev);
3254 skb_dump(KERN_WARNING, skb, false);
3255 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3256 name, dev ? &dev->features : &null_features,
3257 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3261 * Invalidate hardware checksum when packet is to be mangled, and
3262 * complete checksum manually on outgoing path.
3264 int skb_checksum_help(struct sk_buff *skb)
3267 int ret = 0, offset;
3269 if (skb->ip_summed == CHECKSUM_COMPLETE)
3270 goto out_set_summed;
3272 if (unlikely(skb_is_gso(skb))) {
3273 skb_warn_bad_offload(skb);
3277 /* Before computing a checksum, we should make sure no frag could
3278 * be modified by an external entity : checksum could be wrong.
3280 if (skb_has_shared_frag(skb)) {
3281 ret = __skb_linearize(skb);
3286 offset = skb_checksum_start_offset(skb);
3288 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3289 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3292 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3294 offset += skb->csum_offset;
3295 if (WARN_ON_ONCE(offset + sizeof(__sum16) > skb_headlen(skb))) {
3296 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3299 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3303 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3305 skb->ip_summed = CHECKSUM_NONE;
3309 EXPORT_SYMBOL(skb_checksum_help);
3311 int skb_crc32c_csum_help(struct sk_buff *skb)
3314 int ret = 0, offset, start;
3316 if (skb->ip_summed != CHECKSUM_PARTIAL)
3319 if (unlikely(skb_is_gso(skb)))
3322 /* Before computing a checksum, we should make sure no frag could
3323 * be modified by an external entity : checksum could be wrong.
3325 if (unlikely(skb_has_shared_frag(skb))) {
3326 ret = __skb_linearize(skb);
3330 start = skb_checksum_start_offset(skb);
3331 offset = start + offsetof(struct sctphdr, checksum);
3332 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3337 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3341 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3342 skb->len - start, ~(__u32)0,
3344 *(__le32 *)(skb->data + offset) = crc32c_csum;
3345 skb_reset_csum_not_inet(skb);
3350 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3352 __be16 type = skb->protocol;
3354 /* Tunnel gso handlers can set protocol to ethernet. */
3355 if (type == htons(ETH_P_TEB)) {
3358 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3361 eth = (struct ethhdr *)skb->data;
3362 type = eth->h_proto;
3365 return vlan_get_protocol_and_depth(skb, type, depth);
3369 /* Take action when hardware reception checksum errors are detected. */
3371 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3373 netdev_err(dev, "hw csum failure\n");
3374 skb_dump(KERN_ERR, skb, true);
3378 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3380 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3382 EXPORT_SYMBOL(netdev_rx_csum_fault);
3385 /* XXX: check that highmem exists at all on the given machine. */
3386 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3388 #ifdef CONFIG_HIGHMEM
3391 if (!(dev->features & NETIF_F_HIGHDMA)) {
3392 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3393 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3395 if (PageHighMem(skb_frag_page(frag)))
3403 /* If MPLS offload request, verify we are testing hardware MPLS features
3404 * instead of standard features for the netdev.
3406 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3407 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3408 netdev_features_t features,
3411 if (eth_p_mpls(type))
3412 features &= skb->dev->mpls_features;
3417 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3418 netdev_features_t features,
3425 static netdev_features_t harmonize_features(struct sk_buff *skb,
3426 netdev_features_t features)
3430 type = skb_network_protocol(skb, NULL);
3431 features = net_mpls_features(skb, features, type);
3433 if (skb->ip_summed != CHECKSUM_NONE &&
3434 !can_checksum_protocol(features, type)) {
3435 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3437 if (illegal_highdma(skb->dev, skb))
3438 features &= ~NETIF_F_SG;
3443 netdev_features_t passthru_features_check(struct sk_buff *skb,
3444 struct net_device *dev,
3445 netdev_features_t features)
3449 EXPORT_SYMBOL(passthru_features_check);
3451 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3452 struct net_device *dev,
3453 netdev_features_t features)
3455 return vlan_features_check(skb, features);
3458 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3459 struct net_device *dev,
3460 netdev_features_t features)
3462 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3464 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3465 return features & ~NETIF_F_GSO_MASK;
3467 if (!skb_shinfo(skb)->gso_type) {
3468 skb_warn_bad_offload(skb);
3469 return features & ~NETIF_F_GSO_MASK;
3472 /* Support for GSO partial features requires software
3473 * intervention before we can actually process the packets
3474 * so we need to strip support for any partial features now
3475 * and we can pull them back in after we have partially
3476 * segmented the frame.
3478 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3479 features &= ~dev->gso_partial_features;
3481 /* Make sure to clear the IPv4 ID mangling feature if the
3482 * IPv4 header has the potential to be fragmented.
3484 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3485 struct iphdr *iph = skb->encapsulation ?
3486 inner_ip_hdr(skb) : ip_hdr(skb);
3488 if (!(iph->frag_off & htons(IP_DF)))
3489 features &= ~NETIF_F_TSO_MANGLEID;
3495 netdev_features_t netif_skb_features(struct sk_buff *skb)
3497 struct net_device *dev = skb->dev;
3498 netdev_features_t features = dev->features;
3500 if (skb_is_gso(skb))
3501 features = gso_features_check(skb, dev, features);
3503 /* If encapsulation offload request, verify we are testing
3504 * hardware encapsulation features instead of standard
3505 * features for the netdev
3507 if (skb->encapsulation)
3508 features &= dev->hw_enc_features;
3510 if (skb_vlan_tagged(skb))
3511 features = netdev_intersect_features(features,
3512 dev->vlan_features |
3513 NETIF_F_HW_VLAN_CTAG_TX |
3514 NETIF_F_HW_VLAN_STAG_TX);
3516 if (dev->netdev_ops->ndo_features_check)
3517 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3520 features &= dflt_features_check(skb, dev, features);
3522 return harmonize_features(skb, features);
3524 EXPORT_SYMBOL(netif_skb_features);
3526 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3527 struct netdev_queue *txq, bool more)
3532 if (dev_nit_active(dev))
3533 dev_queue_xmit_nit(skb, dev);
3536 trace_net_dev_start_xmit(skb, dev);
3537 rc = netdev_start_xmit(skb, dev, txq, more);
3538 trace_net_dev_xmit(skb, rc, dev, len);
3543 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3544 struct netdev_queue *txq, int *ret)
3546 struct sk_buff *skb = first;
3547 int rc = NETDEV_TX_OK;
3550 struct sk_buff *next = skb->next;
3552 skb_mark_not_on_list(skb);
3553 rc = xmit_one(skb, dev, txq, next != NULL);
3554 if (unlikely(!dev_xmit_complete(rc))) {
3560 if (netif_tx_queue_stopped(txq) && skb) {
3561 rc = NETDEV_TX_BUSY;
3571 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3572 netdev_features_t features)
3574 if (skb_vlan_tag_present(skb) &&
3575 !vlan_hw_offload_capable(features, skb->vlan_proto))
3576 skb = __vlan_hwaccel_push_inside(skb);
3580 int skb_csum_hwoffload_help(struct sk_buff *skb,
3581 const netdev_features_t features)
3583 if (unlikely(skb_csum_is_sctp(skb)))
3584 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3585 skb_crc32c_csum_help(skb);
3587 if (features & NETIF_F_HW_CSUM)
3590 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3591 switch (skb->csum_offset) {
3592 case offsetof(struct tcphdr, check):
3593 case offsetof(struct udphdr, check):
3598 return skb_checksum_help(skb);
3600 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3602 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3604 netdev_features_t features;
3606 features = netif_skb_features(skb);
3607 skb = validate_xmit_vlan(skb, features);
3611 skb = sk_validate_xmit_skb(skb, dev);
3615 if (netif_needs_gso(skb, features)) {
3616 struct sk_buff *segs;
3618 segs = skb_gso_segment(skb, features);
3626 if (skb_needs_linearize(skb, features) &&
3627 __skb_linearize(skb))
3630 /* If packet is not checksummed and device does not
3631 * support checksumming for this protocol, complete
3632 * checksumming here.
3634 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3635 if (skb->encapsulation)
3636 skb_set_inner_transport_header(skb,
3637 skb_checksum_start_offset(skb));
3639 skb_set_transport_header(skb,
3640 skb_checksum_start_offset(skb));
3641 if (skb_csum_hwoffload_help(skb, features))
3646 skb = validate_xmit_xfrm(skb, features, again);
3653 dev_core_stats_tx_dropped_inc(dev);
3657 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3659 struct sk_buff *next, *head = NULL, *tail;
3661 for (; skb != NULL; skb = next) {
3663 skb_mark_not_on_list(skb);
3665 /* in case skb wont be segmented, point to itself */
3668 skb = validate_xmit_skb(skb, dev, again);
3676 /* If skb was segmented, skb->prev points to
3677 * the last segment. If not, it still contains skb.
3683 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3685 static void qdisc_pkt_len_init(struct sk_buff *skb)
3687 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3689 qdisc_skb_cb(skb)->pkt_len = skb->len;
3691 /* To get more precise estimation of bytes sent on wire,
3692 * we add to pkt_len the headers size of all segments
3694 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3695 u16 gso_segs = shinfo->gso_segs;
3696 unsigned int hdr_len;
3698 /* mac layer + network layer */
3699 hdr_len = skb_transport_offset(skb);
3701 /* + transport layer */
3702 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3703 const struct tcphdr *th;
3704 struct tcphdr _tcphdr;
3706 th = skb_header_pointer(skb, hdr_len,
3707 sizeof(_tcphdr), &_tcphdr);
3709 hdr_len += __tcp_hdrlen(th);
3711 struct udphdr _udphdr;
3713 if (skb_header_pointer(skb, hdr_len,
3714 sizeof(_udphdr), &_udphdr))
3715 hdr_len += sizeof(struct udphdr);
3718 if (shinfo->gso_type & SKB_GSO_DODGY)
3719 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3722 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3726 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3727 struct sk_buff **to_free,
3728 struct netdev_queue *txq)
3732 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3733 if (rc == NET_XMIT_SUCCESS)
3734 trace_qdisc_enqueue(q, txq, skb);
3738 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3739 struct net_device *dev,
3740 struct netdev_queue *txq)
3742 spinlock_t *root_lock = qdisc_lock(q);
3743 struct sk_buff *to_free = NULL;
3747 qdisc_calculate_pkt_len(skb, q);
3749 if (q->flags & TCQ_F_NOLOCK) {
3750 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3751 qdisc_run_begin(q)) {
3752 /* Retest nolock_qdisc_is_empty() within the protection
3753 * of q->seqlock to protect from racing with requeuing.
3755 if (unlikely(!nolock_qdisc_is_empty(q))) {
3756 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3763 qdisc_bstats_cpu_update(q, skb);
3764 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3765 !nolock_qdisc_is_empty(q))
3769 return NET_XMIT_SUCCESS;
3772 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3776 if (unlikely(to_free))
3777 kfree_skb_list_reason(to_free,
3778 SKB_DROP_REASON_QDISC_DROP);
3783 * Heuristic to force contended enqueues to serialize on a
3784 * separate lock before trying to get qdisc main lock.
3785 * This permits qdisc->running owner to get the lock more
3786 * often and dequeue packets faster.
3787 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3788 * and then other tasks will only enqueue packets. The packets will be
3789 * sent after the qdisc owner is scheduled again. To prevent this
3790 * scenario the task always serialize on the lock.
3792 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3793 if (unlikely(contended))
3794 spin_lock(&q->busylock);
3796 spin_lock(root_lock);
3797 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3798 __qdisc_drop(skb, &to_free);
3800 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3801 qdisc_run_begin(q)) {
3803 * This is a work-conserving queue; there are no old skbs
3804 * waiting to be sent out; and the qdisc is not running -
3805 * xmit the skb directly.
3808 qdisc_bstats_update(q, skb);
3810 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3811 if (unlikely(contended)) {
3812 spin_unlock(&q->busylock);
3819 rc = NET_XMIT_SUCCESS;
3821 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3822 if (qdisc_run_begin(q)) {
3823 if (unlikely(contended)) {
3824 spin_unlock(&q->busylock);
3831 spin_unlock(root_lock);
3832 if (unlikely(to_free))
3833 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP);
3834 if (unlikely(contended))
3835 spin_unlock(&q->busylock);
3839 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3840 static void skb_update_prio(struct sk_buff *skb)
3842 const struct netprio_map *map;
3843 const struct sock *sk;
3844 unsigned int prioidx;
3848 map = rcu_dereference_bh(skb->dev->priomap);
3851 sk = skb_to_full_sk(skb);
3855 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3857 if (prioidx < map->priomap_len)
3858 skb->priority = map->priomap[prioidx];
3861 #define skb_update_prio(skb)
3865 * dev_loopback_xmit - loop back @skb
3866 * @net: network namespace this loopback is happening in
3867 * @sk: sk needed to be a netfilter okfn
3868 * @skb: buffer to transmit
3870 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3872 skb_reset_mac_header(skb);
3873 __skb_pull(skb, skb_network_offset(skb));
3874 skb->pkt_type = PACKET_LOOPBACK;
3875 if (skb->ip_summed == CHECKSUM_NONE)
3876 skb->ip_summed = CHECKSUM_UNNECESSARY;
3877 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
3882 EXPORT_SYMBOL(dev_loopback_xmit);
3884 #ifdef CONFIG_NET_EGRESS
3885 static struct sk_buff *
3886 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3888 #ifdef CONFIG_NET_CLS_ACT
3889 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3890 struct tcf_result cl_res;
3895 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3896 tc_skb_cb(skb)->mru = 0;
3897 tc_skb_cb(skb)->post_ct = false;
3898 mini_qdisc_bstats_cpu_update(miniq, skb);
3900 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
3902 case TC_ACT_RECLASSIFY:
3903 skb->tc_index = TC_H_MIN(cl_res.classid);
3906 mini_qdisc_qstats_cpu_drop(miniq);
3907 *ret = NET_XMIT_DROP;
3908 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS);
3913 *ret = NET_XMIT_SUCCESS;
3916 case TC_ACT_REDIRECT:
3917 /* No need to push/pop skb's mac_header here on egress! */
3918 skb_do_redirect(skb);
3919 *ret = NET_XMIT_SUCCESS;
3924 #endif /* CONFIG_NET_CLS_ACT */
3929 static struct netdev_queue *
3930 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
3932 int qm = skb_get_queue_mapping(skb);
3934 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
3937 static bool netdev_xmit_txqueue_skipped(void)
3939 return __this_cpu_read(softnet_data.xmit.skip_txqueue);
3942 void netdev_xmit_skip_txqueue(bool skip)
3944 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
3946 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3947 #endif /* CONFIG_NET_EGRESS */
3950 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3951 struct xps_dev_maps *dev_maps, unsigned int tci)
3953 int tc = netdev_get_prio_tc_map(dev, skb->priority);
3954 struct xps_map *map;
3955 int queue_index = -1;
3957 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
3960 tci *= dev_maps->num_tc;
3963 map = rcu_dereference(dev_maps->attr_map[tci]);
3966 queue_index = map->queues[0];
3968 queue_index = map->queues[reciprocal_scale(
3969 skb_get_hash(skb), map->len)];
3970 if (unlikely(queue_index >= dev->real_num_tx_queues))
3977 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3978 struct sk_buff *skb)
3981 struct xps_dev_maps *dev_maps;
3982 struct sock *sk = skb->sk;
3983 int queue_index = -1;
3985 if (!static_key_false(&xps_needed))
3989 if (!static_key_false(&xps_rxqs_needed))
3992 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
3994 int tci = sk_rx_queue_get(sk);
3997 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4002 if (queue_index < 0) {
4003 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
4005 unsigned int tci = skb->sender_cpu - 1;
4007 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4019 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
4020 struct net_device *sb_dev)
4024 EXPORT_SYMBOL(dev_pick_tx_zero);
4026 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4027 struct net_device *sb_dev)
4029 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4031 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4033 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4034 struct net_device *sb_dev)
4036 struct sock *sk = skb->sk;
4037 int queue_index = sk_tx_queue_get(sk);
4039 sb_dev = sb_dev ? : dev;
4041 if (queue_index < 0 || skb->ooo_okay ||
4042 queue_index >= dev->real_num_tx_queues) {
4043 int new_index = get_xps_queue(dev, sb_dev, skb);
4046 new_index = skb_tx_hash(dev, sb_dev, skb);
4048 if (queue_index != new_index && sk &&
4050 rcu_access_pointer(sk->sk_dst_cache))
4051 sk_tx_queue_set(sk, new_index);
4053 queue_index = new_index;
4058 EXPORT_SYMBOL(netdev_pick_tx);
4060 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4061 struct sk_buff *skb,
4062 struct net_device *sb_dev)
4064 int queue_index = 0;
4067 u32 sender_cpu = skb->sender_cpu - 1;
4069 if (sender_cpu >= (u32)NR_CPUS)
4070 skb->sender_cpu = raw_smp_processor_id() + 1;
4073 if (dev->real_num_tx_queues != 1) {
4074 const struct net_device_ops *ops = dev->netdev_ops;
4076 if (ops->ndo_select_queue)
4077 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4079 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4081 queue_index = netdev_cap_txqueue(dev, queue_index);
4084 skb_set_queue_mapping(skb, queue_index);
4085 return netdev_get_tx_queue(dev, queue_index);
4089 * __dev_queue_xmit() - transmit a buffer
4090 * @skb: buffer to transmit
4091 * @sb_dev: suboordinate device used for L2 forwarding offload
4093 * Queue a buffer for transmission to a network device. The caller must
4094 * have set the device and priority and built the buffer before calling
4095 * this function. The function can be called from an interrupt.
4097 * When calling this method, interrupts MUST be enabled. This is because
4098 * the BH enable code must have IRQs enabled so that it will not deadlock.
4100 * Regardless of the return value, the skb is consumed, so it is currently
4101 * difficult to retry a send to this method. (You can bump the ref count
4102 * before sending to hold a reference for retry if you are careful.)
4105 * * 0 - buffer successfully transmitted
4106 * * positive qdisc return code - NET_XMIT_DROP etc.
4107 * * negative errno - other errors
4109 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4111 struct net_device *dev = skb->dev;
4112 struct netdev_queue *txq = NULL;
4117 skb_reset_mac_header(skb);
4118 skb_assert_len(skb);
4120 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4121 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4123 /* Disable soft irqs for various locks below. Also
4124 * stops preemption for RCU.
4128 skb_update_prio(skb);
4130 qdisc_pkt_len_init(skb);
4131 #ifdef CONFIG_NET_CLS_ACT
4132 skb->tc_at_ingress = 0;
4134 #ifdef CONFIG_NET_EGRESS
4135 if (static_branch_unlikely(&egress_needed_key)) {
4136 if (nf_hook_egress_active()) {
4137 skb = nf_hook_egress(skb, &rc, dev);
4142 netdev_xmit_skip_txqueue(false);
4144 nf_skip_egress(skb, true);
4145 skb = sch_handle_egress(skb, &rc, dev);
4148 nf_skip_egress(skb, false);
4150 if (netdev_xmit_txqueue_skipped())
4151 txq = netdev_tx_queue_mapping(dev, skb);
4154 /* If device/qdisc don't need skb->dst, release it right now while
4155 * its hot in this cpu cache.
4157 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4163 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4165 q = rcu_dereference_bh(txq->qdisc);
4167 trace_net_dev_queue(skb);
4169 rc = __dev_xmit_skb(skb, q, dev, txq);
4173 /* The device has no queue. Common case for software devices:
4174 * loopback, all the sorts of tunnels...
4176 * Really, it is unlikely that netif_tx_lock protection is necessary
4177 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4179 * However, it is possible, that they rely on protection
4182 * Check this and shot the lock. It is not prone from deadlocks.
4183 *Either shot noqueue qdisc, it is even simpler 8)
4185 if (dev->flags & IFF_UP) {
4186 int cpu = smp_processor_id(); /* ok because BHs are off */
4188 /* Other cpus might concurrently change txq->xmit_lock_owner
4189 * to -1 or to their cpu id, but not to our id.
4191 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4192 if (dev_xmit_recursion())
4193 goto recursion_alert;
4195 skb = validate_xmit_skb(skb, dev, &again);
4199 HARD_TX_LOCK(dev, txq, cpu);
4201 if (!netif_xmit_stopped(txq)) {
4202 dev_xmit_recursion_inc();
4203 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4204 dev_xmit_recursion_dec();
4205 if (dev_xmit_complete(rc)) {
4206 HARD_TX_UNLOCK(dev, txq);
4210 HARD_TX_UNLOCK(dev, txq);
4211 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4214 /* Recursion is detected! It is possible,
4218 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4224 rcu_read_unlock_bh();
4226 dev_core_stats_tx_dropped_inc(dev);
4227 kfree_skb_list(skb);
4230 rcu_read_unlock_bh();
4233 EXPORT_SYMBOL(__dev_queue_xmit);
4235 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4237 struct net_device *dev = skb->dev;
4238 struct sk_buff *orig_skb = skb;
4239 struct netdev_queue *txq;
4240 int ret = NETDEV_TX_BUSY;
4243 if (unlikely(!netif_running(dev) ||
4244 !netif_carrier_ok(dev)))
4247 skb = validate_xmit_skb_list(skb, dev, &again);
4248 if (skb != orig_skb)
4251 skb_set_queue_mapping(skb, queue_id);
4252 txq = skb_get_tx_queue(dev, skb);
4256 dev_xmit_recursion_inc();
4257 HARD_TX_LOCK(dev, txq, smp_processor_id());
4258 if (!netif_xmit_frozen_or_drv_stopped(txq))
4259 ret = netdev_start_xmit(skb, dev, txq, false);
4260 HARD_TX_UNLOCK(dev, txq);
4261 dev_xmit_recursion_dec();
4266 dev_core_stats_tx_dropped_inc(dev);
4267 kfree_skb_list(skb);
4268 return NET_XMIT_DROP;
4270 EXPORT_SYMBOL(__dev_direct_xmit);
4272 /*************************************************************************
4274 *************************************************************************/
4276 int netdev_max_backlog __read_mostly = 1000;
4277 EXPORT_SYMBOL(netdev_max_backlog);
4279 int netdev_tstamp_prequeue __read_mostly = 1;
4280 unsigned int sysctl_skb_defer_max __read_mostly = 64;
4281 int netdev_budget __read_mostly = 300;
4282 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4283 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4284 int weight_p __read_mostly = 64; /* old backlog weight */
4285 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4286 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4287 int dev_rx_weight __read_mostly = 64;
4288 int dev_tx_weight __read_mostly = 64;
4290 /* Called with irq disabled */
4291 static inline void ____napi_schedule(struct softnet_data *sd,
4292 struct napi_struct *napi)
4294 struct task_struct *thread;
4296 lockdep_assert_irqs_disabled();
4298 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4299 /* Paired with smp_mb__before_atomic() in
4300 * napi_enable()/dev_set_threaded().
4301 * Use READ_ONCE() to guarantee a complete
4302 * read on napi->thread. Only call
4303 * wake_up_process() when it's not NULL.
4305 thread = READ_ONCE(napi->thread);
4307 /* Avoid doing set_bit() if the thread is in
4308 * INTERRUPTIBLE state, cause napi_thread_wait()
4309 * makes sure to proceed with napi polling
4310 * if the thread is explicitly woken from here.
4312 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4313 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4314 wake_up_process(thread);
4319 list_add_tail(&napi->poll_list, &sd->poll_list);
4320 WRITE_ONCE(napi->list_owner, smp_processor_id());
4321 /* If not called from net_rx_action()
4322 * we have to raise NET_RX_SOFTIRQ.
4324 if (!sd->in_net_rx_action)
4325 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4330 /* One global table that all flow-based protocols share. */
4331 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4332 EXPORT_SYMBOL(rps_sock_flow_table);
4333 u32 rps_cpu_mask __read_mostly;
4334 EXPORT_SYMBOL(rps_cpu_mask);
4336 struct static_key_false rps_needed __read_mostly;
4337 EXPORT_SYMBOL(rps_needed);
4338 struct static_key_false rfs_needed __read_mostly;
4339 EXPORT_SYMBOL(rfs_needed);
4341 static struct rps_dev_flow *
4342 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4343 struct rps_dev_flow *rflow, u16 next_cpu)
4345 if (next_cpu < nr_cpu_ids) {
4346 #ifdef CONFIG_RFS_ACCEL
4347 struct netdev_rx_queue *rxqueue;
4348 struct rps_dev_flow_table *flow_table;
4349 struct rps_dev_flow *old_rflow;
4354 /* Should we steer this flow to a different hardware queue? */
4355 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4356 !(dev->features & NETIF_F_NTUPLE))
4358 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4359 if (rxq_index == skb_get_rx_queue(skb))
4362 rxqueue = dev->_rx + rxq_index;
4363 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4366 flow_id = skb_get_hash(skb) & flow_table->mask;
4367 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4368 rxq_index, flow_id);
4372 rflow = &flow_table->flows[flow_id];
4374 if (old_rflow->filter == rflow->filter)
4375 old_rflow->filter = RPS_NO_FILTER;
4379 per_cpu(softnet_data, next_cpu).input_queue_head;
4382 rflow->cpu = next_cpu;
4387 * get_rps_cpu is called from netif_receive_skb and returns the target
4388 * CPU from the RPS map of the receiving queue for a given skb.
4389 * rcu_read_lock must be held on entry.
4391 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4392 struct rps_dev_flow **rflowp)
4394 const struct rps_sock_flow_table *sock_flow_table;
4395 struct netdev_rx_queue *rxqueue = dev->_rx;
4396 struct rps_dev_flow_table *flow_table;
4397 struct rps_map *map;
4402 if (skb_rx_queue_recorded(skb)) {
4403 u16 index = skb_get_rx_queue(skb);
4405 if (unlikely(index >= dev->real_num_rx_queues)) {
4406 WARN_ONCE(dev->real_num_rx_queues > 1,
4407 "%s received packet on queue %u, but number "
4408 "of RX queues is %u\n",
4409 dev->name, index, dev->real_num_rx_queues);
4415 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4417 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4418 map = rcu_dereference(rxqueue->rps_map);
4419 if (!flow_table && !map)
4422 skb_reset_network_header(skb);
4423 hash = skb_get_hash(skb);
4427 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4428 if (flow_table && sock_flow_table) {
4429 struct rps_dev_flow *rflow;
4433 /* First check into global flow table if there is a match.
4434 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
4436 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
4437 if ((ident ^ hash) & ~rps_cpu_mask)
4440 next_cpu = ident & rps_cpu_mask;
4442 /* OK, now we know there is a match,
4443 * we can look at the local (per receive queue) flow table
4445 rflow = &flow_table->flows[hash & flow_table->mask];
4449 * If the desired CPU (where last recvmsg was done) is
4450 * different from current CPU (one in the rx-queue flow
4451 * table entry), switch if one of the following holds:
4452 * - Current CPU is unset (>= nr_cpu_ids).
4453 * - Current CPU is offline.
4454 * - The current CPU's queue tail has advanced beyond the
4455 * last packet that was enqueued using this table entry.
4456 * This guarantees that all previous packets for the flow
4457 * have been dequeued, thus preserving in order delivery.
4459 if (unlikely(tcpu != next_cpu) &&
4460 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4461 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4462 rflow->last_qtail)) >= 0)) {
4464 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4467 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4477 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4478 if (cpu_online(tcpu)) {
4488 #ifdef CONFIG_RFS_ACCEL
4491 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4492 * @dev: Device on which the filter was set
4493 * @rxq_index: RX queue index
4494 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4495 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4497 * Drivers that implement ndo_rx_flow_steer() should periodically call
4498 * this function for each installed filter and remove the filters for
4499 * which it returns %true.
4501 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4502 u32 flow_id, u16 filter_id)
4504 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4505 struct rps_dev_flow_table *flow_table;
4506 struct rps_dev_flow *rflow;
4511 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4512 if (flow_table && flow_id <= flow_table->mask) {
4513 rflow = &flow_table->flows[flow_id];
4514 cpu = READ_ONCE(rflow->cpu);
4515 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4516 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4517 rflow->last_qtail) <
4518 (int)(10 * flow_table->mask)))
4524 EXPORT_SYMBOL(rps_may_expire_flow);
4526 #endif /* CONFIG_RFS_ACCEL */
4528 /* Called from hardirq (IPI) context */
4529 static void rps_trigger_softirq(void *data)
4531 struct softnet_data *sd = data;
4533 ____napi_schedule(sd, &sd->backlog);
4537 #endif /* CONFIG_RPS */
4539 /* Called from hardirq (IPI) context */
4540 static void trigger_rx_softirq(void *data)
4542 struct softnet_data *sd = data;
4544 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4545 smp_store_release(&sd->defer_ipi_scheduled, 0);
4549 * After we queued a packet into sd->input_pkt_queue,
4550 * we need to make sure this queue is serviced soon.
4552 * - If this is another cpu queue, link it to our rps_ipi_list,
4553 * and make sure we will process rps_ipi_list from net_rx_action().
4555 * - If this is our own queue, NAPI schedule our backlog.
4556 * Note that this also raises NET_RX_SOFTIRQ.
4558 static void napi_schedule_rps(struct softnet_data *sd)
4560 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4564 sd->rps_ipi_next = mysd->rps_ipi_list;
4565 mysd->rps_ipi_list = sd;
4567 /* If not called from net_rx_action() or napi_threaded_poll()
4568 * we have to raise NET_RX_SOFTIRQ.
4570 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
4571 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4574 #endif /* CONFIG_RPS */
4575 __napi_schedule_irqoff(&mysd->backlog);
4578 #ifdef CONFIG_NET_FLOW_LIMIT
4579 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4582 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4584 #ifdef CONFIG_NET_FLOW_LIMIT
4585 struct sd_flow_limit *fl;
4586 struct softnet_data *sd;
4587 unsigned int old_flow, new_flow;
4589 if (qlen < (READ_ONCE(netdev_max_backlog) >> 1))
4592 sd = this_cpu_ptr(&softnet_data);
4595 fl = rcu_dereference(sd->flow_limit);
4597 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4598 old_flow = fl->history[fl->history_head];
4599 fl->history[fl->history_head] = new_flow;
4602 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4604 if (likely(fl->buckets[old_flow]))
4605 fl->buckets[old_flow]--;
4607 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4619 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4620 * queue (may be a remote CPU queue).
4622 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4623 unsigned int *qtail)
4625 enum skb_drop_reason reason;
4626 struct softnet_data *sd;
4627 unsigned long flags;
4630 reason = SKB_DROP_REASON_NOT_SPECIFIED;
4631 sd = &per_cpu(softnet_data, cpu);
4633 rps_lock_irqsave(sd, &flags);
4634 if (!netif_running(skb->dev))
4636 qlen = skb_queue_len(&sd->input_pkt_queue);
4637 if (qlen <= READ_ONCE(netdev_max_backlog) && !skb_flow_limit(skb, qlen)) {
4640 __skb_queue_tail(&sd->input_pkt_queue, skb);
4641 input_queue_tail_incr_save(sd, qtail);
4642 rps_unlock_irq_restore(sd, &flags);
4643 return NET_RX_SUCCESS;
4646 /* Schedule NAPI for backlog device
4647 * We can use non atomic operation since we own the queue lock
4649 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4650 napi_schedule_rps(sd);
4653 reason = SKB_DROP_REASON_CPU_BACKLOG;
4657 rps_unlock_irq_restore(sd, &flags);
4659 dev_core_stats_rx_dropped_inc(skb->dev);
4660 kfree_skb_reason(skb, reason);
4664 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4666 struct net_device *dev = skb->dev;
4667 struct netdev_rx_queue *rxqueue;
4671 if (skb_rx_queue_recorded(skb)) {
4672 u16 index = skb_get_rx_queue(skb);
4674 if (unlikely(index >= dev->real_num_rx_queues)) {
4675 WARN_ONCE(dev->real_num_rx_queues > 1,
4676 "%s received packet on queue %u, but number "
4677 "of RX queues is %u\n",
4678 dev->name, index, dev->real_num_rx_queues);
4680 return rxqueue; /* Return first rxqueue */
4687 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4688 struct bpf_prog *xdp_prog)
4690 void *orig_data, *orig_data_end, *hard_start;
4691 struct netdev_rx_queue *rxqueue;
4692 bool orig_bcast, orig_host;
4693 u32 mac_len, frame_sz;
4694 __be16 orig_eth_type;
4699 /* The XDP program wants to see the packet starting at the MAC
4702 mac_len = skb->data - skb_mac_header(skb);
4703 hard_start = skb->data - skb_headroom(skb);
4705 /* SKB "head" area always have tailroom for skb_shared_info */
4706 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4707 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4709 rxqueue = netif_get_rxqueue(skb);
4710 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4711 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4712 skb_headlen(skb) + mac_len, true);
4714 orig_data_end = xdp->data_end;
4715 orig_data = xdp->data;
4716 eth = (struct ethhdr *)xdp->data;
4717 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4718 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4719 orig_eth_type = eth->h_proto;
4721 act = bpf_prog_run_xdp(xdp_prog, xdp);
4723 /* check if bpf_xdp_adjust_head was used */
4724 off = xdp->data - orig_data;
4727 __skb_pull(skb, off);
4729 __skb_push(skb, -off);
4731 skb->mac_header += off;
4732 skb_reset_network_header(skb);
4735 /* check if bpf_xdp_adjust_tail was used */
4736 off = xdp->data_end - orig_data_end;
4738 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4739 skb->len += off; /* positive on grow, negative on shrink */
4742 /* check if XDP changed eth hdr such SKB needs update */
4743 eth = (struct ethhdr *)xdp->data;
4744 if ((orig_eth_type != eth->h_proto) ||
4745 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4746 skb->dev->dev_addr)) ||
4747 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4748 __skb_push(skb, ETH_HLEN);
4749 skb->pkt_type = PACKET_HOST;
4750 skb->protocol = eth_type_trans(skb, skb->dev);
4753 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4754 * before calling us again on redirect path. We do not call do_redirect
4755 * as we leave that up to the caller.
4757 * Caller is responsible for managing lifetime of skb (i.e. calling
4758 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4763 __skb_push(skb, mac_len);
4766 metalen = xdp->data - xdp->data_meta;
4768 skb_metadata_set(skb, metalen);
4775 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4776 struct xdp_buff *xdp,
4777 struct bpf_prog *xdp_prog)
4781 /* Reinjected packets coming from act_mirred or similar should
4782 * not get XDP generic processing.
4784 if (skb_is_redirected(skb))
4787 /* XDP packets must be linear and must have sufficient headroom
4788 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4789 * native XDP provides, thus we need to do it here as well.
4791 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4792 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4793 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4794 int troom = skb->tail + skb->data_len - skb->end;
4796 /* In case we have to go down the path and also linearize,
4797 * then lets do the pskb_expand_head() work just once here.
4799 if (pskb_expand_head(skb,
4800 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4801 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4803 if (skb_linearize(skb))
4807 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4814 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act);
4817 trace_xdp_exception(skb->dev, xdp_prog, act);
4828 /* When doing generic XDP we have to bypass the qdisc layer and the
4829 * network taps in order to match in-driver-XDP behavior. This also means
4830 * that XDP packets are able to starve other packets going through a qdisc,
4831 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
4832 * queues, so they do not have this starvation issue.
4834 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4836 struct net_device *dev = skb->dev;
4837 struct netdev_queue *txq;
4838 bool free_skb = true;
4841 txq = netdev_core_pick_tx(dev, skb, NULL);
4842 cpu = smp_processor_id();
4843 HARD_TX_LOCK(dev, txq, cpu);
4844 if (!netif_xmit_frozen_or_drv_stopped(txq)) {
4845 rc = netdev_start_xmit(skb, dev, txq, 0);
4846 if (dev_xmit_complete(rc))
4849 HARD_TX_UNLOCK(dev, txq);
4851 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4852 dev_core_stats_tx_dropped_inc(dev);
4857 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4859 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4862 struct xdp_buff xdp;
4866 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4867 if (act != XDP_PASS) {
4870 err = xdp_do_generic_redirect(skb->dev, skb,
4876 generic_xdp_tx(skb, xdp_prog);
4884 kfree_skb_reason(skb, SKB_DROP_REASON_XDP);
4887 EXPORT_SYMBOL_GPL(do_xdp_generic);
4889 static int netif_rx_internal(struct sk_buff *skb)
4893 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
4895 trace_netif_rx(skb);
4898 if (static_branch_unlikely(&rps_needed)) {
4899 struct rps_dev_flow voidflow, *rflow = &voidflow;
4904 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4906 cpu = smp_processor_id();
4908 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4916 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
4922 * __netif_rx - Slightly optimized version of netif_rx
4923 * @skb: buffer to post
4925 * This behaves as netif_rx except that it does not disable bottom halves.
4926 * As a result this function may only be invoked from the interrupt context
4927 * (either hard or soft interrupt).
4929 int __netif_rx(struct sk_buff *skb)
4933 lockdep_assert_once(hardirq_count() | softirq_count());
4935 trace_netif_rx_entry(skb);
4936 ret = netif_rx_internal(skb);
4937 trace_netif_rx_exit(ret);
4940 EXPORT_SYMBOL(__netif_rx);
4943 * netif_rx - post buffer to the network code
4944 * @skb: buffer to post
4946 * This function receives a packet from a device driver and queues it for
4947 * the upper (protocol) levels to process via the backlog NAPI device. It
4948 * always succeeds. The buffer may be dropped during processing for
4949 * congestion control or by the protocol layers.
4950 * The network buffer is passed via the backlog NAPI device. Modern NIC
4951 * driver should use NAPI and GRO.
4952 * This function can used from interrupt and from process context. The
4953 * caller from process context must not disable interrupts before invoking
4957 * NET_RX_SUCCESS (no congestion)
4958 * NET_RX_DROP (packet was dropped)
4961 int netif_rx(struct sk_buff *skb)
4963 bool need_bh_off = !(hardirq_count() | softirq_count());
4968 trace_netif_rx_entry(skb);
4969 ret = netif_rx_internal(skb);
4970 trace_netif_rx_exit(ret);
4975 EXPORT_SYMBOL(netif_rx);
4977 static __latent_entropy void net_tx_action(struct softirq_action *h)
4979 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4981 if (sd->completion_queue) {
4982 struct sk_buff *clist;
4984 local_irq_disable();
4985 clist = sd->completion_queue;
4986 sd->completion_queue = NULL;
4990 struct sk_buff *skb = clist;
4992 clist = clist->next;
4994 WARN_ON(refcount_read(&skb->users));
4995 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
4996 trace_consume_skb(skb, net_tx_action);
4998 trace_kfree_skb(skb, net_tx_action,
4999 get_kfree_skb_cb(skb)->reason);
5001 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
5004 __napi_kfree_skb(skb,
5005 get_kfree_skb_cb(skb)->reason);
5009 if (sd->output_queue) {
5012 local_irq_disable();
5013 head = sd->output_queue;
5014 sd->output_queue = NULL;
5015 sd->output_queue_tailp = &sd->output_queue;
5021 struct Qdisc *q = head;
5022 spinlock_t *root_lock = NULL;
5024 head = head->next_sched;
5026 /* We need to make sure head->next_sched is read
5027 * before clearing __QDISC_STATE_SCHED
5029 smp_mb__before_atomic();
5031 if (!(q->flags & TCQ_F_NOLOCK)) {
5032 root_lock = qdisc_lock(q);
5033 spin_lock(root_lock);
5034 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
5036 /* There is a synchronize_net() between
5037 * STATE_DEACTIVATED flag being set and
5038 * qdisc_reset()/some_qdisc_is_busy() in
5039 * dev_deactivate(), so we can safely bail out
5040 * early here to avoid data race between
5041 * qdisc_deactivate() and some_qdisc_is_busy()
5042 * for lockless qdisc.
5044 clear_bit(__QDISC_STATE_SCHED, &q->state);
5048 clear_bit(__QDISC_STATE_SCHED, &q->state);
5051 spin_unlock(root_lock);
5057 xfrm_dev_backlog(sd);
5060 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5061 /* This hook is defined here for ATM LANE */
5062 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5063 unsigned char *addr) __read_mostly;
5064 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5067 static inline struct sk_buff *
5068 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
5069 struct net_device *orig_dev, bool *another)
5071 #ifdef CONFIG_NET_CLS_ACT
5072 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
5073 struct tcf_result cl_res;
5075 /* If there's at least one ingress present somewhere (so
5076 * we get here via enabled static key), remaining devices
5077 * that are not configured with an ingress qdisc will bail
5084 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5088 qdisc_skb_cb(skb)->pkt_len = skb->len;
5089 tc_skb_cb(skb)->mru = 0;
5090 tc_skb_cb(skb)->post_ct = false;
5091 skb->tc_at_ingress = 1;
5092 mini_qdisc_bstats_cpu_update(miniq, skb);
5094 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
5096 case TC_ACT_RECLASSIFY:
5097 skb->tc_index = TC_H_MIN(cl_res.classid);
5100 mini_qdisc_qstats_cpu_drop(miniq);
5101 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS);
5108 *ret = NET_RX_SUCCESS;
5110 case TC_ACT_REDIRECT:
5111 /* skb_mac_header check was done by cls/act_bpf, so
5112 * we can safely push the L2 header back before
5113 * redirecting to another netdev
5115 __skb_push(skb, skb->mac_len);
5116 if (skb_do_redirect(skb) == -EAGAIN) {
5117 __skb_pull(skb, skb->mac_len);
5121 *ret = NET_RX_SUCCESS;
5123 case TC_ACT_CONSUMED:
5124 *ret = NET_RX_SUCCESS;
5129 #endif /* CONFIG_NET_CLS_ACT */
5134 * netdev_is_rx_handler_busy - check if receive handler is registered
5135 * @dev: device to check
5137 * Check if a receive handler is already registered for a given device.
5138 * Return true if there one.
5140 * The caller must hold the rtnl_mutex.
5142 bool netdev_is_rx_handler_busy(struct net_device *dev)
5145 return dev && rtnl_dereference(dev->rx_handler);
5147 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5150 * netdev_rx_handler_register - register receive handler
5151 * @dev: device to register a handler for
5152 * @rx_handler: receive handler to register
5153 * @rx_handler_data: data pointer that is used by rx handler
5155 * Register a receive handler for a device. This handler will then be
5156 * called from __netif_receive_skb. A negative errno code is returned
5159 * The caller must hold the rtnl_mutex.
5161 * For a general description of rx_handler, see enum rx_handler_result.
5163 int netdev_rx_handler_register(struct net_device *dev,
5164 rx_handler_func_t *rx_handler,
5165 void *rx_handler_data)
5167 if (netdev_is_rx_handler_busy(dev))
5170 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5173 /* Note: rx_handler_data must be set before rx_handler */
5174 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5175 rcu_assign_pointer(dev->rx_handler, rx_handler);
5179 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5182 * netdev_rx_handler_unregister - unregister receive handler
5183 * @dev: device to unregister a handler from
5185 * Unregister a receive handler from a device.
5187 * The caller must hold the rtnl_mutex.
5189 void netdev_rx_handler_unregister(struct net_device *dev)
5193 RCU_INIT_POINTER(dev->rx_handler, NULL);
5194 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5195 * section has a guarantee to see a non NULL rx_handler_data
5199 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5201 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5204 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5205 * the special handling of PFMEMALLOC skbs.
5207 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5209 switch (skb->protocol) {
5210 case htons(ETH_P_ARP):
5211 case htons(ETH_P_IP):
5212 case htons(ETH_P_IPV6):
5213 case htons(ETH_P_8021Q):
5214 case htons(ETH_P_8021AD):
5221 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5222 int *ret, struct net_device *orig_dev)
5224 if (nf_hook_ingress_active(skb)) {
5228 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5233 ingress_retval = nf_hook_ingress(skb);
5235 return ingress_retval;
5240 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5241 struct packet_type **ppt_prev)
5243 struct packet_type *ptype, *pt_prev;
5244 rx_handler_func_t *rx_handler;
5245 struct sk_buff *skb = *pskb;
5246 struct net_device *orig_dev;
5247 bool deliver_exact = false;
5248 int ret = NET_RX_DROP;
5251 net_timestamp_check(!READ_ONCE(netdev_tstamp_prequeue), skb);
5253 trace_netif_receive_skb(skb);
5255 orig_dev = skb->dev;
5257 skb_reset_network_header(skb);
5258 if (!skb_transport_header_was_set(skb))
5259 skb_reset_transport_header(skb);
5260 skb_reset_mac_len(skb);
5265 skb->skb_iif = skb->dev->ifindex;
5267 __this_cpu_inc(softnet_data.processed);
5269 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5273 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5276 if (ret2 != XDP_PASS) {
5282 if (eth_type_vlan(skb->protocol)) {
5283 skb = skb_vlan_untag(skb);
5288 if (skb_skip_tc_classify(skb))
5294 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5296 ret = deliver_skb(skb, pt_prev, orig_dev);
5300 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5302 ret = deliver_skb(skb, pt_prev, orig_dev);
5307 #ifdef CONFIG_NET_INGRESS
5308 if (static_branch_unlikely(&ingress_needed_key)) {
5309 bool another = false;
5311 nf_skip_egress(skb, true);
5312 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5319 nf_skip_egress(skb, false);
5320 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5324 skb_reset_redirect(skb);
5326 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5329 if (skb_vlan_tag_present(skb)) {
5331 ret = deliver_skb(skb, pt_prev, orig_dev);
5334 if (vlan_do_receive(&skb))
5336 else if (unlikely(!skb))
5340 rx_handler = rcu_dereference(skb->dev->rx_handler);
5343 ret = deliver_skb(skb, pt_prev, orig_dev);
5346 switch (rx_handler(&skb)) {
5347 case RX_HANDLER_CONSUMED:
5348 ret = NET_RX_SUCCESS;
5350 case RX_HANDLER_ANOTHER:
5352 case RX_HANDLER_EXACT:
5353 deliver_exact = true;
5355 case RX_HANDLER_PASS:
5362 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5364 if (skb_vlan_tag_get_id(skb)) {
5365 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5368 skb->pkt_type = PACKET_OTHERHOST;
5369 } else if (eth_type_vlan(skb->protocol)) {
5370 /* Outer header is 802.1P with vlan 0, inner header is
5371 * 802.1Q or 802.1AD and vlan_do_receive() above could
5372 * not find vlan dev for vlan id 0.
5374 __vlan_hwaccel_clear_tag(skb);
5375 skb = skb_vlan_untag(skb);
5378 if (vlan_do_receive(&skb))
5379 /* After stripping off 802.1P header with vlan 0
5380 * vlan dev is found for inner header.
5383 else if (unlikely(!skb))
5386 /* We have stripped outer 802.1P vlan 0 header.
5387 * But could not find vlan dev.
5388 * check again for vlan id to set OTHERHOST.
5392 /* Note: we might in the future use prio bits
5393 * and set skb->priority like in vlan_do_receive()
5394 * For the time being, just ignore Priority Code Point
5396 __vlan_hwaccel_clear_tag(skb);
5399 type = skb->protocol;
5401 /* deliver only exact match when indicated */
5402 if (likely(!deliver_exact)) {
5403 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5404 &ptype_base[ntohs(type) &
5408 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5409 &orig_dev->ptype_specific);
5411 if (unlikely(skb->dev != orig_dev)) {
5412 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5413 &skb->dev->ptype_specific);
5417 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5419 *ppt_prev = pt_prev;
5423 dev_core_stats_rx_dropped_inc(skb->dev);
5425 dev_core_stats_rx_nohandler_inc(skb->dev);
5426 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5427 /* Jamal, now you will not able to escape explaining
5428 * me how you were going to use this. :-)
5434 /* The invariant here is that if *ppt_prev is not NULL
5435 * then skb should also be non-NULL.
5437 * Apparently *ppt_prev assignment above holds this invariant due to
5438 * skb dereferencing near it.
5444 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5446 struct net_device *orig_dev = skb->dev;
5447 struct packet_type *pt_prev = NULL;
5450 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5452 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5453 skb->dev, pt_prev, orig_dev);
5458 * netif_receive_skb_core - special purpose version of netif_receive_skb
5459 * @skb: buffer to process
5461 * More direct receive version of netif_receive_skb(). It should
5462 * only be used by callers that have a need to skip RPS and Generic XDP.
5463 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5465 * This function may only be called from softirq context and interrupts
5466 * should be enabled.
5468 * Return values (usually ignored):
5469 * NET_RX_SUCCESS: no congestion
5470 * NET_RX_DROP: packet was dropped
5472 int netif_receive_skb_core(struct sk_buff *skb)
5477 ret = __netif_receive_skb_one_core(skb, false);
5482 EXPORT_SYMBOL(netif_receive_skb_core);
5484 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5485 struct packet_type *pt_prev,
5486 struct net_device *orig_dev)
5488 struct sk_buff *skb, *next;
5492 if (list_empty(head))
5494 if (pt_prev->list_func != NULL)
5495 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5496 ip_list_rcv, head, pt_prev, orig_dev);
5498 list_for_each_entry_safe(skb, next, head, list) {
5499 skb_list_del_init(skb);
5500 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5504 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5506 /* Fast-path assumptions:
5507 * - There is no RX handler.
5508 * - Only one packet_type matches.
5509 * If either of these fails, we will end up doing some per-packet
5510 * processing in-line, then handling the 'last ptype' for the whole
5511 * sublist. This can't cause out-of-order delivery to any single ptype,
5512 * because the 'last ptype' must be constant across the sublist, and all
5513 * other ptypes are handled per-packet.
5515 /* Current (common) ptype of sublist */
5516 struct packet_type *pt_curr = NULL;
5517 /* Current (common) orig_dev of sublist */
5518 struct net_device *od_curr = NULL;
5519 struct list_head sublist;
5520 struct sk_buff *skb, *next;
5522 INIT_LIST_HEAD(&sublist);
5523 list_for_each_entry_safe(skb, next, head, list) {
5524 struct net_device *orig_dev = skb->dev;
5525 struct packet_type *pt_prev = NULL;
5527 skb_list_del_init(skb);
5528 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5531 if (pt_curr != pt_prev || od_curr != orig_dev) {
5532 /* dispatch old sublist */
5533 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5534 /* start new sublist */
5535 INIT_LIST_HEAD(&sublist);
5539 list_add_tail(&skb->list, &sublist);
5542 /* dispatch final sublist */
5543 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5546 static int __netif_receive_skb(struct sk_buff *skb)
5550 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5551 unsigned int noreclaim_flag;
5554 * PFMEMALLOC skbs are special, they should
5555 * - be delivered to SOCK_MEMALLOC sockets only
5556 * - stay away from userspace
5557 * - have bounded memory usage
5559 * Use PF_MEMALLOC as this saves us from propagating the allocation
5560 * context down to all allocation sites.
5562 noreclaim_flag = memalloc_noreclaim_save();
5563 ret = __netif_receive_skb_one_core(skb, true);
5564 memalloc_noreclaim_restore(noreclaim_flag);
5566 ret = __netif_receive_skb_one_core(skb, false);
5571 static void __netif_receive_skb_list(struct list_head *head)
5573 unsigned long noreclaim_flag = 0;
5574 struct sk_buff *skb, *next;
5575 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5577 list_for_each_entry_safe(skb, next, head, list) {
5578 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5579 struct list_head sublist;
5581 /* Handle the previous sublist */
5582 list_cut_before(&sublist, head, &skb->list);
5583 if (!list_empty(&sublist))
5584 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5585 pfmemalloc = !pfmemalloc;
5586 /* See comments in __netif_receive_skb */
5588 noreclaim_flag = memalloc_noreclaim_save();
5590 memalloc_noreclaim_restore(noreclaim_flag);
5593 /* Handle the remaining sublist */
5594 if (!list_empty(head))
5595 __netif_receive_skb_list_core(head, pfmemalloc);
5596 /* Restore pflags */
5598 memalloc_noreclaim_restore(noreclaim_flag);
5601 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5603 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5604 struct bpf_prog *new = xdp->prog;
5607 switch (xdp->command) {
5608 case XDP_SETUP_PROG:
5609 rcu_assign_pointer(dev->xdp_prog, new);
5614 static_branch_dec(&generic_xdp_needed_key);
5615 } else if (new && !old) {
5616 static_branch_inc(&generic_xdp_needed_key);
5617 dev_disable_lro(dev);
5618 dev_disable_gro_hw(dev);
5630 static int netif_receive_skb_internal(struct sk_buff *skb)
5634 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5636 if (skb_defer_rx_timestamp(skb))
5637 return NET_RX_SUCCESS;
5641 if (static_branch_unlikely(&rps_needed)) {
5642 struct rps_dev_flow voidflow, *rflow = &voidflow;
5643 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5646 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5652 ret = __netif_receive_skb(skb);
5657 void netif_receive_skb_list_internal(struct list_head *head)
5659 struct sk_buff *skb, *next;
5660 struct list_head sublist;
5662 INIT_LIST_HEAD(&sublist);
5663 list_for_each_entry_safe(skb, next, head, list) {
5664 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5665 skb_list_del_init(skb);
5666 if (!skb_defer_rx_timestamp(skb))
5667 list_add_tail(&skb->list, &sublist);
5669 list_splice_init(&sublist, head);
5673 if (static_branch_unlikely(&rps_needed)) {
5674 list_for_each_entry_safe(skb, next, head, list) {
5675 struct rps_dev_flow voidflow, *rflow = &voidflow;
5676 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5679 /* Will be handled, remove from list */
5680 skb_list_del_init(skb);
5681 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5686 __netif_receive_skb_list(head);
5691 * netif_receive_skb - process receive buffer from network
5692 * @skb: buffer to process
5694 * netif_receive_skb() is the main receive data processing function.
5695 * It always succeeds. The buffer may be dropped during processing
5696 * for congestion control or by the protocol layers.
5698 * This function may only be called from softirq context and interrupts
5699 * should be enabled.
5701 * Return values (usually ignored):
5702 * NET_RX_SUCCESS: no congestion
5703 * NET_RX_DROP: packet was dropped
5705 int netif_receive_skb(struct sk_buff *skb)
5709 trace_netif_receive_skb_entry(skb);
5711 ret = netif_receive_skb_internal(skb);
5712 trace_netif_receive_skb_exit(ret);
5716 EXPORT_SYMBOL(netif_receive_skb);
5719 * netif_receive_skb_list - process many receive buffers from network
5720 * @head: list of skbs to process.
5722 * Since return value of netif_receive_skb() is normally ignored, and
5723 * wouldn't be meaningful for a list, this function returns void.
5725 * This function may only be called from softirq context and interrupts
5726 * should be enabled.
5728 void netif_receive_skb_list(struct list_head *head)
5730 struct sk_buff *skb;
5732 if (list_empty(head))
5734 if (trace_netif_receive_skb_list_entry_enabled()) {
5735 list_for_each_entry(skb, head, list)
5736 trace_netif_receive_skb_list_entry(skb);
5738 netif_receive_skb_list_internal(head);
5739 trace_netif_receive_skb_list_exit(0);
5741 EXPORT_SYMBOL(netif_receive_skb_list);
5743 static DEFINE_PER_CPU(struct work_struct, flush_works);
5745 /* Network device is going away, flush any packets still pending */
5746 static void flush_backlog(struct work_struct *work)
5748 struct sk_buff *skb, *tmp;
5749 struct softnet_data *sd;
5752 sd = this_cpu_ptr(&softnet_data);
5754 rps_lock_irq_disable(sd);
5755 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5756 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5757 __skb_unlink(skb, &sd->input_pkt_queue);
5758 dev_kfree_skb_irq(skb);
5759 input_queue_head_incr(sd);
5762 rps_unlock_irq_enable(sd);
5764 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5765 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5766 __skb_unlink(skb, &sd->process_queue);
5768 input_queue_head_incr(sd);
5774 static bool flush_required(int cpu)
5776 #if IS_ENABLED(CONFIG_RPS)
5777 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5780 rps_lock_irq_disable(sd);
5782 /* as insertion into process_queue happens with the rps lock held,
5783 * process_queue access may race only with dequeue
5785 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5786 !skb_queue_empty_lockless(&sd->process_queue);
5787 rps_unlock_irq_enable(sd);
5791 /* without RPS we can't safely check input_pkt_queue: during a
5792 * concurrent remote skb_queue_splice() we can detect as empty both
5793 * input_pkt_queue and process_queue even if the latter could end-up
5794 * containing a lot of packets.
5799 static void flush_all_backlogs(void)
5801 static cpumask_t flush_cpus;
5804 /* since we are under rtnl lock protection we can use static data
5805 * for the cpumask and avoid allocating on stack the possibly
5812 cpumask_clear(&flush_cpus);
5813 for_each_online_cpu(cpu) {
5814 if (flush_required(cpu)) {
5815 queue_work_on(cpu, system_highpri_wq,
5816 per_cpu_ptr(&flush_works, cpu));
5817 cpumask_set_cpu(cpu, &flush_cpus);
5821 /* we can have in flight packet[s] on the cpus we are not flushing,
5822 * synchronize_net() in unregister_netdevice_many() will take care of
5825 for_each_cpu(cpu, &flush_cpus)
5826 flush_work(per_cpu_ptr(&flush_works, cpu));
5831 static void net_rps_send_ipi(struct softnet_data *remsd)
5835 struct softnet_data *next = remsd->rps_ipi_next;
5837 if (cpu_online(remsd->cpu))
5838 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5845 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5846 * Note: called with local irq disabled, but exits with local irq enabled.
5848 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5851 struct softnet_data *remsd = sd->rps_ipi_list;
5854 sd->rps_ipi_list = NULL;
5858 /* Send pending IPI's to kick RPS processing on remote cpus. */
5859 net_rps_send_ipi(remsd);
5865 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5868 return sd->rps_ipi_list != NULL;
5874 static int process_backlog(struct napi_struct *napi, int quota)
5876 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5880 /* Check if we have pending ipi, its better to send them now,
5881 * not waiting net_rx_action() end.
5883 if (sd_has_rps_ipi_waiting(sd)) {
5884 local_irq_disable();
5885 net_rps_action_and_irq_enable(sd);
5888 napi->weight = READ_ONCE(dev_rx_weight);
5890 struct sk_buff *skb;
5892 while ((skb = __skb_dequeue(&sd->process_queue))) {
5894 __netif_receive_skb(skb);
5896 input_queue_head_incr(sd);
5897 if (++work >= quota)
5902 rps_lock_irq_disable(sd);
5903 if (skb_queue_empty(&sd->input_pkt_queue)) {
5905 * Inline a custom version of __napi_complete().
5906 * only current cpu owns and manipulates this napi,
5907 * and NAPI_STATE_SCHED is the only possible flag set
5909 * We can use a plain write instead of clear_bit(),
5910 * and we dont need an smp_mb() memory barrier.
5915 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5916 &sd->process_queue);
5918 rps_unlock_irq_enable(sd);
5925 * __napi_schedule - schedule for receive
5926 * @n: entry to schedule
5928 * The entry's receive function will be scheduled to run.
5929 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5931 void __napi_schedule(struct napi_struct *n)
5933 unsigned long flags;
5935 local_irq_save(flags);
5936 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5937 local_irq_restore(flags);
5939 EXPORT_SYMBOL(__napi_schedule);
5942 * napi_schedule_prep - check if napi can be scheduled
5945 * Test if NAPI routine is already running, and if not mark
5946 * it as running. This is used as a condition variable to
5947 * insure only one NAPI poll instance runs. We also make
5948 * sure there is no pending NAPI disable.
5950 bool napi_schedule_prep(struct napi_struct *n)
5952 unsigned long new, val = READ_ONCE(n->state);
5955 if (unlikely(val & NAPIF_STATE_DISABLE))
5957 new = val | NAPIF_STATE_SCHED;
5959 /* Sets STATE_MISSED bit if STATE_SCHED was already set
5960 * This was suggested by Alexander Duyck, as compiler
5961 * emits better code than :
5962 * if (val & NAPIF_STATE_SCHED)
5963 * new |= NAPIF_STATE_MISSED;
5965 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
5967 } while (!try_cmpxchg(&n->state, &val, new));
5969 return !(val & NAPIF_STATE_SCHED);
5971 EXPORT_SYMBOL(napi_schedule_prep);
5974 * __napi_schedule_irqoff - schedule for receive
5975 * @n: entry to schedule
5977 * Variant of __napi_schedule() assuming hard irqs are masked.
5979 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
5980 * because the interrupt disabled assumption might not be true
5981 * due to force-threaded interrupts and spinlock substitution.
5983 void __napi_schedule_irqoff(struct napi_struct *n)
5985 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
5986 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5990 EXPORT_SYMBOL(__napi_schedule_irqoff);
5992 bool napi_complete_done(struct napi_struct *n, int work_done)
5994 unsigned long flags, val, new, timeout = 0;
5998 * 1) Don't let napi dequeue from the cpu poll list
5999 * just in case its running on a different cpu.
6000 * 2) If we are busy polling, do nothing here, we have
6001 * the guarantee we will be called later.
6003 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6004 NAPIF_STATE_IN_BUSY_POLL)))
6009 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6010 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6012 if (n->defer_hard_irqs_count > 0) {
6013 n->defer_hard_irqs_count--;
6014 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6018 if (n->gro_bitmask) {
6019 /* When the NAPI instance uses a timeout and keeps postponing
6020 * it, we need to bound somehow the time packets are kept in
6023 napi_gro_flush(n, !!timeout);
6028 if (unlikely(!list_empty(&n->poll_list))) {
6029 /* If n->poll_list is not empty, we need to mask irqs */
6030 local_irq_save(flags);
6031 list_del_init(&n->poll_list);
6032 local_irq_restore(flags);
6034 WRITE_ONCE(n->list_owner, -1);
6036 val = READ_ONCE(n->state);
6038 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6040 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6041 NAPIF_STATE_SCHED_THREADED |
6042 NAPIF_STATE_PREFER_BUSY_POLL);
6044 /* If STATE_MISSED was set, leave STATE_SCHED set,
6045 * because we will call napi->poll() one more time.
6046 * This C code was suggested by Alexander Duyck to help gcc.
6048 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6050 } while (!try_cmpxchg(&n->state, &val, new));
6052 if (unlikely(val & NAPIF_STATE_MISSED)) {
6058 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6059 HRTIMER_MODE_REL_PINNED);
6062 EXPORT_SYMBOL(napi_complete_done);
6064 /* must be called under rcu_read_lock(), as we dont take a reference */
6065 static struct napi_struct *napi_by_id(unsigned int napi_id)
6067 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6068 struct napi_struct *napi;
6070 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6071 if (napi->napi_id == napi_id)
6077 #if defined(CONFIG_NET_RX_BUSY_POLL)
6079 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6081 if (!skip_schedule) {
6082 gro_normal_list(napi);
6083 __napi_schedule(napi);
6087 if (napi->gro_bitmask) {
6088 /* flush too old packets
6089 * If HZ < 1000, flush all packets.
6091 napi_gro_flush(napi, HZ >= 1000);
6094 gro_normal_list(napi);
6095 clear_bit(NAPI_STATE_SCHED, &napi->state);
6098 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6101 bool skip_schedule = false;
6102 unsigned long timeout;
6105 /* Busy polling means there is a high chance device driver hard irq
6106 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6107 * set in napi_schedule_prep().
6108 * Since we are about to call napi->poll() once more, we can safely
6109 * clear NAPI_STATE_MISSED.
6111 * Note: x86 could use a single "lock and ..." instruction
6112 * to perform these two clear_bit()
6114 clear_bit(NAPI_STATE_MISSED, &napi->state);
6115 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6119 if (prefer_busy_poll) {
6120 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6121 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6122 if (napi->defer_hard_irqs_count && timeout) {
6123 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6124 skip_schedule = true;
6128 /* All we really want here is to re-enable device interrupts.
6129 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6131 rc = napi->poll(napi, budget);
6132 /* We can't gro_normal_list() here, because napi->poll() might have
6133 * rearmed the napi (napi_complete_done()) in which case it could
6134 * already be running on another CPU.
6136 trace_napi_poll(napi, rc, budget);
6137 netpoll_poll_unlock(have_poll_lock);
6139 __busy_poll_stop(napi, skip_schedule);
6143 void napi_busy_loop(unsigned int napi_id,
6144 bool (*loop_end)(void *, unsigned long),
6145 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6147 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6148 int (*napi_poll)(struct napi_struct *napi, int budget);
6149 void *have_poll_lock = NULL;
6150 struct napi_struct *napi;
6157 napi = napi_by_id(napi_id);
6161 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6168 unsigned long val = READ_ONCE(napi->state);
6170 /* If multiple threads are competing for this napi,
6171 * we avoid dirtying napi->state as much as we can.
6173 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6174 NAPIF_STATE_IN_BUSY_POLL)) {
6175 if (prefer_busy_poll)
6176 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6179 if (cmpxchg(&napi->state, val,
6180 val | NAPIF_STATE_IN_BUSY_POLL |
6181 NAPIF_STATE_SCHED) != val) {
6182 if (prefer_busy_poll)
6183 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6186 have_poll_lock = netpoll_poll_lock(napi);
6187 napi_poll = napi->poll;
6189 work = napi_poll(napi, budget);
6190 trace_napi_poll(napi, work, budget);
6191 gro_normal_list(napi);
6194 __NET_ADD_STATS(dev_net(napi->dev),
6195 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6198 if (!loop_end || loop_end(loop_end_arg, start_time))
6201 if (unlikely(need_resched())) {
6203 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6204 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6208 if (loop_end(loop_end_arg, start_time))
6215 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6216 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6221 EXPORT_SYMBOL(napi_busy_loop);
6223 #endif /* CONFIG_NET_RX_BUSY_POLL */
6225 static void napi_hash_add(struct napi_struct *napi)
6227 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6230 spin_lock(&napi_hash_lock);
6232 /* 0..NR_CPUS range is reserved for sender_cpu use */
6234 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6235 napi_gen_id = MIN_NAPI_ID;
6236 } while (napi_by_id(napi_gen_id));
6237 napi->napi_id = napi_gen_id;
6239 hlist_add_head_rcu(&napi->napi_hash_node,
6240 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6242 spin_unlock(&napi_hash_lock);
6245 /* Warning : caller is responsible to make sure rcu grace period
6246 * is respected before freeing memory containing @napi
6248 static void napi_hash_del(struct napi_struct *napi)
6250 spin_lock(&napi_hash_lock);
6252 hlist_del_init_rcu(&napi->napi_hash_node);
6254 spin_unlock(&napi_hash_lock);
6257 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6259 struct napi_struct *napi;
6261 napi = container_of(timer, struct napi_struct, timer);
6263 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6264 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6266 if (!napi_disable_pending(napi) &&
6267 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6268 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6269 __napi_schedule_irqoff(napi);
6272 return HRTIMER_NORESTART;
6275 static void init_gro_hash(struct napi_struct *napi)
6279 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6280 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6281 napi->gro_hash[i].count = 0;
6283 napi->gro_bitmask = 0;
6286 int dev_set_threaded(struct net_device *dev, bool threaded)
6288 struct napi_struct *napi;
6291 if (dev->threaded == threaded)
6295 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6296 if (!napi->thread) {
6297 err = napi_kthread_create(napi);
6306 dev->threaded = threaded;
6308 /* Make sure kthread is created before THREADED bit
6311 smp_mb__before_atomic();
6313 /* Setting/unsetting threaded mode on a napi might not immediately
6314 * take effect, if the current napi instance is actively being
6315 * polled. In this case, the switch between threaded mode and
6316 * softirq mode will happen in the next round of napi_schedule().
6317 * This should not cause hiccups/stalls to the live traffic.
6319 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6321 set_bit(NAPI_STATE_THREADED, &napi->state);
6323 clear_bit(NAPI_STATE_THREADED, &napi->state);
6328 EXPORT_SYMBOL(dev_set_threaded);
6330 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6331 int (*poll)(struct napi_struct *, int), int weight)
6333 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6336 INIT_LIST_HEAD(&napi->poll_list);
6337 INIT_HLIST_NODE(&napi->napi_hash_node);
6338 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6339 napi->timer.function = napi_watchdog;
6340 init_gro_hash(napi);
6342 INIT_LIST_HEAD(&napi->rx_list);
6345 if (weight > NAPI_POLL_WEIGHT)
6346 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6348 napi->weight = weight;
6350 #ifdef CONFIG_NETPOLL
6351 napi->poll_owner = -1;
6353 napi->list_owner = -1;
6354 set_bit(NAPI_STATE_SCHED, &napi->state);
6355 set_bit(NAPI_STATE_NPSVC, &napi->state);
6356 list_add_rcu(&napi->dev_list, &dev->napi_list);
6357 napi_hash_add(napi);
6358 napi_get_frags_check(napi);
6359 /* Create kthread for this napi if dev->threaded is set.
6360 * Clear dev->threaded if kthread creation failed so that
6361 * threaded mode will not be enabled in napi_enable().
6363 if (dev->threaded && napi_kthread_create(napi))
6366 EXPORT_SYMBOL(netif_napi_add_weight);
6368 void napi_disable(struct napi_struct *n)
6370 unsigned long val, new;
6373 set_bit(NAPI_STATE_DISABLE, &n->state);
6375 val = READ_ONCE(n->state);
6377 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6378 usleep_range(20, 200);
6379 val = READ_ONCE(n->state);
6382 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6383 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6384 } while (!try_cmpxchg(&n->state, &val, new));
6386 hrtimer_cancel(&n->timer);
6388 clear_bit(NAPI_STATE_DISABLE, &n->state);
6390 EXPORT_SYMBOL(napi_disable);
6393 * napi_enable - enable NAPI scheduling
6396 * Resume NAPI from being scheduled on this context.
6397 * Must be paired with napi_disable.
6399 void napi_enable(struct napi_struct *n)
6401 unsigned long new, val = READ_ONCE(n->state);
6404 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6406 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6407 if (n->dev->threaded && n->thread)
6408 new |= NAPIF_STATE_THREADED;
6409 } while (!try_cmpxchg(&n->state, &val, new));
6411 EXPORT_SYMBOL(napi_enable);
6413 static void flush_gro_hash(struct napi_struct *napi)
6417 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6418 struct sk_buff *skb, *n;
6420 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6422 napi->gro_hash[i].count = 0;
6426 /* Must be called in process context */
6427 void __netif_napi_del(struct napi_struct *napi)
6429 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6432 napi_hash_del(napi);
6433 list_del_rcu(&napi->dev_list);
6434 napi_free_frags(napi);
6436 flush_gro_hash(napi);
6437 napi->gro_bitmask = 0;
6440 kthread_stop(napi->thread);
6441 napi->thread = NULL;
6444 EXPORT_SYMBOL(__netif_napi_del);
6446 static int __napi_poll(struct napi_struct *n, bool *repoll)
6452 /* This NAPI_STATE_SCHED test is for avoiding a race
6453 * with netpoll's poll_napi(). Only the entity which
6454 * obtains the lock and sees NAPI_STATE_SCHED set will
6455 * actually make the ->poll() call. Therefore we avoid
6456 * accidentally calling ->poll() when NAPI is not scheduled.
6459 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6460 work = n->poll(n, weight);
6461 trace_napi_poll(n, work, weight);
6464 if (unlikely(work > weight))
6465 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6466 n->poll, work, weight);
6468 if (likely(work < weight))
6471 /* Drivers must not modify the NAPI state if they
6472 * consume the entire weight. In such cases this code
6473 * still "owns" the NAPI instance and therefore can
6474 * move the instance around on the list at-will.
6476 if (unlikely(napi_disable_pending(n))) {
6481 /* The NAPI context has more processing work, but busy-polling
6482 * is preferred. Exit early.
6484 if (napi_prefer_busy_poll(n)) {
6485 if (napi_complete_done(n, work)) {
6486 /* If timeout is not set, we need to make sure
6487 * that the NAPI is re-scheduled.
6494 if (n->gro_bitmask) {
6495 /* flush too old packets
6496 * If HZ < 1000, flush all packets.
6498 napi_gro_flush(n, HZ >= 1000);
6503 /* Some drivers may have called napi_schedule
6504 * prior to exhausting their budget.
6506 if (unlikely(!list_empty(&n->poll_list))) {
6507 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6508 n->dev ? n->dev->name : "backlog");
6517 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6519 bool do_repoll = false;
6523 list_del_init(&n->poll_list);
6525 have = netpoll_poll_lock(n);
6527 work = __napi_poll(n, &do_repoll);
6530 list_add_tail(&n->poll_list, repoll);
6532 netpoll_poll_unlock(have);
6537 static int napi_thread_wait(struct napi_struct *napi)
6541 set_current_state(TASK_INTERRUPTIBLE);
6543 while (!kthread_should_stop()) {
6544 /* Testing SCHED_THREADED bit here to make sure the current
6545 * kthread owns this napi and could poll on this napi.
6546 * Testing SCHED bit is not enough because SCHED bit might be
6547 * set by some other busy poll thread or by napi_disable().
6549 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6550 WARN_ON(!list_empty(&napi->poll_list));
6551 __set_current_state(TASK_RUNNING);
6556 /* woken being true indicates this thread owns this napi. */
6558 set_current_state(TASK_INTERRUPTIBLE);
6560 __set_current_state(TASK_RUNNING);
6565 static void skb_defer_free_flush(struct softnet_data *sd)
6567 struct sk_buff *skb, *next;
6569 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6570 if (!READ_ONCE(sd->defer_list))
6573 spin_lock(&sd->defer_lock);
6574 skb = sd->defer_list;
6575 sd->defer_list = NULL;
6576 sd->defer_count = 0;
6577 spin_unlock(&sd->defer_lock);
6579 while (skb != NULL) {
6581 napi_consume_skb(skb, 1);
6586 static int napi_threaded_poll(void *data)
6588 struct napi_struct *napi = data;
6589 struct softnet_data *sd;
6592 while (!napi_thread_wait(napi)) {
6594 bool repoll = false;
6597 sd = this_cpu_ptr(&softnet_data);
6598 sd->in_napi_threaded_poll = true;
6600 have = netpoll_poll_lock(napi);
6601 __napi_poll(napi, &repoll);
6602 netpoll_poll_unlock(have);
6604 sd->in_napi_threaded_poll = false;
6607 if (sd_has_rps_ipi_waiting(sd)) {
6608 local_irq_disable();
6609 net_rps_action_and_irq_enable(sd);
6611 skb_defer_free_flush(sd);
6623 static __latent_entropy void net_rx_action(struct softirq_action *h)
6625 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6626 unsigned long time_limit = jiffies +
6627 usecs_to_jiffies(READ_ONCE(netdev_budget_usecs));
6628 int budget = READ_ONCE(netdev_budget);
6633 sd->in_net_rx_action = true;
6634 local_irq_disable();
6635 list_splice_init(&sd->poll_list, &list);
6639 struct napi_struct *n;
6641 skb_defer_free_flush(sd);
6643 if (list_empty(&list)) {
6644 if (list_empty(&repoll)) {
6645 sd->in_net_rx_action = false;
6647 /* We need to check if ____napi_schedule()
6648 * had refilled poll_list while
6649 * sd->in_net_rx_action was true.
6651 if (!list_empty(&sd->poll_list))
6653 if (!sd_has_rps_ipi_waiting(sd))
6659 n = list_first_entry(&list, struct napi_struct, poll_list);
6660 budget -= napi_poll(n, &repoll);
6662 /* If softirq window is exhausted then punt.
6663 * Allow this to run for 2 jiffies since which will allow
6664 * an average latency of 1.5/HZ.
6666 if (unlikely(budget <= 0 ||
6667 time_after_eq(jiffies, time_limit))) {
6673 local_irq_disable();
6675 list_splice_tail_init(&sd->poll_list, &list);
6676 list_splice_tail(&repoll, &list);
6677 list_splice(&list, &sd->poll_list);
6678 if (!list_empty(&sd->poll_list))
6679 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6681 sd->in_net_rx_action = false;
6683 net_rps_action_and_irq_enable(sd);
6687 struct netdev_adjacent {
6688 struct net_device *dev;
6689 netdevice_tracker dev_tracker;
6691 /* upper master flag, there can only be one master device per list */
6694 /* lookup ignore flag */
6697 /* counter for the number of times this device was added to us */
6700 /* private field for the users */
6703 struct list_head list;
6704 struct rcu_head rcu;
6707 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6708 struct list_head *adj_list)
6710 struct netdev_adjacent *adj;
6712 list_for_each_entry(adj, adj_list, list) {
6713 if (adj->dev == adj_dev)
6719 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6720 struct netdev_nested_priv *priv)
6722 struct net_device *dev = (struct net_device *)priv->data;
6724 return upper_dev == dev;
6728 * netdev_has_upper_dev - Check if device is linked to an upper device
6730 * @upper_dev: upper device to check
6732 * Find out if a device is linked to specified upper device and return true
6733 * in case it is. Note that this checks only immediate upper device,
6734 * not through a complete stack of devices. The caller must hold the RTNL lock.
6736 bool netdev_has_upper_dev(struct net_device *dev,
6737 struct net_device *upper_dev)
6739 struct netdev_nested_priv priv = {
6740 .data = (void *)upper_dev,
6745 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6748 EXPORT_SYMBOL(netdev_has_upper_dev);
6751 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6753 * @upper_dev: upper device to check
6755 * Find out if a device is linked to specified upper device and return true
6756 * in case it is. Note that this checks the entire upper device chain.
6757 * The caller must hold rcu lock.
6760 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6761 struct net_device *upper_dev)
6763 struct netdev_nested_priv priv = {
6764 .data = (void *)upper_dev,
6767 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6770 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6773 * netdev_has_any_upper_dev - Check if device is linked to some device
6776 * Find out if a device is linked to an upper device and return true in case
6777 * it is. The caller must hold the RTNL lock.
6779 bool netdev_has_any_upper_dev(struct net_device *dev)
6783 return !list_empty(&dev->adj_list.upper);
6785 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6788 * netdev_master_upper_dev_get - Get master upper device
6791 * Find a master upper device and return pointer to it or NULL in case
6792 * it's not there. The caller must hold the RTNL lock.
6794 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6796 struct netdev_adjacent *upper;
6800 if (list_empty(&dev->adj_list.upper))
6803 upper = list_first_entry(&dev->adj_list.upper,
6804 struct netdev_adjacent, list);
6805 if (likely(upper->master))
6809 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6811 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6813 struct netdev_adjacent *upper;
6817 if (list_empty(&dev->adj_list.upper))
6820 upper = list_first_entry(&dev->adj_list.upper,
6821 struct netdev_adjacent, list);
6822 if (likely(upper->master) && !upper->ignore)
6828 * netdev_has_any_lower_dev - Check if device is linked to some device
6831 * Find out if a device is linked to a lower device and return true in case
6832 * it is. The caller must hold the RTNL lock.
6834 static bool netdev_has_any_lower_dev(struct net_device *dev)
6838 return !list_empty(&dev->adj_list.lower);
6841 void *netdev_adjacent_get_private(struct list_head *adj_list)
6843 struct netdev_adjacent *adj;
6845 adj = list_entry(adj_list, struct netdev_adjacent, list);
6847 return adj->private;
6849 EXPORT_SYMBOL(netdev_adjacent_get_private);
6852 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6854 * @iter: list_head ** of the current position
6856 * Gets the next device from the dev's upper list, starting from iter
6857 * position. The caller must hold RCU read lock.
6859 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6860 struct list_head **iter)
6862 struct netdev_adjacent *upper;
6864 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6866 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6868 if (&upper->list == &dev->adj_list.upper)
6871 *iter = &upper->list;
6875 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6877 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6878 struct list_head **iter,
6881 struct netdev_adjacent *upper;
6883 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6885 if (&upper->list == &dev->adj_list.upper)
6888 *iter = &upper->list;
6889 *ignore = upper->ignore;
6894 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6895 struct list_head **iter)
6897 struct netdev_adjacent *upper;
6899 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6901 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6903 if (&upper->list == &dev->adj_list.upper)
6906 *iter = &upper->list;
6911 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6912 int (*fn)(struct net_device *dev,
6913 struct netdev_nested_priv *priv),
6914 struct netdev_nested_priv *priv)
6916 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6917 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6922 iter = &dev->adj_list.upper;
6926 ret = fn(now, priv);
6933 udev = __netdev_next_upper_dev(now, &iter, &ignore);
6940 niter = &udev->adj_list.upper;
6941 dev_stack[cur] = now;
6942 iter_stack[cur++] = iter;
6949 next = dev_stack[--cur];
6950 niter = iter_stack[cur];
6960 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6961 int (*fn)(struct net_device *dev,
6962 struct netdev_nested_priv *priv),
6963 struct netdev_nested_priv *priv)
6965 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6966 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6970 iter = &dev->adj_list.upper;
6974 ret = fn(now, priv);
6981 udev = netdev_next_upper_dev_rcu(now, &iter);
6986 niter = &udev->adj_list.upper;
6987 dev_stack[cur] = now;
6988 iter_stack[cur++] = iter;
6995 next = dev_stack[--cur];
6996 niter = iter_stack[cur];
7005 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7007 static bool __netdev_has_upper_dev(struct net_device *dev,
7008 struct net_device *upper_dev)
7010 struct netdev_nested_priv priv = {
7012 .data = (void *)upper_dev,
7017 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7022 * netdev_lower_get_next_private - Get the next ->private from the
7023 * lower neighbour list
7025 * @iter: list_head ** of the current position
7027 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7028 * list, starting from iter position. The caller must hold either hold the
7029 * RTNL lock or its own locking that guarantees that the neighbour lower
7030 * list will remain unchanged.
7032 void *netdev_lower_get_next_private(struct net_device *dev,
7033 struct list_head **iter)
7035 struct netdev_adjacent *lower;
7037 lower = list_entry(*iter, struct netdev_adjacent, list);
7039 if (&lower->list == &dev->adj_list.lower)
7042 *iter = lower->list.next;
7044 return lower->private;
7046 EXPORT_SYMBOL(netdev_lower_get_next_private);
7049 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7050 * lower neighbour list, RCU
7053 * @iter: list_head ** of the current position
7055 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7056 * list, starting from iter position. The caller must hold RCU read lock.
7058 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7059 struct list_head **iter)
7061 struct netdev_adjacent *lower;
7063 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7065 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7067 if (&lower->list == &dev->adj_list.lower)
7070 *iter = &lower->list;
7072 return lower->private;
7074 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7077 * netdev_lower_get_next - Get the next device from the lower neighbour
7080 * @iter: list_head ** of the current position
7082 * Gets the next netdev_adjacent from the dev's lower neighbour
7083 * list, starting from iter position. The caller must hold RTNL lock or
7084 * its own locking that guarantees that the neighbour lower
7085 * list will remain unchanged.
7087 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7089 struct netdev_adjacent *lower;
7091 lower = list_entry(*iter, struct netdev_adjacent, list);
7093 if (&lower->list == &dev->adj_list.lower)
7096 *iter = lower->list.next;
7100 EXPORT_SYMBOL(netdev_lower_get_next);
7102 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7103 struct list_head **iter)
7105 struct netdev_adjacent *lower;
7107 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7109 if (&lower->list == &dev->adj_list.lower)
7112 *iter = &lower->list;
7117 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7118 struct list_head **iter,
7121 struct netdev_adjacent *lower;
7123 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7125 if (&lower->list == &dev->adj_list.lower)
7128 *iter = &lower->list;
7129 *ignore = lower->ignore;
7134 int netdev_walk_all_lower_dev(struct net_device *dev,
7135 int (*fn)(struct net_device *dev,
7136 struct netdev_nested_priv *priv),
7137 struct netdev_nested_priv *priv)
7139 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7140 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7144 iter = &dev->adj_list.lower;
7148 ret = fn(now, priv);
7155 ldev = netdev_next_lower_dev(now, &iter);
7160 niter = &ldev->adj_list.lower;
7161 dev_stack[cur] = now;
7162 iter_stack[cur++] = iter;
7169 next = dev_stack[--cur];
7170 niter = iter_stack[cur];
7179 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7181 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7182 int (*fn)(struct net_device *dev,
7183 struct netdev_nested_priv *priv),
7184 struct netdev_nested_priv *priv)
7186 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7187 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7192 iter = &dev->adj_list.lower;
7196 ret = fn(now, priv);
7203 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7210 niter = &ldev->adj_list.lower;
7211 dev_stack[cur] = now;
7212 iter_stack[cur++] = iter;
7219 next = dev_stack[--cur];
7220 niter = iter_stack[cur];
7230 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7231 struct list_head **iter)
7233 struct netdev_adjacent *lower;
7235 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7236 if (&lower->list == &dev->adj_list.lower)
7239 *iter = &lower->list;
7243 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7245 static u8 __netdev_upper_depth(struct net_device *dev)
7247 struct net_device *udev;
7248 struct list_head *iter;
7252 for (iter = &dev->adj_list.upper,
7253 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7255 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7258 if (max_depth < udev->upper_level)
7259 max_depth = udev->upper_level;
7265 static u8 __netdev_lower_depth(struct net_device *dev)
7267 struct net_device *ldev;
7268 struct list_head *iter;
7272 for (iter = &dev->adj_list.lower,
7273 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7275 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7278 if (max_depth < ldev->lower_level)
7279 max_depth = ldev->lower_level;
7285 static int __netdev_update_upper_level(struct net_device *dev,
7286 struct netdev_nested_priv *__unused)
7288 dev->upper_level = __netdev_upper_depth(dev) + 1;
7292 #ifdef CONFIG_LOCKDEP
7293 static LIST_HEAD(net_unlink_list);
7295 static void net_unlink_todo(struct net_device *dev)
7297 if (list_empty(&dev->unlink_list))
7298 list_add_tail(&dev->unlink_list, &net_unlink_list);
7302 static int __netdev_update_lower_level(struct net_device *dev,
7303 struct netdev_nested_priv *priv)
7305 dev->lower_level = __netdev_lower_depth(dev) + 1;
7307 #ifdef CONFIG_LOCKDEP
7311 if (priv->flags & NESTED_SYNC_IMM)
7312 dev->nested_level = dev->lower_level - 1;
7313 if (priv->flags & NESTED_SYNC_TODO)
7314 net_unlink_todo(dev);
7319 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7320 int (*fn)(struct net_device *dev,
7321 struct netdev_nested_priv *priv),
7322 struct netdev_nested_priv *priv)
7324 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7325 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7329 iter = &dev->adj_list.lower;
7333 ret = fn(now, priv);
7340 ldev = netdev_next_lower_dev_rcu(now, &iter);
7345 niter = &ldev->adj_list.lower;
7346 dev_stack[cur] = now;
7347 iter_stack[cur++] = iter;
7354 next = dev_stack[--cur];
7355 niter = iter_stack[cur];
7364 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7367 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7368 * lower neighbour list, RCU
7372 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7373 * list. The caller must hold RCU read lock.
7375 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7377 struct netdev_adjacent *lower;
7379 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7380 struct netdev_adjacent, list);
7382 return lower->private;
7385 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7388 * netdev_master_upper_dev_get_rcu - Get master upper device
7391 * Find a master upper device and return pointer to it or NULL in case
7392 * it's not there. The caller must hold the RCU read lock.
7394 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7396 struct netdev_adjacent *upper;
7398 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7399 struct netdev_adjacent, list);
7400 if (upper && likely(upper->master))
7404 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7406 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7407 struct net_device *adj_dev,
7408 struct list_head *dev_list)
7410 char linkname[IFNAMSIZ+7];
7412 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7413 "upper_%s" : "lower_%s", adj_dev->name);
7414 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7417 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7419 struct list_head *dev_list)
7421 char linkname[IFNAMSIZ+7];
7423 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7424 "upper_%s" : "lower_%s", name);
7425 sysfs_remove_link(&(dev->dev.kobj), linkname);
7428 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7429 struct net_device *adj_dev,
7430 struct list_head *dev_list)
7432 return (dev_list == &dev->adj_list.upper ||
7433 dev_list == &dev->adj_list.lower) &&
7434 net_eq(dev_net(dev), dev_net(adj_dev));
7437 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7438 struct net_device *adj_dev,
7439 struct list_head *dev_list,
7440 void *private, bool master)
7442 struct netdev_adjacent *adj;
7445 adj = __netdev_find_adj(adj_dev, dev_list);
7449 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7450 dev->name, adj_dev->name, adj->ref_nr);
7455 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7460 adj->master = master;
7462 adj->private = private;
7463 adj->ignore = false;
7464 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7466 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7467 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7469 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7470 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7475 /* Ensure that master link is always the first item in list. */
7477 ret = sysfs_create_link(&(dev->dev.kobj),
7478 &(adj_dev->dev.kobj), "master");
7480 goto remove_symlinks;
7482 list_add_rcu(&adj->list, dev_list);
7484 list_add_tail_rcu(&adj->list, dev_list);
7490 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7491 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7493 netdev_put(adj_dev, &adj->dev_tracker);
7499 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7500 struct net_device *adj_dev,
7502 struct list_head *dev_list)
7504 struct netdev_adjacent *adj;
7506 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7507 dev->name, adj_dev->name, ref_nr);
7509 adj = __netdev_find_adj(adj_dev, dev_list);
7512 pr_err("Adjacency does not exist for device %s from %s\n",
7513 dev->name, adj_dev->name);
7518 if (adj->ref_nr > ref_nr) {
7519 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7520 dev->name, adj_dev->name, ref_nr,
7521 adj->ref_nr - ref_nr);
7522 adj->ref_nr -= ref_nr;
7527 sysfs_remove_link(&(dev->dev.kobj), "master");
7529 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7530 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7532 list_del_rcu(&adj->list);
7533 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7534 adj_dev->name, dev->name, adj_dev->name);
7535 netdev_put(adj_dev, &adj->dev_tracker);
7536 kfree_rcu(adj, rcu);
7539 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7540 struct net_device *upper_dev,
7541 struct list_head *up_list,
7542 struct list_head *down_list,
7543 void *private, bool master)
7547 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7552 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7555 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7562 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7563 struct net_device *upper_dev,
7565 struct list_head *up_list,
7566 struct list_head *down_list)
7568 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7569 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7572 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7573 struct net_device *upper_dev,
7574 void *private, bool master)
7576 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7577 &dev->adj_list.upper,
7578 &upper_dev->adj_list.lower,
7582 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7583 struct net_device *upper_dev)
7585 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7586 &dev->adj_list.upper,
7587 &upper_dev->adj_list.lower);
7590 static int __netdev_upper_dev_link(struct net_device *dev,
7591 struct net_device *upper_dev, bool master,
7592 void *upper_priv, void *upper_info,
7593 struct netdev_nested_priv *priv,
7594 struct netlink_ext_ack *extack)
7596 struct netdev_notifier_changeupper_info changeupper_info = {
7601 .upper_dev = upper_dev,
7604 .upper_info = upper_info,
7606 struct net_device *master_dev;
7611 if (dev == upper_dev)
7614 /* To prevent loops, check if dev is not upper device to upper_dev. */
7615 if (__netdev_has_upper_dev(upper_dev, dev))
7618 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7622 if (__netdev_has_upper_dev(dev, upper_dev))
7625 master_dev = __netdev_master_upper_dev_get(dev);
7627 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7630 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7631 &changeupper_info.info);
7632 ret = notifier_to_errno(ret);
7636 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7641 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7642 &changeupper_info.info);
7643 ret = notifier_to_errno(ret);
7647 __netdev_update_upper_level(dev, NULL);
7648 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7650 __netdev_update_lower_level(upper_dev, priv);
7651 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7657 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7663 * netdev_upper_dev_link - Add a link to the upper device
7665 * @upper_dev: new upper device
7666 * @extack: netlink extended ack
7668 * Adds a link to device which is upper to this one. The caller must hold
7669 * the RTNL lock. On a failure a negative errno code is returned.
7670 * On success the reference counts are adjusted and the function
7673 int netdev_upper_dev_link(struct net_device *dev,
7674 struct net_device *upper_dev,
7675 struct netlink_ext_ack *extack)
7677 struct netdev_nested_priv priv = {
7678 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7682 return __netdev_upper_dev_link(dev, upper_dev, false,
7683 NULL, NULL, &priv, extack);
7685 EXPORT_SYMBOL(netdev_upper_dev_link);
7688 * netdev_master_upper_dev_link - Add a master link to the upper device
7690 * @upper_dev: new upper device
7691 * @upper_priv: upper device private
7692 * @upper_info: upper info to be passed down via notifier
7693 * @extack: netlink extended ack
7695 * Adds a link to device which is upper to this one. In this case, only
7696 * one master upper device can be linked, although other non-master devices
7697 * might be linked as well. The caller must hold the RTNL lock.
7698 * On a failure a negative errno code is returned. On success the reference
7699 * counts are adjusted and the function returns zero.
7701 int netdev_master_upper_dev_link(struct net_device *dev,
7702 struct net_device *upper_dev,
7703 void *upper_priv, void *upper_info,
7704 struct netlink_ext_ack *extack)
7706 struct netdev_nested_priv priv = {
7707 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7711 return __netdev_upper_dev_link(dev, upper_dev, true,
7712 upper_priv, upper_info, &priv, extack);
7714 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7716 static void __netdev_upper_dev_unlink(struct net_device *dev,
7717 struct net_device *upper_dev,
7718 struct netdev_nested_priv *priv)
7720 struct netdev_notifier_changeupper_info changeupper_info = {
7724 .upper_dev = upper_dev,
7730 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7732 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7733 &changeupper_info.info);
7735 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7737 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7738 &changeupper_info.info);
7740 __netdev_update_upper_level(dev, NULL);
7741 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7743 __netdev_update_lower_level(upper_dev, priv);
7744 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7749 * netdev_upper_dev_unlink - Removes a link to upper device
7751 * @upper_dev: new upper device
7753 * Removes a link to device which is upper to this one. The caller must hold
7756 void netdev_upper_dev_unlink(struct net_device *dev,
7757 struct net_device *upper_dev)
7759 struct netdev_nested_priv priv = {
7760 .flags = NESTED_SYNC_TODO,
7764 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7766 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7768 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7769 struct net_device *lower_dev,
7772 struct netdev_adjacent *adj;
7774 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7778 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7783 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7784 struct net_device *lower_dev)
7786 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7789 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7790 struct net_device *lower_dev)
7792 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7795 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7796 struct net_device *new_dev,
7797 struct net_device *dev,
7798 struct netlink_ext_ack *extack)
7800 struct netdev_nested_priv priv = {
7809 if (old_dev && new_dev != old_dev)
7810 netdev_adjacent_dev_disable(dev, old_dev);
7811 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7814 if (old_dev && new_dev != old_dev)
7815 netdev_adjacent_dev_enable(dev, old_dev);
7821 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7823 void netdev_adjacent_change_commit(struct net_device *old_dev,
7824 struct net_device *new_dev,
7825 struct net_device *dev)
7827 struct netdev_nested_priv priv = {
7828 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7832 if (!new_dev || !old_dev)
7835 if (new_dev == old_dev)
7838 netdev_adjacent_dev_enable(dev, old_dev);
7839 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7841 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7843 void netdev_adjacent_change_abort(struct net_device *old_dev,
7844 struct net_device *new_dev,
7845 struct net_device *dev)
7847 struct netdev_nested_priv priv = {
7855 if (old_dev && new_dev != old_dev)
7856 netdev_adjacent_dev_enable(dev, old_dev);
7858 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7860 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7863 * netdev_bonding_info_change - Dispatch event about slave change
7865 * @bonding_info: info to dispatch
7867 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7868 * The caller must hold the RTNL lock.
7870 void netdev_bonding_info_change(struct net_device *dev,
7871 struct netdev_bonding_info *bonding_info)
7873 struct netdev_notifier_bonding_info info = {
7877 memcpy(&info.bonding_info, bonding_info,
7878 sizeof(struct netdev_bonding_info));
7879 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7882 EXPORT_SYMBOL(netdev_bonding_info_change);
7884 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
7885 struct netlink_ext_ack *extack)
7887 struct netdev_notifier_offload_xstats_info info = {
7889 .info.extack = extack,
7890 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7895 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
7897 if (!dev->offload_xstats_l3)
7900 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
7901 NETDEV_OFFLOAD_XSTATS_DISABLE,
7903 err = notifier_to_errno(rc);
7910 kfree(dev->offload_xstats_l3);
7911 dev->offload_xstats_l3 = NULL;
7915 int netdev_offload_xstats_enable(struct net_device *dev,
7916 enum netdev_offload_xstats_type type,
7917 struct netlink_ext_ack *extack)
7921 if (netdev_offload_xstats_enabled(dev, type))
7925 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7926 return netdev_offload_xstats_enable_l3(dev, extack);
7932 EXPORT_SYMBOL(netdev_offload_xstats_enable);
7934 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
7936 struct netdev_notifier_offload_xstats_info info = {
7938 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7941 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
7943 kfree(dev->offload_xstats_l3);
7944 dev->offload_xstats_l3 = NULL;
7947 int netdev_offload_xstats_disable(struct net_device *dev,
7948 enum netdev_offload_xstats_type type)
7952 if (!netdev_offload_xstats_enabled(dev, type))
7956 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7957 netdev_offload_xstats_disable_l3(dev);
7964 EXPORT_SYMBOL(netdev_offload_xstats_disable);
7966 static void netdev_offload_xstats_disable_all(struct net_device *dev)
7968 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
7971 static struct rtnl_hw_stats64 *
7972 netdev_offload_xstats_get_ptr(const struct net_device *dev,
7973 enum netdev_offload_xstats_type type)
7976 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7977 return dev->offload_xstats_l3;
7984 bool netdev_offload_xstats_enabled(const struct net_device *dev,
7985 enum netdev_offload_xstats_type type)
7989 return netdev_offload_xstats_get_ptr(dev, type);
7991 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
7993 struct netdev_notifier_offload_xstats_ru {
7997 struct netdev_notifier_offload_xstats_rd {
7998 struct rtnl_hw_stats64 stats;
8002 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8003 const struct rtnl_hw_stats64 *src)
8005 dest->rx_packets += src->rx_packets;
8006 dest->tx_packets += src->tx_packets;
8007 dest->rx_bytes += src->rx_bytes;
8008 dest->tx_bytes += src->tx_bytes;
8009 dest->rx_errors += src->rx_errors;
8010 dest->tx_errors += src->tx_errors;
8011 dest->rx_dropped += src->rx_dropped;
8012 dest->tx_dropped += src->tx_dropped;
8013 dest->multicast += src->multicast;
8016 static int netdev_offload_xstats_get_used(struct net_device *dev,
8017 enum netdev_offload_xstats_type type,
8019 struct netlink_ext_ack *extack)
8021 struct netdev_notifier_offload_xstats_ru report_used = {};
8022 struct netdev_notifier_offload_xstats_info info = {
8024 .info.extack = extack,
8026 .report_used = &report_used,
8030 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8031 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8033 *p_used = report_used.used;
8034 return notifier_to_errno(rc);
8037 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8038 enum netdev_offload_xstats_type type,
8039 struct rtnl_hw_stats64 *p_stats,
8041 struct netlink_ext_ack *extack)
8043 struct netdev_notifier_offload_xstats_rd report_delta = {};
8044 struct netdev_notifier_offload_xstats_info info = {
8046 .info.extack = extack,
8048 .report_delta = &report_delta,
8050 struct rtnl_hw_stats64 *stats;
8053 stats = netdev_offload_xstats_get_ptr(dev, type);
8054 if (WARN_ON(!stats))
8057 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8060 /* Cache whatever we got, even if there was an error, otherwise the
8061 * successful stats retrievals would get lost.
8063 netdev_hw_stats64_add(stats, &report_delta.stats);
8067 *p_used = report_delta.used;
8069 return notifier_to_errno(rc);
8072 int netdev_offload_xstats_get(struct net_device *dev,
8073 enum netdev_offload_xstats_type type,
8074 struct rtnl_hw_stats64 *p_stats, bool *p_used,
8075 struct netlink_ext_ack *extack)
8080 return netdev_offload_xstats_get_stats(dev, type, p_stats,
8083 return netdev_offload_xstats_get_used(dev, type, p_used,
8086 EXPORT_SYMBOL(netdev_offload_xstats_get);
8089 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8090 const struct rtnl_hw_stats64 *stats)
8092 report_delta->used = true;
8093 netdev_hw_stats64_add(&report_delta->stats, stats);
8095 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8098 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8100 report_used->used = true;
8102 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8104 void netdev_offload_xstats_push_delta(struct net_device *dev,
8105 enum netdev_offload_xstats_type type,
8106 const struct rtnl_hw_stats64 *p_stats)
8108 struct rtnl_hw_stats64 *stats;
8112 stats = netdev_offload_xstats_get_ptr(dev, type);
8113 if (WARN_ON(!stats))
8116 netdev_hw_stats64_add(stats, p_stats);
8118 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8121 * netdev_get_xmit_slave - Get the xmit slave of master device
8124 * @all_slaves: assume all the slaves are active
8126 * The reference counters are not incremented so the caller must be
8127 * careful with locks. The caller must hold RCU lock.
8128 * %NULL is returned if no slave is found.
8131 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8132 struct sk_buff *skb,
8135 const struct net_device_ops *ops = dev->netdev_ops;
8137 if (!ops->ndo_get_xmit_slave)
8139 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8141 EXPORT_SYMBOL(netdev_get_xmit_slave);
8143 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8146 const struct net_device_ops *ops = dev->netdev_ops;
8148 if (!ops->ndo_sk_get_lower_dev)
8150 return ops->ndo_sk_get_lower_dev(dev, sk);
8154 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8158 * %NULL is returned if no lower device is found.
8161 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8164 struct net_device *lower;
8166 lower = netdev_sk_get_lower_dev(dev, sk);
8169 lower = netdev_sk_get_lower_dev(dev, sk);
8174 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8176 static void netdev_adjacent_add_links(struct net_device *dev)
8178 struct netdev_adjacent *iter;
8180 struct net *net = dev_net(dev);
8182 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8183 if (!net_eq(net, dev_net(iter->dev)))
8185 netdev_adjacent_sysfs_add(iter->dev, dev,
8186 &iter->dev->adj_list.lower);
8187 netdev_adjacent_sysfs_add(dev, iter->dev,
8188 &dev->adj_list.upper);
8191 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8192 if (!net_eq(net, dev_net(iter->dev)))
8194 netdev_adjacent_sysfs_add(iter->dev, dev,
8195 &iter->dev->adj_list.upper);
8196 netdev_adjacent_sysfs_add(dev, iter->dev,
8197 &dev->adj_list.lower);
8201 static void netdev_adjacent_del_links(struct net_device *dev)
8203 struct netdev_adjacent *iter;
8205 struct net *net = dev_net(dev);
8207 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8208 if (!net_eq(net, dev_net(iter->dev)))
8210 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8211 &iter->dev->adj_list.lower);
8212 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8213 &dev->adj_list.upper);
8216 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8217 if (!net_eq(net, dev_net(iter->dev)))
8219 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8220 &iter->dev->adj_list.upper);
8221 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8222 &dev->adj_list.lower);
8226 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8228 struct netdev_adjacent *iter;
8230 struct net *net = dev_net(dev);
8232 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8233 if (!net_eq(net, dev_net(iter->dev)))
8235 netdev_adjacent_sysfs_del(iter->dev, oldname,
8236 &iter->dev->adj_list.lower);
8237 netdev_adjacent_sysfs_add(iter->dev, dev,
8238 &iter->dev->adj_list.lower);
8241 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8242 if (!net_eq(net, dev_net(iter->dev)))
8244 netdev_adjacent_sysfs_del(iter->dev, oldname,
8245 &iter->dev->adj_list.upper);
8246 netdev_adjacent_sysfs_add(iter->dev, dev,
8247 &iter->dev->adj_list.upper);
8251 void *netdev_lower_dev_get_private(struct net_device *dev,
8252 struct net_device *lower_dev)
8254 struct netdev_adjacent *lower;
8258 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8262 return lower->private;
8264 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8268 * netdev_lower_state_changed - Dispatch event about lower device state change
8269 * @lower_dev: device
8270 * @lower_state_info: state to dispatch
8272 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8273 * The caller must hold the RTNL lock.
8275 void netdev_lower_state_changed(struct net_device *lower_dev,
8276 void *lower_state_info)
8278 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8279 .info.dev = lower_dev,
8283 changelowerstate_info.lower_state_info = lower_state_info;
8284 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8285 &changelowerstate_info.info);
8287 EXPORT_SYMBOL(netdev_lower_state_changed);
8289 static void dev_change_rx_flags(struct net_device *dev, int flags)
8291 const struct net_device_ops *ops = dev->netdev_ops;
8293 if (ops->ndo_change_rx_flags)
8294 ops->ndo_change_rx_flags(dev, flags);
8297 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8299 unsigned int old_flags = dev->flags;
8305 dev->flags |= IFF_PROMISC;
8306 dev->promiscuity += inc;
8307 if (dev->promiscuity == 0) {
8310 * If inc causes overflow, untouch promisc and return error.
8313 dev->flags &= ~IFF_PROMISC;
8315 dev->promiscuity -= inc;
8316 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8320 if (dev->flags != old_flags) {
8321 netdev_info(dev, "%s promiscuous mode\n",
8322 dev->flags & IFF_PROMISC ? "entered" : "left");
8323 if (audit_enabled) {
8324 current_uid_gid(&uid, &gid);
8325 audit_log(audit_context(), GFP_ATOMIC,
8326 AUDIT_ANOM_PROMISCUOUS,
8327 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8328 dev->name, (dev->flags & IFF_PROMISC),
8329 (old_flags & IFF_PROMISC),
8330 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8331 from_kuid(&init_user_ns, uid),
8332 from_kgid(&init_user_ns, gid),
8333 audit_get_sessionid(current));
8336 dev_change_rx_flags(dev, IFF_PROMISC);
8339 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8344 * dev_set_promiscuity - update promiscuity count on a device
8348 * Add or remove promiscuity from a device. While the count in the device
8349 * remains above zero the interface remains promiscuous. Once it hits zero
8350 * the device reverts back to normal filtering operation. A negative inc
8351 * value is used to drop promiscuity on the device.
8352 * Return 0 if successful or a negative errno code on error.
8354 int dev_set_promiscuity(struct net_device *dev, int inc)
8356 unsigned int old_flags = dev->flags;
8359 err = __dev_set_promiscuity(dev, inc, true);
8362 if (dev->flags != old_flags)
8363 dev_set_rx_mode(dev);
8366 EXPORT_SYMBOL(dev_set_promiscuity);
8368 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8370 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8374 dev->flags |= IFF_ALLMULTI;
8375 dev->allmulti += inc;
8376 if (dev->allmulti == 0) {
8379 * If inc causes overflow, untouch allmulti and return error.
8382 dev->flags &= ~IFF_ALLMULTI;
8384 dev->allmulti -= inc;
8385 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8389 if (dev->flags ^ old_flags) {
8390 netdev_info(dev, "%s allmulticast mode\n",
8391 dev->flags & IFF_ALLMULTI ? "entered" : "left");
8392 dev_change_rx_flags(dev, IFF_ALLMULTI);
8393 dev_set_rx_mode(dev);
8395 __dev_notify_flags(dev, old_flags,
8396 dev->gflags ^ old_gflags, 0, NULL);
8402 * dev_set_allmulti - update allmulti count on a device
8406 * Add or remove reception of all multicast frames to a device. While the
8407 * count in the device remains above zero the interface remains listening
8408 * to all interfaces. Once it hits zero the device reverts back to normal
8409 * filtering operation. A negative @inc value is used to drop the counter
8410 * when releasing a resource needing all multicasts.
8411 * Return 0 if successful or a negative errno code on error.
8414 int dev_set_allmulti(struct net_device *dev, int inc)
8416 return __dev_set_allmulti(dev, inc, true);
8418 EXPORT_SYMBOL(dev_set_allmulti);
8421 * Upload unicast and multicast address lists to device and
8422 * configure RX filtering. When the device doesn't support unicast
8423 * filtering it is put in promiscuous mode while unicast addresses
8426 void __dev_set_rx_mode(struct net_device *dev)
8428 const struct net_device_ops *ops = dev->netdev_ops;
8430 /* dev_open will call this function so the list will stay sane. */
8431 if (!(dev->flags&IFF_UP))
8434 if (!netif_device_present(dev))
8437 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8438 /* Unicast addresses changes may only happen under the rtnl,
8439 * therefore calling __dev_set_promiscuity here is safe.
8441 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8442 __dev_set_promiscuity(dev, 1, false);
8443 dev->uc_promisc = true;
8444 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8445 __dev_set_promiscuity(dev, -1, false);
8446 dev->uc_promisc = false;
8450 if (ops->ndo_set_rx_mode)
8451 ops->ndo_set_rx_mode(dev);
8454 void dev_set_rx_mode(struct net_device *dev)
8456 netif_addr_lock_bh(dev);
8457 __dev_set_rx_mode(dev);
8458 netif_addr_unlock_bh(dev);
8462 * dev_get_flags - get flags reported to userspace
8465 * Get the combination of flag bits exported through APIs to userspace.
8467 unsigned int dev_get_flags(const struct net_device *dev)
8471 flags = (dev->flags & ~(IFF_PROMISC |
8476 (dev->gflags & (IFF_PROMISC |
8479 if (netif_running(dev)) {
8480 if (netif_oper_up(dev))
8481 flags |= IFF_RUNNING;
8482 if (netif_carrier_ok(dev))
8483 flags |= IFF_LOWER_UP;
8484 if (netif_dormant(dev))
8485 flags |= IFF_DORMANT;
8490 EXPORT_SYMBOL(dev_get_flags);
8492 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8493 struct netlink_ext_ack *extack)
8495 unsigned int old_flags = dev->flags;
8501 * Set the flags on our device.
8504 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8505 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8507 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8511 * Load in the correct multicast list now the flags have changed.
8514 if ((old_flags ^ flags) & IFF_MULTICAST)
8515 dev_change_rx_flags(dev, IFF_MULTICAST);
8517 dev_set_rx_mode(dev);
8520 * Have we downed the interface. We handle IFF_UP ourselves
8521 * according to user attempts to set it, rather than blindly
8526 if ((old_flags ^ flags) & IFF_UP) {
8527 if (old_flags & IFF_UP)
8530 ret = __dev_open(dev, extack);
8533 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8534 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8535 unsigned int old_flags = dev->flags;
8537 dev->gflags ^= IFF_PROMISC;
8539 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8540 if (dev->flags != old_flags)
8541 dev_set_rx_mode(dev);
8544 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8545 * is important. Some (broken) drivers set IFF_PROMISC, when
8546 * IFF_ALLMULTI is requested not asking us and not reporting.
8548 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8549 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8551 dev->gflags ^= IFF_ALLMULTI;
8552 __dev_set_allmulti(dev, inc, false);
8558 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8559 unsigned int gchanges, u32 portid,
8560 const struct nlmsghdr *nlh)
8562 unsigned int changes = dev->flags ^ old_flags;
8565 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8567 if (changes & IFF_UP) {
8568 if (dev->flags & IFF_UP)
8569 call_netdevice_notifiers(NETDEV_UP, dev);
8571 call_netdevice_notifiers(NETDEV_DOWN, dev);
8574 if (dev->flags & IFF_UP &&
8575 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8576 struct netdev_notifier_change_info change_info = {
8580 .flags_changed = changes,
8583 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8588 * dev_change_flags - change device settings
8590 * @flags: device state flags
8591 * @extack: netlink extended ack
8593 * Change settings on device based state flags. The flags are
8594 * in the userspace exported format.
8596 int dev_change_flags(struct net_device *dev, unsigned int flags,
8597 struct netlink_ext_ack *extack)
8600 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8602 ret = __dev_change_flags(dev, flags, extack);
8606 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8607 __dev_notify_flags(dev, old_flags, changes, 0, NULL);
8610 EXPORT_SYMBOL(dev_change_flags);
8612 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8614 const struct net_device_ops *ops = dev->netdev_ops;
8616 if (ops->ndo_change_mtu)
8617 return ops->ndo_change_mtu(dev, new_mtu);
8619 /* Pairs with all the lockless reads of dev->mtu in the stack */
8620 WRITE_ONCE(dev->mtu, new_mtu);
8623 EXPORT_SYMBOL(__dev_set_mtu);
8625 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8626 struct netlink_ext_ack *extack)
8628 /* MTU must be positive, and in range */
8629 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8630 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8634 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8635 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8642 * dev_set_mtu_ext - Change maximum transfer unit
8644 * @new_mtu: new transfer unit
8645 * @extack: netlink extended ack
8647 * Change the maximum transfer size of the network device.
8649 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8650 struct netlink_ext_ack *extack)
8654 if (new_mtu == dev->mtu)
8657 err = dev_validate_mtu(dev, new_mtu, extack);
8661 if (!netif_device_present(dev))
8664 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8665 err = notifier_to_errno(err);
8669 orig_mtu = dev->mtu;
8670 err = __dev_set_mtu(dev, new_mtu);
8673 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8675 err = notifier_to_errno(err);
8677 /* setting mtu back and notifying everyone again,
8678 * so that they have a chance to revert changes.
8680 __dev_set_mtu(dev, orig_mtu);
8681 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8688 int dev_set_mtu(struct net_device *dev, int new_mtu)
8690 struct netlink_ext_ack extack;
8693 memset(&extack, 0, sizeof(extack));
8694 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8695 if (err && extack._msg)
8696 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8699 EXPORT_SYMBOL(dev_set_mtu);
8702 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8704 * @new_len: new tx queue length
8706 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8708 unsigned int orig_len = dev->tx_queue_len;
8711 if (new_len != (unsigned int)new_len)
8714 if (new_len != orig_len) {
8715 dev->tx_queue_len = new_len;
8716 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8717 res = notifier_to_errno(res);
8720 res = dev_qdisc_change_tx_queue_len(dev);
8728 netdev_err(dev, "refused to change device tx_queue_len\n");
8729 dev->tx_queue_len = orig_len;
8734 * dev_set_group - Change group this device belongs to
8736 * @new_group: group this device should belong to
8738 void dev_set_group(struct net_device *dev, int new_group)
8740 dev->group = new_group;
8744 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8746 * @addr: new address
8747 * @extack: netlink extended ack
8749 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8750 struct netlink_ext_ack *extack)
8752 struct netdev_notifier_pre_changeaddr_info info = {
8754 .info.extack = extack,
8759 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8760 return notifier_to_errno(rc);
8762 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8765 * dev_set_mac_address - Change Media Access Control Address
8768 * @extack: netlink extended ack
8770 * Change the hardware (MAC) address of the device
8772 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8773 struct netlink_ext_ack *extack)
8775 const struct net_device_ops *ops = dev->netdev_ops;
8778 if (!ops->ndo_set_mac_address)
8780 if (sa->sa_family != dev->type)
8782 if (!netif_device_present(dev))
8784 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8787 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
8788 err = ops->ndo_set_mac_address(dev, sa);
8792 dev->addr_assign_type = NET_ADDR_SET;
8793 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8794 add_device_randomness(dev->dev_addr, dev->addr_len);
8797 EXPORT_SYMBOL(dev_set_mac_address);
8799 static DECLARE_RWSEM(dev_addr_sem);
8801 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8802 struct netlink_ext_ack *extack)
8806 down_write(&dev_addr_sem);
8807 ret = dev_set_mac_address(dev, sa, extack);
8808 up_write(&dev_addr_sem);
8811 EXPORT_SYMBOL(dev_set_mac_address_user);
8813 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8815 size_t size = sizeof(sa->sa_data_min);
8816 struct net_device *dev;
8819 down_read(&dev_addr_sem);
8822 dev = dev_get_by_name_rcu(net, dev_name);
8828 memset(sa->sa_data, 0, size);
8830 memcpy(sa->sa_data, dev->dev_addr,
8831 min_t(size_t, size, dev->addr_len));
8832 sa->sa_family = dev->type;
8836 up_read(&dev_addr_sem);
8839 EXPORT_SYMBOL(dev_get_mac_address);
8842 * dev_change_carrier - Change device carrier
8844 * @new_carrier: new value
8846 * Change device carrier
8848 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8850 const struct net_device_ops *ops = dev->netdev_ops;
8852 if (!ops->ndo_change_carrier)
8854 if (!netif_device_present(dev))
8856 return ops->ndo_change_carrier(dev, new_carrier);
8860 * dev_get_phys_port_id - Get device physical port ID
8864 * Get device physical port ID
8866 int dev_get_phys_port_id(struct net_device *dev,
8867 struct netdev_phys_item_id *ppid)
8869 const struct net_device_ops *ops = dev->netdev_ops;
8871 if (!ops->ndo_get_phys_port_id)
8873 return ops->ndo_get_phys_port_id(dev, ppid);
8877 * dev_get_phys_port_name - Get device physical port name
8880 * @len: limit of bytes to copy to name
8882 * Get device physical port name
8884 int dev_get_phys_port_name(struct net_device *dev,
8885 char *name, size_t len)
8887 const struct net_device_ops *ops = dev->netdev_ops;
8890 if (ops->ndo_get_phys_port_name) {
8891 err = ops->ndo_get_phys_port_name(dev, name, len);
8892 if (err != -EOPNOTSUPP)
8895 return devlink_compat_phys_port_name_get(dev, name, len);
8899 * dev_get_port_parent_id - Get the device's port parent identifier
8900 * @dev: network device
8901 * @ppid: pointer to a storage for the port's parent identifier
8902 * @recurse: allow/disallow recursion to lower devices
8904 * Get the devices's port parent identifier
8906 int dev_get_port_parent_id(struct net_device *dev,
8907 struct netdev_phys_item_id *ppid,
8910 const struct net_device_ops *ops = dev->netdev_ops;
8911 struct netdev_phys_item_id first = { };
8912 struct net_device *lower_dev;
8913 struct list_head *iter;
8916 if (ops->ndo_get_port_parent_id) {
8917 err = ops->ndo_get_port_parent_id(dev, ppid);
8918 if (err != -EOPNOTSUPP)
8922 err = devlink_compat_switch_id_get(dev, ppid);
8923 if (!recurse || err != -EOPNOTSUPP)
8926 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8927 err = dev_get_port_parent_id(lower_dev, ppid, true);
8932 else if (memcmp(&first, ppid, sizeof(*ppid)))
8938 EXPORT_SYMBOL(dev_get_port_parent_id);
8941 * netdev_port_same_parent_id - Indicate if two network devices have
8942 * the same port parent identifier
8943 * @a: first network device
8944 * @b: second network device
8946 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8948 struct netdev_phys_item_id a_id = { };
8949 struct netdev_phys_item_id b_id = { };
8951 if (dev_get_port_parent_id(a, &a_id, true) ||
8952 dev_get_port_parent_id(b, &b_id, true))
8955 return netdev_phys_item_id_same(&a_id, &b_id);
8957 EXPORT_SYMBOL(netdev_port_same_parent_id);
8960 * dev_change_proto_down - set carrier according to proto_down.
8963 * @proto_down: new value
8965 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8967 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
8969 if (!netif_device_present(dev))
8972 netif_carrier_off(dev);
8974 netif_carrier_on(dev);
8975 dev->proto_down = proto_down;
8980 * dev_change_proto_down_reason - proto down reason
8983 * @mask: proto down mask
8984 * @value: proto down value
8986 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8992 dev->proto_down_reason = value;
8994 for_each_set_bit(b, &mask, 32) {
8995 if (value & (1 << b))
8996 dev->proto_down_reason |= BIT(b);
8998 dev->proto_down_reason &= ~BIT(b);
9003 struct bpf_xdp_link {
9004 struct bpf_link link;
9005 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9009 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9011 if (flags & XDP_FLAGS_HW_MODE)
9013 if (flags & XDP_FLAGS_DRV_MODE)
9014 return XDP_MODE_DRV;
9015 if (flags & XDP_FLAGS_SKB_MODE)
9016 return XDP_MODE_SKB;
9017 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9020 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9024 return generic_xdp_install;
9027 return dev->netdev_ops->ndo_bpf;
9033 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9034 enum bpf_xdp_mode mode)
9036 return dev->xdp_state[mode].link;
9039 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9040 enum bpf_xdp_mode mode)
9042 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9045 return link->link.prog;
9046 return dev->xdp_state[mode].prog;
9049 u8 dev_xdp_prog_count(struct net_device *dev)
9054 for (i = 0; i < __MAX_XDP_MODE; i++)
9055 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9059 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9061 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9063 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9065 return prog ? prog->aux->id : 0;
9068 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9069 struct bpf_xdp_link *link)
9071 dev->xdp_state[mode].link = link;
9072 dev->xdp_state[mode].prog = NULL;
9075 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9076 struct bpf_prog *prog)
9078 dev->xdp_state[mode].link = NULL;
9079 dev->xdp_state[mode].prog = prog;
9082 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9083 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9084 u32 flags, struct bpf_prog *prog)
9086 struct netdev_bpf xdp;
9089 memset(&xdp, 0, sizeof(xdp));
9090 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9091 xdp.extack = extack;
9095 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9096 * "moved" into driver), so they don't increment it on their own, but
9097 * they do decrement refcnt when program is detached or replaced.
9098 * Given net_device also owns link/prog, we need to bump refcnt here
9099 * to prevent drivers from underflowing it.
9103 err = bpf_op(dev, &xdp);
9110 if (mode != XDP_MODE_HW)
9111 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9116 static void dev_xdp_uninstall(struct net_device *dev)
9118 struct bpf_xdp_link *link;
9119 struct bpf_prog *prog;
9120 enum bpf_xdp_mode mode;
9125 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9126 prog = dev_xdp_prog(dev, mode);
9130 bpf_op = dev_xdp_bpf_op(dev, mode);
9134 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9136 /* auto-detach link from net device */
9137 link = dev_xdp_link(dev, mode);
9143 dev_xdp_set_link(dev, mode, NULL);
9147 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9148 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9149 struct bpf_prog *old_prog, u32 flags)
9151 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9152 struct bpf_prog *cur_prog;
9153 struct net_device *upper;
9154 struct list_head *iter;
9155 enum bpf_xdp_mode mode;
9161 /* either link or prog attachment, never both */
9162 if (link && (new_prog || old_prog))
9164 /* link supports only XDP mode flags */
9165 if (link && (flags & ~XDP_FLAGS_MODES)) {
9166 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9169 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9170 if (num_modes > 1) {
9171 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9174 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9175 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9176 NL_SET_ERR_MSG(extack,
9177 "More than one program loaded, unset mode is ambiguous");
9180 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9181 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9182 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9186 mode = dev_xdp_mode(dev, flags);
9187 /* can't replace attached link */
9188 if (dev_xdp_link(dev, mode)) {
9189 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9193 /* don't allow if an upper device already has a program */
9194 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9195 if (dev_xdp_prog_count(upper) > 0) {
9196 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9201 cur_prog = dev_xdp_prog(dev, mode);
9202 /* can't replace attached prog with link */
9203 if (link && cur_prog) {
9204 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9207 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9208 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9212 /* put effective new program into new_prog */
9214 new_prog = link->link.prog;
9217 bool offload = mode == XDP_MODE_HW;
9218 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9219 ? XDP_MODE_DRV : XDP_MODE_SKB;
9221 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9222 NL_SET_ERR_MSG(extack, "XDP program already attached");
9225 if (!offload && dev_xdp_prog(dev, other_mode)) {
9226 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9229 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9230 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9233 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9234 NL_SET_ERR_MSG(extack, "Program bound to different device");
9237 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9238 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9241 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9242 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9247 /* don't call drivers if the effective program didn't change */
9248 if (new_prog != cur_prog) {
9249 bpf_op = dev_xdp_bpf_op(dev, mode);
9251 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9255 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9261 dev_xdp_set_link(dev, mode, link);
9263 dev_xdp_set_prog(dev, mode, new_prog);
9265 bpf_prog_put(cur_prog);
9270 static int dev_xdp_attach_link(struct net_device *dev,
9271 struct netlink_ext_ack *extack,
9272 struct bpf_xdp_link *link)
9274 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9277 static int dev_xdp_detach_link(struct net_device *dev,
9278 struct netlink_ext_ack *extack,
9279 struct bpf_xdp_link *link)
9281 enum bpf_xdp_mode mode;
9286 mode = dev_xdp_mode(dev, link->flags);
9287 if (dev_xdp_link(dev, mode) != link)
9290 bpf_op = dev_xdp_bpf_op(dev, mode);
9291 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9292 dev_xdp_set_link(dev, mode, NULL);
9296 static void bpf_xdp_link_release(struct bpf_link *link)
9298 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9302 /* if racing with net_device's tear down, xdp_link->dev might be
9303 * already NULL, in which case link was already auto-detached
9305 if (xdp_link->dev) {
9306 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9307 xdp_link->dev = NULL;
9313 static int bpf_xdp_link_detach(struct bpf_link *link)
9315 bpf_xdp_link_release(link);
9319 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9321 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9326 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9327 struct seq_file *seq)
9329 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9334 ifindex = xdp_link->dev->ifindex;
9337 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9340 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9341 struct bpf_link_info *info)
9343 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9348 ifindex = xdp_link->dev->ifindex;
9351 info->xdp.ifindex = ifindex;
9355 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9356 struct bpf_prog *old_prog)
9358 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9359 enum bpf_xdp_mode mode;
9365 /* link might have been auto-released already, so fail */
9366 if (!xdp_link->dev) {
9371 if (old_prog && link->prog != old_prog) {
9375 old_prog = link->prog;
9376 if (old_prog->type != new_prog->type ||
9377 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9382 if (old_prog == new_prog) {
9383 /* no-op, don't disturb drivers */
9384 bpf_prog_put(new_prog);
9388 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9389 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9390 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9391 xdp_link->flags, new_prog);
9395 old_prog = xchg(&link->prog, new_prog);
9396 bpf_prog_put(old_prog);
9403 static const struct bpf_link_ops bpf_xdp_link_lops = {
9404 .release = bpf_xdp_link_release,
9405 .dealloc = bpf_xdp_link_dealloc,
9406 .detach = bpf_xdp_link_detach,
9407 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9408 .fill_link_info = bpf_xdp_link_fill_link_info,
9409 .update_prog = bpf_xdp_link_update,
9412 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9414 struct net *net = current->nsproxy->net_ns;
9415 struct bpf_link_primer link_primer;
9416 struct bpf_xdp_link *link;
9417 struct net_device *dev;
9421 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9427 link = kzalloc(sizeof(*link), GFP_USER);
9433 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9435 link->flags = attr->link_create.flags;
9437 err = bpf_link_prime(&link->link, &link_primer);
9443 err = dev_xdp_attach_link(dev, NULL, link);
9448 bpf_link_cleanup(&link_primer);
9452 fd = bpf_link_settle(&link_primer);
9453 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9466 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9468 * @extack: netlink extended ack
9469 * @fd: new program fd or negative value to clear
9470 * @expected_fd: old program fd that userspace expects to replace or clear
9471 * @flags: xdp-related flags
9473 * Set or clear a bpf program for a device
9475 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9476 int fd, int expected_fd, u32 flags)
9478 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9479 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9485 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9486 mode != XDP_MODE_SKB);
9487 if (IS_ERR(new_prog))
9488 return PTR_ERR(new_prog);
9491 if (expected_fd >= 0) {
9492 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9493 mode != XDP_MODE_SKB);
9494 if (IS_ERR(old_prog)) {
9495 err = PTR_ERR(old_prog);
9501 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9504 if (err && new_prog)
9505 bpf_prog_put(new_prog);
9507 bpf_prog_put(old_prog);
9512 * dev_new_index - allocate an ifindex
9513 * @net: the applicable net namespace
9515 * Returns a suitable unique value for a new device interface
9516 * number. The caller must hold the rtnl semaphore or the
9517 * dev_base_lock to be sure it remains unique.
9519 static int dev_new_index(struct net *net)
9521 int ifindex = net->ifindex;
9526 if (!__dev_get_by_index(net, ifindex))
9527 return net->ifindex = ifindex;
9531 /* Delayed registration/unregisteration */
9532 LIST_HEAD(net_todo_list);
9533 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9535 static void net_set_todo(struct net_device *dev)
9537 list_add_tail(&dev->todo_list, &net_todo_list);
9538 atomic_inc(&dev_net(dev)->dev_unreg_count);
9541 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9542 struct net_device *upper, netdev_features_t features)
9544 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9545 netdev_features_t feature;
9548 for_each_netdev_feature(upper_disables, feature_bit) {
9549 feature = __NETIF_F_BIT(feature_bit);
9550 if (!(upper->wanted_features & feature)
9551 && (features & feature)) {
9552 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9553 &feature, upper->name);
9554 features &= ~feature;
9561 static void netdev_sync_lower_features(struct net_device *upper,
9562 struct net_device *lower, netdev_features_t features)
9564 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9565 netdev_features_t feature;
9568 for_each_netdev_feature(upper_disables, feature_bit) {
9569 feature = __NETIF_F_BIT(feature_bit);
9570 if (!(features & feature) && (lower->features & feature)) {
9571 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9572 &feature, lower->name);
9573 lower->wanted_features &= ~feature;
9574 __netdev_update_features(lower);
9576 if (unlikely(lower->features & feature))
9577 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9578 &feature, lower->name);
9580 netdev_features_change(lower);
9585 static netdev_features_t netdev_fix_features(struct net_device *dev,
9586 netdev_features_t features)
9588 /* Fix illegal checksum combinations */
9589 if ((features & NETIF_F_HW_CSUM) &&
9590 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9591 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9592 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9595 /* TSO requires that SG is present as well. */
9596 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9597 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9598 features &= ~NETIF_F_ALL_TSO;
9601 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9602 !(features & NETIF_F_IP_CSUM)) {
9603 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9604 features &= ~NETIF_F_TSO;
9605 features &= ~NETIF_F_TSO_ECN;
9608 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9609 !(features & NETIF_F_IPV6_CSUM)) {
9610 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9611 features &= ~NETIF_F_TSO6;
9614 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9615 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9616 features &= ~NETIF_F_TSO_MANGLEID;
9618 /* TSO ECN requires that TSO is present as well. */
9619 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9620 features &= ~NETIF_F_TSO_ECN;
9622 /* Software GSO depends on SG. */
9623 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9624 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9625 features &= ~NETIF_F_GSO;
9628 /* GSO partial features require GSO partial be set */
9629 if ((features & dev->gso_partial_features) &&
9630 !(features & NETIF_F_GSO_PARTIAL)) {
9632 "Dropping partially supported GSO features since no GSO partial.\n");
9633 features &= ~dev->gso_partial_features;
9636 if (!(features & NETIF_F_RXCSUM)) {
9637 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9638 * successfully merged by hardware must also have the
9639 * checksum verified by hardware. If the user does not
9640 * want to enable RXCSUM, logically, we should disable GRO_HW.
9642 if (features & NETIF_F_GRO_HW) {
9643 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9644 features &= ~NETIF_F_GRO_HW;
9648 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9649 if (features & NETIF_F_RXFCS) {
9650 if (features & NETIF_F_LRO) {
9651 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9652 features &= ~NETIF_F_LRO;
9655 if (features & NETIF_F_GRO_HW) {
9656 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9657 features &= ~NETIF_F_GRO_HW;
9661 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9662 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9663 features &= ~NETIF_F_LRO;
9666 if (features & NETIF_F_HW_TLS_TX) {
9667 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9668 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9669 bool hw_csum = features & NETIF_F_HW_CSUM;
9671 if (!ip_csum && !hw_csum) {
9672 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9673 features &= ~NETIF_F_HW_TLS_TX;
9677 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9678 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9679 features &= ~NETIF_F_HW_TLS_RX;
9685 int __netdev_update_features(struct net_device *dev)
9687 struct net_device *upper, *lower;
9688 netdev_features_t features;
9689 struct list_head *iter;
9694 features = netdev_get_wanted_features(dev);
9696 if (dev->netdev_ops->ndo_fix_features)
9697 features = dev->netdev_ops->ndo_fix_features(dev, features);
9699 /* driver might be less strict about feature dependencies */
9700 features = netdev_fix_features(dev, features);
9702 /* some features can't be enabled if they're off on an upper device */
9703 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9704 features = netdev_sync_upper_features(dev, upper, features);
9706 if (dev->features == features)
9709 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9710 &dev->features, &features);
9712 if (dev->netdev_ops->ndo_set_features)
9713 err = dev->netdev_ops->ndo_set_features(dev, features);
9717 if (unlikely(err < 0)) {
9719 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9720 err, &features, &dev->features);
9721 /* return non-0 since some features might have changed and
9722 * it's better to fire a spurious notification than miss it
9728 /* some features must be disabled on lower devices when disabled
9729 * on an upper device (think: bonding master or bridge)
9731 netdev_for_each_lower_dev(dev, lower, iter)
9732 netdev_sync_lower_features(dev, lower, features);
9735 netdev_features_t diff = features ^ dev->features;
9737 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9738 /* udp_tunnel_{get,drop}_rx_info both need
9739 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9740 * device, or they won't do anything.
9741 * Thus we need to update dev->features
9742 * *before* calling udp_tunnel_get_rx_info,
9743 * but *after* calling udp_tunnel_drop_rx_info.
9745 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9746 dev->features = features;
9747 udp_tunnel_get_rx_info(dev);
9749 udp_tunnel_drop_rx_info(dev);
9753 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9754 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9755 dev->features = features;
9756 err |= vlan_get_rx_ctag_filter_info(dev);
9758 vlan_drop_rx_ctag_filter_info(dev);
9762 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9763 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9764 dev->features = features;
9765 err |= vlan_get_rx_stag_filter_info(dev);
9767 vlan_drop_rx_stag_filter_info(dev);
9771 dev->features = features;
9774 return err < 0 ? 0 : 1;
9778 * netdev_update_features - recalculate device features
9779 * @dev: the device to check
9781 * Recalculate dev->features set and send notifications if it
9782 * has changed. Should be called after driver or hardware dependent
9783 * conditions might have changed that influence the features.
9785 void netdev_update_features(struct net_device *dev)
9787 if (__netdev_update_features(dev))
9788 netdev_features_change(dev);
9790 EXPORT_SYMBOL(netdev_update_features);
9793 * netdev_change_features - recalculate device features
9794 * @dev: the device to check
9796 * Recalculate dev->features set and send notifications even
9797 * if they have not changed. Should be called instead of
9798 * netdev_update_features() if also dev->vlan_features might
9799 * have changed to allow the changes to be propagated to stacked
9802 void netdev_change_features(struct net_device *dev)
9804 __netdev_update_features(dev);
9805 netdev_features_change(dev);
9807 EXPORT_SYMBOL(netdev_change_features);
9810 * netif_stacked_transfer_operstate - transfer operstate
9811 * @rootdev: the root or lower level device to transfer state from
9812 * @dev: the device to transfer operstate to
9814 * Transfer operational state from root to device. This is normally
9815 * called when a stacking relationship exists between the root
9816 * device and the device(a leaf device).
9818 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9819 struct net_device *dev)
9821 if (rootdev->operstate == IF_OPER_DORMANT)
9822 netif_dormant_on(dev);
9824 netif_dormant_off(dev);
9826 if (rootdev->operstate == IF_OPER_TESTING)
9827 netif_testing_on(dev);
9829 netif_testing_off(dev);
9831 if (netif_carrier_ok(rootdev))
9832 netif_carrier_on(dev);
9834 netif_carrier_off(dev);
9836 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9838 static int netif_alloc_rx_queues(struct net_device *dev)
9840 unsigned int i, count = dev->num_rx_queues;
9841 struct netdev_rx_queue *rx;
9842 size_t sz = count * sizeof(*rx);
9847 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9853 for (i = 0; i < count; i++) {
9856 /* XDP RX-queue setup */
9857 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9864 /* Rollback successful reg's and free other resources */
9866 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9872 static void netif_free_rx_queues(struct net_device *dev)
9874 unsigned int i, count = dev->num_rx_queues;
9876 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9880 for (i = 0; i < count; i++)
9881 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9886 static void netdev_init_one_queue(struct net_device *dev,
9887 struct netdev_queue *queue, void *_unused)
9889 /* Initialize queue lock */
9890 spin_lock_init(&queue->_xmit_lock);
9891 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9892 queue->xmit_lock_owner = -1;
9893 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9896 dql_init(&queue->dql, HZ);
9900 static void netif_free_tx_queues(struct net_device *dev)
9905 static int netif_alloc_netdev_queues(struct net_device *dev)
9907 unsigned int count = dev->num_tx_queues;
9908 struct netdev_queue *tx;
9909 size_t sz = count * sizeof(*tx);
9911 if (count < 1 || count > 0xffff)
9914 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9920 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9921 spin_lock_init(&dev->tx_global_lock);
9926 void netif_tx_stop_all_queues(struct net_device *dev)
9930 for (i = 0; i < dev->num_tx_queues; i++) {
9931 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9933 netif_tx_stop_queue(txq);
9936 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9939 * register_netdevice() - register a network device
9940 * @dev: device to register
9942 * Take a prepared network device structure and make it externally accessible.
9943 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
9944 * Callers must hold the rtnl lock - you may want register_netdev()
9947 int register_netdevice(struct net_device *dev)
9950 struct net *net = dev_net(dev);
9952 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9953 NETDEV_FEATURE_COUNT);
9954 BUG_ON(dev_boot_phase);
9959 /* When net_device's are persistent, this will be fatal. */
9960 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9963 ret = ethtool_check_ops(dev->ethtool_ops);
9967 spin_lock_init(&dev->addr_list_lock);
9968 netdev_set_addr_lockdep_class(dev);
9970 ret = dev_get_valid_name(net, dev, dev->name);
9975 dev->name_node = netdev_name_node_head_alloc(dev);
9976 if (!dev->name_node)
9979 /* Init, if this function is available */
9980 if (dev->netdev_ops->ndo_init) {
9981 ret = dev->netdev_ops->ndo_init(dev);
9989 if (((dev->hw_features | dev->features) &
9990 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9991 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9992 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9993 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10000 dev->ifindex = dev_new_index(net);
10001 else if (__dev_get_by_index(net, dev->ifindex))
10004 /* Transfer changeable features to wanted_features and enable
10005 * software offloads (GSO and GRO).
10007 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10008 dev->features |= NETIF_F_SOFT_FEATURES;
10010 if (dev->udp_tunnel_nic_info) {
10011 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10012 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10015 dev->wanted_features = dev->features & dev->hw_features;
10017 if (!(dev->flags & IFF_LOOPBACK))
10018 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10020 /* If IPv4 TCP segmentation offload is supported we should also
10021 * allow the device to enable segmenting the frame with the option
10022 * of ignoring a static IP ID value. This doesn't enable the
10023 * feature itself but allows the user to enable it later.
10025 if (dev->hw_features & NETIF_F_TSO)
10026 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10027 if (dev->vlan_features & NETIF_F_TSO)
10028 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10029 if (dev->mpls_features & NETIF_F_TSO)
10030 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10031 if (dev->hw_enc_features & NETIF_F_TSO)
10032 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10034 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10036 dev->vlan_features |= NETIF_F_HIGHDMA;
10038 /* Make NETIF_F_SG inheritable to tunnel devices.
10040 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10042 /* Make NETIF_F_SG inheritable to MPLS.
10044 dev->mpls_features |= NETIF_F_SG;
10046 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10047 ret = notifier_to_errno(ret);
10051 ret = netdev_register_kobject(dev);
10052 write_lock(&dev_base_lock);
10053 dev->reg_state = ret ? NETREG_UNREGISTERED : NETREG_REGISTERED;
10054 write_unlock(&dev_base_lock);
10056 goto err_uninit_notify;
10058 __netdev_update_features(dev);
10061 * Default initial state at registry is that the
10062 * device is present.
10065 set_bit(__LINK_STATE_PRESENT, &dev->state);
10067 linkwatch_init_dev(dev);
10069 dev_init_scheduler(dev);
10071 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10072 list_netdevice(dev);
10074 add_device_randomness(dev->dev_addr, dev->addr_len);
10076 /* If the device has permanent device address, driver should
10077 * set dev_addr and also addr_assign_type should be set to
10078 * NET_ADDR_PERM (default value).
10080 if (dev->addr_assign_type == NET_ADDR_PERM)
10081 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10083 /* Notify protocols, that a new device appeared. */
10084 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10085 ret = notifier_to_errno(ret);
10087 /* Expect explicit free_netdev() on failure */
10088 dev->needs_free_netdev = false;
10089 unregister_netdevice_queue(dev, NULL);
10093 * Prevent userspace races by waiting until the network
10094 * device is fully setup before sending notifications.
10096 if (!dev->rtnl_link_ops ||
10097 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10098 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10104 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10106 if (dev->netdev_ops->ndo_uninit)
10107 dev->netdev_ops->ndo_uninit(dev);
10108 if (dev->priv_destructor)
10109 dev->priv_destructor(dev);
10111 netdev_name_node_free(dev->name_node);
10114 EXPORT_SYMBOL(register_netdevice);
10117 * init_dummy_netdev - init a dummy network device for NAPI
10118 * @dev: device to init
10120 * This takes a network device structure and initialize the minimum
10121 * amount of fields so it can be used to schedule NAPI polls without
10122 * registering a full blown interface. This is to be used by drivers
10123 * that need to tie several hardware interfaces to a single NAPI
10124 * poll scheduler due to HW limitations.
10126 int init_dummy_netdev(struct net_device *dev)
10128 /* Clear everything. Note we don't initialize spinlocks
10129 * are they aren't supposed to be taken by any of the
10130 * NAPI code and this dummy netdev is supposed to be
10131 * only ever used for NAPI polls
10133 memset(dev, 0, sizeof(struct net_device));
10135 /* make sure we BUG if trying to hit standard
10136 * register/unregister code path
10138 dev->reg_state = NETREG_DUMMY;
10140 /* NAPI wants this */
10141 INIT_LIST_HEAD(&dev->napi_list);
10143 /* a dummy interface is started by default */
10144 set_bit(__LINK_STATE_PRESENT, &dev->state);
10145 set_bit(__LINK_STATE_START, &dev->state);
10147 /* napi_busy_loop stats accounting wants this */
10148 dev_net_set(dev, &init_net);
10150 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10151 * because users of this 'device' dont need to change
10157 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10161 * register_netdev - register a network device
10162 * @dev: device to register
10164 * Take a completed network device structure and add it to the kernel
10165 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10166 * chain. 0 is returned on success. A negative errno code is returned
10167 * on a failure to set up the device, or if the name is a duplicate.
10169 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10170 * and expands the device name if you passed a format string to
10173 int register_netdev(struct net_device *dev)
10177 if (rtnl_lock_killable())
10179 err = register_netdevice(dev);
10183 EXPORT_SYMBOL(register_netdev);
10185 int netdev_refcnt_read(const struct net_device *dev)
10187 #ifdef CONFIG_PCPU_DEV_REFCNT
10190 for_each_possible_cpu(i)
10191 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10194 return refcount_read(&dev->dev_refcnt);
10197 EXPORT_SYMBOL(netdev_refcnt_read);
10199 int netdev_unregister_timeout_secs __read_mostly = 10;
10201 #define WAIT_REFS_MIN_MSECS 1
10202 #define WAIT_REFS_MAX_MSECS 250
10204 * netdev_wait_allrefs_any - wait until all references are gone.
10205 * @list: list of net_devices to wait on
10207 * This is called when unregistering network devices.
10209 * Any protocol or device that holds a reference should register
10210 * for netdevice notification, and cleanup and put back the
10211 * reference if they receive an UNREGISTER event.
10212 * We can get stuck here if buggy protocols don't correctly
10215 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10217 unsigned long rebroadcast_time, warning_time;
10218 struct net_device *dev;
10221 rebroadcast_time = warning_time = jiffies;
10223 list_for_each_entry(dev, list, todo_list)
10224 if (netdev_refcnt_read(dev) == 1)
10228 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10231 /* Rebroadcast unregister notification */
10232 list_for_each_entry(dev, list, todo_list)
10233 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10239 list_for_each_entry(dev, list, todo_list)
10240 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10242 /* We must not have linkwatch events
10243 * pending on unregister. If this
10244 * happens, we simply run the queue
10245 * unscheduled, resulting in a noop
10248 linkwatch_run_queue();
10254 rebroadcast_time = jiffies;
10259 wait = WAIT_REFS_MIN_MSECS;
10262 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10265 list_for_each_entry(dev, list, todo_list)
10266 if (netdev_refcnt_read(dev) == 1)
10269 if (time_after(jiffies, warning_time +
10270 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10271 list_for_each_entry(dev, list, todo_list) {
10272 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10273 dev->name, netdev_refcnt_read(dev));
10274 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10277 warning_time = jiffies;
10282 /* The sequence is:
10286 * register_netdevice(x1);
10287 * register_netdevice(x2);
10289 * unregister_netdevice(y1);
10290 * unregister_netdevice(y2);
10296 * We are invoked by rtnl_unlock().
10297 * This allows us to deal with problems:
10298 * 1) We can delete sysfs objects which invoke hotplug
10299 * without deadlocking with linkwatch via keventd.
10300 * 2) Since we run with the RTNL semaphore not held, we can sleep
10301 * safely in order to wait for the netdev refcnt to drop to zero.
10303 * We must not return until all unregister events added during
10304 * the interval the lock was held have been completed.
10306 void netdev_run_todo(void)
10308 struct net_device *dev, *tmp;
10309 struct list_head list;
10310 #ifdef CONFIG_LOCKDEP
10311 struct list_head unlink_list;
10313 list_replace_init(&net_unlink_list, &unlink_list);
10315 while (!list_empty(&unlink_list)) {
10316 struct net_device *dev = list_first_entry(&unlink_list,
10319 list_del_init(&dev->unlink_list);
10320 dev->nested_level = dev->lower_level - 1;
10324 /* Snapshot list, allow later requests */
10325 list_replace_init(&net_todo_list, &list);
10329 /* Wait for rcu callbacks to finish before next phase */
10330 if (!list_empty(&list))
10333 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10334 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10335 netdev_WARN(dev, "run_todo but not unregistering\n");
10336 list_del(&dev->todo_list);
10340 write_lock(&dev_base_lock);
10341 dev->reg_state = NETREG_UNREGISTERED;
10342 write_unlock(&dev_base_lock);
10343 linkwatch_forget_dev(dev);
10346 while (!list_empty(&list)) {
10347 dev = netdev_wait_allrefs_any(&list);
10348 list_del(&dev->todo_list);
10351 BUG_ON(netdev_refcnt_read(dev) != 1);
10352 BUG_ON(!list_empty(&dev->ptype_all));
10353 BUG_ON(!list_empty(&dev->ptype_specific));
10354 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10355 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10357 if (dev->priv_destructor)
10358 dev->priv_destructor(dev);
10359 if (dev->needs_free_netdev)
10362 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count))
10363 wake_up(&netdev_unregistering_wq);
10365 /* Free network device */
10366 kobject_put(&dev->dev.kobj);
10370 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10371 * all the same fields in the same order as net_device_stats, with only
10372 * the type differing, but rtnl_link_stats64 may have additional fields
10373 * at the end for newer counters.
10375 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10376 const struct net_device_stats *netdev_stats)
10378 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10379 const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10380 u64 *dst = (u64 *)stats64;
10382 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10383 for (i = 0; i < n; i++)
10384 dst[i] = (unsigned long)atomic_long_read(&src[i]);
10385 /* zero out counters that only exist in rtnl_link_stats64 */
10386 memset((char *)stats64 + n * sizeof(u64), 0,
10387 sizeof(*stats64) - n * sizeof(u64));
10389 EXPORT_SYMBOL(netdev_stats_to_stats64);
10391 struct net_device_core_stats __percpu *netdev_core_stats_alloc(struct net_device *dev)
10393 struct net_device_core_stats __percpu *p;
10395 p = alloc_percpu_gfp(struct net_device_core_stats,
10396 GFP_ATOMIC | __GFP_NOWARN);
10398 if (p && cmpxchg(&dev->core_stats, NULL, p))
10401 /* This READ_ONCE() pairs with the cmpxchg() above */
10402 return READ_ONCE(dev->core_stats);
10404 EXPORT_SYMBOL(netdev_core_stats_alloc);
10407 * dev_get_stats - get network device statistics
10408 * @dev: device to get statistics from
10409 * @storage: place to store stats
10411 * Get network statistics from device. Return @storage.
10412 * The device driver may provide its own method by setting
10413 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10414 * otherwise the internal statistics structure is used.
10416 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10417 struct rtnl_link_stats64 *storage)
10419 const struct net_device_ops *ops = dev->netdev_ops;
10420 const struct net_device_core_stats __percpu *p;
10422 if (ops->ndo_get_stats64) {
10423 memset(storage, 0, sizeof(*storage));
10424 ops->ndo_get_stats64(dev, storage);
10425 } else if (ops->ndo_get_stats) {
10426 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10428 netdev_stats_to_stats64(storage, &dev->stats);
10431 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10432 p = READ_ONCE(dev->core_stats);
10434 const struct net_device_core_stats *core_stats;
10437 for_each_possible_cpu(i) {
10438 core_stats = per_cpu_ptr(p, i);
10439 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10440 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10441 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10442 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10447 EXPORT_SYMBOL(dev_get_stats);
10450 * dev_fetch_sw_netstats - get per-cpu network device statistics
10451 * @s: place to store stats
10452 * @netstats: per-cpu network stats to read from
10454 * Read per-cpu network statistics and populate the related fields in @s.
10456 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10457 const struct pcpu_sw_netstats __percpu *netstats)
10461 for_each_possible_cpu(cpu) {
10462 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10463 const struct pcpu_sw_netstats *stats;
10464 unsigned int start;
10466 stats = per_cpu_ptr(netstats, cpu);
10468 start = u64_stats_fetch_begin(&stats->syncp);
10469 rx_packets = u64_stats_read(&stats->rx_packets);
10470 rx_bytes = u64_stats_read(&stats->rx_bytes);
10471 tx_packets = u64_stats_read(&stats->tx_packets);
10472 tx_bytes = u64_stats_read(&stats->tx_bytes);
10473 } while (u64_stats_fetch_retry(&stats->syncp, start));
10475 s->rx_packets += rx_packets;
10476 s->rx_bytes += rx_bytes;
10477 s->tx_packets += tx_packets;
10478 s->tx_bytes += tx_bytes;
10481 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10484 * dev_get_tstats64 - ndo_get_stats64 implementation
10485 * @dev: device to get statistics from
10486 * @s: place to store stats
10488 * Populate @s from dev->stats and dev->tstats. Can be used as
10489 * ndo_get_stats64() callback.
10491 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10493 netdev_stats_to_stats64(s, &dev->stats);
10494 dev_fetch_sw_netstats(s, dev->tstats);
10496 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10498 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10500 struct netdev_queue *queue = dev_ingress_queue(dev);
10502 #ifdef CONFIG_NET_CLS_ACT
10505 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10508 netdev_init_one_queue(dev, queue, NULL);
10509 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10510 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
10511 rcu_assign_pointer(dev->ingress_queue, queue);
10516 static const struct ethtool_ops default_ethtool_ops;
10518 void netdev_set_default_ethtool_ops(struct net_device *dev,
10519 const struct ethtool_ops *ops)
10521 if (dev->ethtool_ops == &default_ethtool_ops)
10522 dev->ethtool_ops = ops;
10524 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10527 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
10528 * @dev: netdev to enable the IRQ coalescing on
10530 * Sets a conservative default for SW IRQ coalescing. Users can use
10531 * sysfs attributes to override the default values.
10533 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
10535 WARN_ON(dev->reg_state == NETREG_REGISTERED);
10537 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
10538 dev->gro_flush_timeout = 20000;
10539 dev->napi_defer_hard_irqs = 1;
10542 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
10544 void netdev_freemem(struct net_device *dev)
10546 char *addr = (char *)dev - dev->padded;
10552 * alloc_netdev_mqs - allocate network device
10553 * @sizeof_priv: size of private data to allocate space for
10554 * @name: device name format string
10555 * @name_assign_type: origin of device name
10556 * @setup: callback to initialize device
10557 * @txqs: the number of TX subqueues to allocate
10558 * @rxqs: the number of RX subqueues to allocate
10560 * Allocates a struct net_device with private data area for driver use
10561 * and performs basic initialization. Also allocates subqueue structs
10562 * for each queue on the device.
10564 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10565 unsigned char name_assign_type,
10566 void (*setup)(struct net_device *),
10567 unsigned int txqs, unsigned int rxqs)
10569 struct net_device *dev;
10570 unsigned int alloc_size;
10571 struct net_device *p;
10573 BUG_ON(strlen(name) >= sizeof(dev->name));
10576 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10581 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10585 alloc_size = sizeof(struct net_device);
10587 /* ensure 32-byte alignment of private area */
10588 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10589 alloc_size += sizeof_priv;
10591 /* ensure 32-byte alignment of whole construct */
10592 alloc_size += NETDEV_ALIGN - 1;
10594 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10598 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10599 dev->padded = (char *)dev - (char *)p;
10601 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
10602 #ifdef CONFIG_PCPU_DEV_REFCNT
10603 dev->pcpu_refcnt = alloc_percpu(int);
10604 if (!dev->pcpu_refcnt)
10608 refcount_set(&dev->dev_refcnt, 1);
10611 if (dev_addr_init(dev))
10617 dev_net_set(dev, &init_net);
10619 dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
10620 dev->gso_max_segs = GSO_MAX_SEGS;
10621 dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
10622 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
10623 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
10624 dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
10625 dev->tso_max_segs = TSO_MAX_SEGS;
10626 dev->upper_level = 1;
10627 dev->lower_level = 1;
10628 #ifdef CONFIG_LOCKDEP
10629 dev->nested_level = 0;
10630 INIT_LIST_HEAD(&dev->unlink_list);
10633 INIT_LIST_HEAD(&dev->napi_list);
10634 INIT_LIST_HEAD(&dev->unreg_list);
10635 INIT_LIST_HEAD(&dev->close_list);
10636 INIT_LIST_HEAD(&dev->link_watch_list);
10637 INIT_LIST_HEAD(&dev->adj_list.upper);
10638 INIT_LIST_HEAD(&dev->adj_list.lower);
10639 INIT_LIST_HEAD(&dev->ptype_all);
10640 INIT_LIST_HEAD(&dev->ptype_specific);
10641 INIT_LIST_HEAD(&dev->net_notifier_list);
10642 #ifdef CONFIG_NET_SCHED
10643 hash_init(dev->qdisc_hash);
10645 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10648 if (!dev->tx_queue_len) {
10649 dev->priv_flags |= IFF_NO_QUEUE;
10650 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10653 dev->num_tx_queues = txqs;
10654 dev->real_num_tx_queues = txqs;
10655 if (netif_alloc_netdev_queues(dev))
10658 dev->num_rx_queues = rxqs;
10659 dev->real_num_rx_queues = rxqs;
10660 if (netif_alloc_rx_queues(dev))
10663 strcpy(dev->name, name);
10664 dev->name_assign_type = name_assign_type;
10665 dev->group = INIT_NETDEV_GROUP;
10666 if (!dev->ethtool_ops)
10667 dev->ethtool_ops = &default_ethtool_ops;
10669 nf_hook_netdev_init(dev);
10678 #ifdef CONFIG_PCPU_DEV_REFCNT
10679 free_percpu(dev->pcpu_refcnt);
10682 netdev_freemem(dev);
10685 EXPORT_SYMBOL(alloc_netdev_mqs);
10688 * free_netdev - free network device
10691 * This function does the last stage of destroying an allocated device
10692 * interface. The reference to the device object is released. If this
10693 * is the last reference then it will be freed.Must be called in process
10696 void free_netdev(struct net_device *dev)
10698 struct napi_struct *p, *n;
10702 /* When called immediately after register_netdevice() failed the unwind
10703 * handling may still be dismantling the device. Handle that case by
10704 * deferring the free.
10706 if (dev->reg_state == NETREG_UNREGISTERING) {
10708 dev->needs_free_netdev = true;
10712 netif_free_tx_queues(dev);
10713 netif_free_rx_queues(dev);
10715 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10717 /* Flush device addresses */
10718 dev_addr_flush(dev);
10720 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10723 ref_tracker_dir_exit(&dev->refcnt_tracker);
10724 #ifdef CONFIG_PCPU_DEV_REFCNT
10725 free_percpu(dev->pcpu_refcnt);
10726 dev->pcpu_refcnt = NULL;
10728 free_percpu(dev->core_stats);
10729 dev->core_stats = NULL;
10730 free_percpu(dev->xdp_bulkq);
10731 dev->xdp_bulkq = NULL;
10733 /* Compatibility with error handling in drivers */
10734 if (dev->reg_state == NETREG_UNINITIALIZED) {
10735 netdev_freemem(dev);
10739 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10740 dev->reg_state = NETREG_RELEASED;
10742 /* will free via device release */
10743 put_device(&dev->dev);
10745 EXPORT_SYMBOL(free_netdev);
10748 * synchronize_net - Synchronize with packet receive processing
10750 * Wait for packets currently being received to be done.
10751 * Does not block later packets from starting.
10753 void synchronize_net(void)
10756 if (rtnl_is_locked())
10757 synchronize_rcu_expedited();
10761 EXPORT_SYMBOL(synchronize_net);
10764 * unregister_netdevice_queue - remove device from the kernel
10768 * This function shuts down a device interface and removes it
10769 * from the kernel tables.
10770 * If head not NULL, device is queued to be unregistered later.
10772 * Callers must hold the rtnl semaphore. You may want
10773 * unregister_netdev() instead of this.
10776 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10781 list_move_tail(&dev->unreg_list, head);
10785 list_add(&dev->unreg_list, &single);
10786 unregister_netdevice_many(&single);
10789 EXPORT_SYMBOL(unregister_netdevice_queue);
10791 void unregister_netdevice_many_notify(struct list_head *head,
10792 u32 portid, const struct nlmsghdr *nlh)
10794 struct net_device *dev, *tmp;
10795 LIST_HEAD(close_head);
10797 BUG_ON(dev_boot_phase);
10800 if (list_empty(head))
10803 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10804 /* Some devices call without registering
10805 * for initialization unwind. Remove those
10806 * devices and proceed with the remaining.
10808 if (dev->reg_state == NETREG_UNINITIALIZED) {
10809 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10813 list_del(&dev->unreg_list);
10816 dev->dismantle = true;
10817 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10820 /* If device is running, close it first. */
10821 list_for_each_entry(dev, head, unreg_list)
10822 list_add_tail(&dev->close_list, &close_head);
10823 dev_close_many(&close_head, true);
10825 list_for_each_entry(dev, head, unreg_list) {
10826 /* And unlink it from device chain. */
10827 write_lock(&dev_base_lock);
10828 unlist_netdevice(dev, false);
10829 dev->reg_state = NETREG_UNREGISTERING;
10830 write_unlock(&dev_base_lock);
10832 flush_all_backlogs();
10836 list_for_each_entry(dev, head, unreg_list) {
10837 struct sk_buff *skb = NULL;
10839 /* Shutdown queueing discipline. */
10842 dev_xdp_uninstall(dev);
10843 bpf_dev_bound_netdev_unregister(dev);
10845 netdev_offload_xstats_disable_all(dev);
10847 /* Notify protocols, that we are about to destroy
10848 * this device. They should clean all the things.
10850 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10852 if (!dev->rtnl_link_ops ||
10853 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10854 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10855 GFP_KERNEL, NULL, 0,
10859 * Flush the unicast and multicast chains
10864 netdev_name_node_alt_flush(dev);
10865 netdev_name_node_free(dev->name_node);
10867 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10869 if (dev->netdev_ops->ndo_uninit)
10870 dev->netdev_ops->ndo_uninit(dev);
10873 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
10875 /* Notifier chain MUST detach us all upper devices. */
10876 WARN_ON(netdev_has_any_upper_dev(dev));
10877 WARN_ON(netdev_has_any_lower_dev(dev));
10879 /* Remove entries from kobject tree */
10880 netdev_unregister_kobject(dev);
10882 /* Remove XPS queueing entries */
10883 netif_reset_xps_queues_gt(dev, 0);
10889 list_for_each_entry(dev, head, unreg_list) {
10890 netdev_put(dev, &dev->dev_registered_tracker);
10898 * unregister_netdevice_many - unregister many devices
10899 * @head: list of devices
10901 * Note: As most callers use a stack allocated list_head,
10902 * we force a list_del() to make sure stack wont be corrupted later.
10904 void unregister_netdevice_many(struct list_head *head)
10906 unregister_netdevice_many_notify(head, 0, NULL);
10908 EXPORT_SYMBOL(unregister_netdevice_many);
10911 * unregister_netdev - remove device from the kernel
10914 * This function shuts down a device interface and removes it
10915 * from the kernel tables.
10917 * This is just a wrapper for unregister_netdevice that takes
10918 * the rtnl semaphore. In general you want to use this and not
10919 * unregister_netdevice.
10921 void unregister_netdev(struct net_device *dev)
10924 unregister_netdevice(dev);
10927 EXPORT_SYMBOL(unregister_netdev);
10930 * __dev_change_net_namespace - move device to different nethost namespace
10932 * @net: network namespace
10933 * @pat: If not NULL name pattern to try if the current device name
10934 * is already taken in the destination network namespace.
10935 * @new_ifindex: If not zero, specifies device index in the target
10938 * This function shuts down a device interface and moves it
10939 * to a new network namespace. On success 0 is returned, on
10940 * a failure a netagive errno code is returned.
10942 * Callers must hold the rtnl semaphore.
10945 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
10946 const char *pat, int new_ifindex)
10948 struct net *net_old = dev_net(dev);
10953 /* Don't allow namespace local devices to be moved. */
10955 if (dev->features & NETIF_F_NETNS_LOCAL)
10958 /* Ensure the device has been registrered */
10959 if (dev->reg_state != NETREG_REGISTERED)
10962 /* Get out if there is nothing todo */
10964 if (net_eq(net_old, net))
10967 /* Pick the destination device name, and ensure
10968 * we can use it in the destination network namespace.
10971 if (netdev_name_in_use(net, dev->name)) {
10972 /* We get here if we can't use the current device name */
10975 err = dev_get_valid_name(net, dev, pat);
10980 /* Check that new_ifindex isn't used yet. */
10982 if (new_ifindex && __dev_get_by_index(net, new_ifindex))
10986 * And now a mini version of register_netdevice unregister_netdevice.
10989 /* If device is running close it first. */
10992 /* And unlink it from device chain */
10993 unlist_netdevice(dev, true);
10997 /* Shutdown queueing discipline. */
11000 /* Notify protocols, that we are about to destroy
11001 * this device. They should clean all the things.
11003 * Note that dev->reg_state stays at NETREG_REGISTERED.
11004 * This is wanted because this way 8021q and macvlan know
11005 * the device is just moving and can keep their slaves up.
11007 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11010 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11011 /* If there is an ifindex conflict assign a new one */
11012 if (!new_ifindex) {
11013 if (__dev_get_by_index(net, dev->ifindex))
11014 new_ifindex = dev_new_index(net);
11016 new_ifindex = dev->ifindex;
11019 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11023 * Flush the unicast and multicast chains
11028 /* Send a netdev-removed uevent to the old namespace */
11029 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11030 netdev_adjacent_del_links(dev);
11032 /* Move per-net netdevice notifiers that are following the netdevice */
11033 move_netdevice_notifiers_dev_net(dev, net);
11035 /* Actually switch the network namespace */
11036 dev_net_set(dev, net);
11037 dev->ifindex = new_ifindex;
11039 /* Send a netdev-add uevent to the new namespace */
11040 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11041 netdev_adjacent_add_links(dev);
11043 /* Fixup kobjects */
11044 err = device_rename(&dev->dev, dev->name);
11047 /* Adapt owner in case owning user namespace of target network
11048 * namespace is different from the original one.
11050 err = netdev_change_owner(dev, net_old, net);
11053 /* Add the device back in the hashes */
11054 list_netdevice(dev);
11056 /* Notify protocols, that a new device appeared. */
11057 call_netdevice_notifiers(NETDEV_REGISTER, dev);
11060 * Prevent userspace races by waiting until the network
11061 * device is fully setup before sending notifications.
11063 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11070 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11072 static int dev_cpu_dead(unsigned int oldcpu)
11074 struct sk_buff **list_skb;
11075 struct sk_buff *skb;
11077 struct softnet_data *sd, *oldsd, *remsd = NULL;
11079 local_irq_disable();
11080 cpu = smp_processor_id();
11081 sd = &per_cpu(softnet_data, cpu);
11082 oldsd = &per_cpu(softnet_data, oldcpu);
11084 /* Find end of our completion_queue. */
11085 list_skb = &sd->completion_queue;
11087 list_skb = &(*list_skb)->next;
11088 /* Append completion queue from offline CPU. */
11089 *list_skb = oldsd->completion_queue;
11090 oldsd->completion_queue = NULL;
11092 /* Append output queue from offline CPU. */
11093 if (oldsd->output_queue) {
11094 *sd->output_queue_tailp = oldsd->output_queue;
11095 sd->output_queue_tailp = oldsd->output_queue_tailp;
11096 oldsd->output_queue = NULL;
11097 oldsd->output_queue_tailp = &oldsd->output_queue;
11099 /* Append NAPI poll list from offline CPU, with one exception :
11100 * process_backlog() must be called by cpu owning percpu backlog.
11101 * We properly handle process_queue & input_pkt_queue later.
11103 while (!list_empty(&oldsd->poll_list)) {
11104 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11105 struct napi_struct,
11108 list_del_init(&napi->poll_list);
11109 if (napi->poll == process_backlog)
11112 ____napi_schedule(sd, napi);
11115 raise_softirq_irqoff(NET_TX_SOFTIRQ);
11116 local_irq_enable();
11119 remsd = oldsd->rps_ipi_list;
11120 oldsd->rps_ipi_list = NULL;
11122 /* send out pending IPI's on offline CPU */
11123 net_rps_send_ipi(remsd);
11125 /* Process offline CPU's input_pkt_queue */
11126 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11128 input_queue_head_incr(oldsd);
11130 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11132 input_queue_head_incr(oldsd);
11139 * netdev_increment_features - increment feature set by one
11140 * @all: current feature set
11141 * @one: new feature set
11142 * @mask: mask feature set
11144 * Computes a new feature set after adding a device with feature set
11145 * @one to the master device with current feature set @all. Will not
11146 * enable anything that is off in @mask. Returns the new feature set.
11148 netdev_features_t netdev_increment_features(netdev_features_t all,
11149 netdev_features_t one, netdev_features_t mask)
11151 if (mask & NETIF_F_HW_CSUM)
11152 mask |= NETIF_F_CSUM_MASK;
11153 mask |= NETIF_F_VLAN_CHALLENGED;
11155 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11156 all &= one | ~NETIF_F_ALL_FOR_ALL;
11158 /* If one device supports hw checksumming, set for all. */
11159 if (all & NETIF_F_HW_CSUM)
11160 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11164 EXPORT_SYMBOL(netdev_increment_features);
11166 static struct hlist_head * __net_init netdev_create_hash(void)
11169 struct hlist_head *hash;
11171 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11173 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11174 INIT_HLIST_HEAD(&hash[i]);
11179 /* Initialize per network namespace state */
11180 static int __net_init netdev_init(struct net *net)
11182 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11183 8 * sizeof_field(struct napi_struct, gro_bitmask));
11185 INIT_LIST_HEAD(&net->dev_base_head);
11187 net->dev_name_head = netdev_create_hash();
11188 if (net->dev_name_head == NULL)
11191 net->dev_index_head = netdev_create_hash();
11192 if (net->dev_index_head == NULL)
11195 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11200 kfree(net->dev_name_head);
11206 * netdev_drivername - network driver for the device
11207 * @dev: network device
11209 * Determine network driver for device.
11211 const char *netdev_drivername(const struct net_device *dev)
11213 const struct device_driver *driver;
11214 const struct device *parent;
11215 const char *empty = "";
11217 parent = dev->dev.parent;
11221 driver = parent->driver;
11222 if (driver && driver->name)
11223 return driver->name;
11227 static void __netdev_printk(const char *level, const struct net_device *dev,
11228 struct va_format *vaf)
11230 if (dev && dev->dev.parent) {
11231 dev_printk_emit(level[1] - '0',
11234 dev_driver_string(dev->dev.parent),
11235 dev_name(dev->dev.parent),
11236 netdev_name(dev), netdev_reg_state(dev),
11239 printk("%s%s%s: %pV",
11240 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11242 printk("%s(NULL net_device): %pV", level, vaf);
11246 void netdev_printk(const char *level, const struct net_device *dev,
11247 const char *format, ...)
11249 struct va_format vaf;
11252 va_start(args, format);
11257 __netdev_printk(level, dev, &vaf);
11261 EXPORT_SYMBOL(netdev_printk);
11263 #define define_netdev_printk_level(func, level) \
11264 void func(const struct net_device *dev, const char *fmt, ...) \
11266 struct va_format vaf; \
11269 va_start(args, fmt); \
11274 __netdev_printk(level, dev, &vaf); \
11278 EXPORT_SYMBOL(func);
11280 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11281 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11282 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11283 define_netdev_printk_level(netdev_err, KERN_ERR);
11284 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11285 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11286 define_netdev_printk_level(netdev_info, KERN_INFO);
11288 static void __net_exit netdev_exit(struct net *net)
11290 kfree(net->dev_name_head);
11291 kfree(net->dev_index_head);
11292 if (net != &init_net)
11293 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11296 static struct pernet_operations __net_initdata netdev_net_ops = {
11297 .init = netdev_init,
11298 .exit = netdev_exit,
11301 static void __net_exit default_device_exit_net(struct net *net)
11303 struct net_device *dev, *aux;
11305 * Push all migratable network devices back to the
11306 * initial network namespace
11309 for_each_netdev_safe(net, dev, aux) {
11311 char fb_name[IFNAMSIZ];
11313 /* Ignore unmoveable devices (i.e. loopback) */
11314 if (dev->features & NETIF_F_NETNS_LOCAL)
11317 /* Leave virtual devices for the generic cleanup */
11318 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11321 /* Push remaining network devices to init_net */
11322 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11323 if (netdev_name_in_use(&init_net, fb_name))
11324 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11325 err = dev_change_net_namespace(dev, &init_net, fb_name);
11327 pr_emerg("%s: failed to move %s to init_net: %d\n",
11328 __func__, dev->name, err);
11334 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11336 /* At exit all network devices most be removed from a network
11337 * namespace. Do this in the reverse order of registration.
11338 * Do this across as many network namespaces as possible to
11339 * improve batching efficiency.
11341 struct net_device *dev;
11343 LIST_HEAD(dev_kill_list);
11346 list_for_each_entry(net, net_list, exit_list) {
11347 default_device_exit_net(net);
11351 list_for_each_entry(net, net_list, exit_list) {
11352 for_each_netdev_reverse(net, dev) {
11353 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11354 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11356 unregister_netdevice_queue(dev, &dev_kill_list);
11359 unregister_netdevice_many(&dev_kill_list);
11363 static struct pernet_operations __net_initdata default_device_ops = {
11364 .exit_batch = default_device_exit_batch,
11368 * Initialize the DEV module. At boot time this walks the device list and
11369 * unhooks any devices that fail to initialise (normally hardware not
11370 * present) and leaves us with a valid list of present and active devices.
11375 * This is called single threaded during boot, so no need
11376 * to take the rtnl semaphore.
11378 static int __init net_dev_init(void)
11380 int i, rc = -ENOMEM;
11382 BUG_ON(!dev_boot_phase);
11384 if (dev_proc_init())
11387 if (netdev_kobject_init())
11390 INIT_LIST_HEAD(&ptype_all);
11391 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11392 INIT_LIST_HEAD(&ptype_base[i]);
11394 if (register_pernet_subsys(&netdev_net_ops))
11398 * Initialise the packet receive queues.
11401 for_each_possible_cpu(i) {
11402 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11403 struct softnet_data *sd = &per_cpu(softnet_data, i);
11405 INIT_WORK(flush, flush_backlog);
11407 skb_queue_head_init(&sd->input_pkt_queue);
11408 skb_queue_head_init(&sd->process_queue);
11409 #ifdef CONFIG_XFRM_OFFLOAD
11410 skb_queue_head_init(&sd->xfrm_backlog);
11412 INIT_LIST_HEAD(&sd->poll_list);
11413 sd->output_queue_tailp = &sd->output_queue;
11415 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11418 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
11419 spin_lock_init(&sd->defer_lock);
11421 init_gro_hash(&sd->backlog);
11422 sd->backlog.poll = process_backlog;
11423 sd->backlog.weight = weight_p;
11426 dev_boot_phase = 0;
11428 /* The loopback device is special if any other network devices
11429 * is present in a network namespace the loopback device must
11430 * be present. Since we now dynamically allocate and free the
11431 * loopback device ensure this invariant is maintained by
11432 * keeping the loopback device as the first device on the
11433 * list of network devices. Ensuring the loopback devices
11434 * is the first device that appears and the last network device
11437 if (register_pernet_device(&loopback_net_ops))
11440 if (register_pernet_device(&default_device_ops))
11443 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11444 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11446 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11447 NULL, dev_cpu_dead);
11454 subsys_initcall(net_dev_init);