1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * NET3 Protocol independent device support routines.
5 * Derived from the non IP parts of dev.c 1.0.19
7 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
8 * Mark Evans, <evansmp@uhura.aston.ac.uk>
11 * Florian la Roche <rzsfl@rz.uni-sb.de>
12 * Alan Cox <gw4pts@gw4pts.ampr.org>
13 * David Hinds <dahinds@users.sourceforge.net>
14 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
15 * Adam Sulmicki <adam@cfar.umd.edu>
16 * Pekka Riikonen <priikone@poesidon.pspt.fi>
19 * D.J. Barrow : Fixed bug where dev->refcnt gets set
20 * to 2 if register_netdev gets called
21 * before net_dev_init & also removed a
22 * few lines of code in the process.
23 * Alan Cox : device private ioctl copies fields back.
24 * Alan Cox : Transmit queue code does relevant
25 * stunts to keep the queue safe.
26 * Alan Cox : Fixed double lock.
27 * Alan Cox : Fixed promisc NULL pointer trap
28 * ???????? : Support the full private ioctl range
29 * Alan Cox : Moved ioctl permission check into
31 * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
32 * Alan Cox : 100 backlog just doesn't cut it when
33 * you start doing multicast video 8)
34 * Alan Cox : Rewrote net_bh and list manager.
35 * Alan Cox : Fix ETH_P_ALL echoback lengths.
36 * Alan Cox : Took out transmit every packet pass
37 * Saved a few bytes in the ioctl handler
38 * Alan Cox : Network driver sets packet type before
39 * calling netif_rx. Saves a function
41 * Alan Cox : Hashed net_bh()
42 * Richard Kooijman: Timestamp fixes.
43 * Alan Cox : Wrong field in SIOCGIFDSTADDR
44 * Alan Cox : Device lock protection.
45 * Alan Cox : Fixed nasty side effect of device close
47 * Rudi Cilibrasi : Pass the right thing to
49 * Dave Miller : 32bit quantity for the device lock to
50 * make it work out on a Sparc.
51 * Bjorn Ekwall : Added KERNELD hack.
52 * Alan Cox : Cleaned up the backlog initialise.
53 * Craig Metz : SIOCGIFCONF fix if space for under
55 * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
56 * is no device open function.
57 * Andi Kleen : Fix error reporting for SIOCGIFCONF
58 * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
59 * Cyrus Durgin : Cleaned for KMOD
60 * Adam Sulmicki : Bug Fix : Network Device Unload
61 * A network device unload needs to purge
63 * Paul Rusty Russell : SIOCSIFNAME
64 * Pekka Riikonen : Netdev boot-time settings code
65 * Andrew Morton : Make unregister_netdevice wait
66 * indefinitely on dev->refcnt
67 * J Hadi Salim : - Backlog queue sampling
68 * - netif_rx() feedback
71 #include <linux/uaccess.h>
72 #include <linux/bitops.h>
73 #include <linux/capability.h>
74 #include <linux/cpu.h>
75 #include <linux/types.h>
76 #include <linux/kernel.h>
77 #include <linux/hash.h>
78 #include <linux/slab.h>
79 #include <linux/sched.h>
80 #include <linux/sched/mm.h>
81 #include <linux/mutex.h>
82 #include <linux/rwsem.h>
83 #include <linux/string.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/errno.h>
88 #include <linux/interrupt.h>
89 #include <linux/if_ether.h>
90 #include <linux/netdevice.h>
91 #include <linux/etherdevice.h>
92 #include <linux/ethtool.h>
93 #include <linux/skbuff.h>
94 #include <linux/kthread.h>
95 #include <linux/bpf.h>
96 #include <linux/bpf_trace.h>
97 #include <net/net_namespace.h>
99 #include <net/busy_poll.h>
100 #include <linux/rtnetlink.h>
101 #include <linux/stat.h>
104 #include <net/dst_metadata.h>
106 #include <net/pkt_sched.h>
107 #include <net/pkt_cls.h>
108 #include <net/checksum.h>
109 #include <net/xfrm.h>
110 #include <linux/highmem.h>
111 #include <linux/init.h>
112 #include <linux/module.h>
113 #include <linux/netpoll.h>
114 #include <linux/rcupdate.h>
115 #include <linux/delay.h>
116 #include <net/iw_handler.h>
117 #include <asm/current.h>
118 #include <linux/audit.h>
119 #include <linux/dmaengine.h>
120 #include <linux/err.h>
121 #include <linux/ctype.h>
122 #include <linux/if_arp.h>
123 #include <linux/if_vlan.h>
124 #include <linux/ip.h>
126 #include <net/mpls.h>
127 #include <linux/ipv6.h>
128 #include <linux/in.h>
129 #include <linux/jhash.h>
130 #include <linux/random.h>
131 #include <trace/events/napi.h>
132 #include <trace/events/net.h>
133 #include <trace/events/skb.h>
134 #include <trace/events/qdisc.h>
135 #include <linux/inetdevice.h>
136 #include <linux/cpu_rmap.h>
137 #include <linux/static_key.h>
138 #include <linux/hashtable.h>
139 #include <linux/vmalloc.h>
140 #include <linux/if_macvlan.h>
141 #include <linux/errqueue.h>
142 #include <linux/hrtimer.h>
143 #include <linux/netfilter_netdev.h>
144 #include <linux/crash_dump.h>
145 #include <linux/sctp.h>
146 #include <net/udp_tunnel.h>
147 #include <linux/net_namespace.h>
148 #include <linux/indirect_call_wrapper.h>
149 #include <net/devlink.h>
150 #include <linux/pm_runtime.h>
151 #include <linux/prandom.h>
152 #include <linux/once_lite.h>
154 #include "net-sysfs.h"
157 static DEFINE_SPINLOCK(ptype_lock);
158 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
159 struct list_head ptype_all __read_mostly; /* Taps */
161 static int netif_rx_internal(struct sk_buff *skb);
162 static int call_netdevice_notifiers_info(unsigned long val,
163 struct netdev_notifier_info *info);
164 static int call_netdevice_notifiers_extack(unsigned long val,
165 struct net_device *dev,
166 struct netlink_ext_ack *extack);
167 static struct napi_struct *napi_by_id(unsigned int napi_id);
170 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
173 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
175 * Writers must hold the rtnl semaphore while they loop through the
176 * dev_base_head list, and hold dev_base_lock for writing when they do the
177 * actual updates. This allows pure readers to access the list even
178 * while a writer is preparing to update it.
180 * To put it another way, dev_base_lock is held for writing only to
181 * protect against pure readers; the rtnl semaphore provides the
182 * protection against other writers.
184 * See, for example usages, register_netdevice() and
185 * unregister_netdevice(), which must be called with the rtnl
188 DEFINE_RWLOCK(dev_base_lock);
189 EXPORT_SYMBOL(dev_base_lock);
191 static DEFINE_MUTEX(ifalias_mutex);
193 /* protects napi_hash addition/deletion and napi_gen_id */
194 static DEFINE_SPINLOCK(napi_hash_lock);
196 static unsigned int napi_gen_id = NR_CPUS;
197 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
199 static DECLARE_RWSEM(devnet_rename_sem);
201 static inline void dev_base_seq_inc(struct net *net)
203 while (++net->dev_base_seq == 0)
207 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
209 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
211 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
214 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
216 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
219 static inline void rps_lock(struct softnet_data *sd)
222 spin_lock(&sd->input_pkt_queue.lock);
226 static inline void rps_unlock(struct softnet_data *sd)
229 spin_unlock(&sd->input_pkt_queue.lock);
233 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
236 struct netdev_name_node *name_node;
238 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
241 INIT_HLIST_NODE(&name_node->hlist);
242 name_node->dev = dev;
243 name_node->name = name;
247 static struct netdev_name_node *
248 netdev_name_node_head_alloc(struct net_device *dev)
250 struct netdev_name_node *name_node;
252 name_node = netdev_name_node_alloc(dev, dev->name);
255 INIT_LIST_HEAD(&name_node->list);
259 static void netdev_name_node_free(struct netdev_name_node *name_node)
264 static void netdev_name_node_add(struct net *net,
265 struct netdev_name_node *name_node)
267 hlist_add_head_rcu(&name_node->hlist,
268 dev_name_hash(net, name_node->name));
271 static void netdev_name_node_del(struct netdev_name_node *name_node)
273 hlist_del_rcu(&name_node->hlist);
276 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
279 struct hlist_head *head = dev_name_hash(net, name);
280 struct netdev_name_node *name_node;
282 hlist_for_each_entry(name_node, head, hlist)
283 if (!strcmp(name_node->name, name))
288 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
291 struct hlist_head *head = dev_name_hash(net, name);
292 struct netdev_name_node *name_node;
294 hlist_for_each_entry_rcu(name_node, head, hlist)
295 if (!strcmp(name_node->name, name))
300 bool netdev_name_in_use(struct net *net, const char *name)
302 return netdev_name_node_lookup(net, name);
304 EXPORT_SYMBOL(netdev_name_in_use);
306 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
308 struct netdev_name_node *name_node;
309 struct net *net = dev_net(dev);
311 name_node = netdev_name_node_lookup(net, name);
314 name_node = netdev_name_node_alloc(dev, name);
317 netdev_name_node_add(net, name_node);
318 /* The node that holds dev->name acts as a head of per-device list. */
319 list_add_tail(&name_node->list, &dev->name_node->list);
323 EXPORT_SYMBOL(netdev_name_node_alt_create);
325 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
327 list_del(&name_node->list);
328 netdev_name_node_del(name_node);
329 kfree(name_node->name);
330 netdev_name_node_free(name_node);
333 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
335 struct netdev_name_node *name_node;
336 struct net *net = dev_net(dev);
338 name_node = netdev_name_node_lookup(net, name);
341 /* lookup might have found our primary name or a name belonging
344 if (name_node == dev->name_node || name_node->dev != dev)
347 __netdev_name_node_alt_destroy(name_node);
351 EXPORT_SYMBOL(netdev_name_node_alt_destroy);
353 static void netdev_name_node_alt_flush(struct net_device *dev)
355 struct netdev_name_node *name_node, *tmp;
357 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
358 __netdev_name_node_alt_destroy(name_node);
361 /* Device list insertion */
362 static void list_netdevice(struct net_device *dev)
364 struct net *net = dev_net(dev);
368 write_lock_bh(&dev_base_lock);
369 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
370 netdev_name_node_add(net, dev->name_node);
371 hlist_add_head_rcu(&dev->index_hlist,
372 dev_index_hash(net, dev->ifindex));
373 write_unlock_bh(&dev_base_lock);
375 dev_base_seq_inc(net);
378 /* Device list removal
379 * caller must respect a RCU grace period before freeing/reusing dev
381 static void unlist_netdevice(struct net_device *dev)
385 /* Unlink dev from the device chain */
386 write_lock_bh(&dev_base_lock);
387 list_del_rcu(&dev->dev_list);
388 netdev_name_node_del(dev->name_node);
389 hlist_del_rcu(&dev->index_hlist);
390 write_unlock_bh(&dev_base_lock);
392 dev_base_seq_inc(dev_net(dev));
399 static RAW_NOTIFIER_HEAD(netdev_chain);
402 * Device drivers call our routines to queue packets here. We empty the
403 * queue in the local softnet handler.
406 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
407 EXPORT_PER_CPU_SYMBOL(softnet_data);
409 #ifdef CONFIG_LOCKDEP
411 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
412 * according to dev->type
414 static const unsigned short netdev_lock_type[] = {
415 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
416 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
417 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
418 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
419 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
420 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
421 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
422 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
423 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
424 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
425 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
426 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
427 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
428 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
429 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
431 static const char *const netdev_lock_name[] = {
432 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
433 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
434 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
435 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
436 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
437 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
438 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
439 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
440 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
441 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
442 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
443 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
444 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
445 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
446 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
448 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
449 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
451 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
455 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
456 if (netdev_lock_type[i] == dev_type)
458 /* the last key is used by default */
459 return ARRAY_SIZE(netdev_lock_type) - 1;
462 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
463 unsigned short dev_type)
467 i = netdev_lock_pos(dev_type);
468 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
469 netdev_lock_name[i]);
472 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
476 i = netdev_lock_pos(dev->type);
477 lockdep_set_class_and_name(&dev->addr_list_lock,
478 &netdev_addr_lock_key[i],
479 netdev_lock_name[i]);
482 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
483 unsigned short dev_type)
487 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
492 /*******************************************************************************
494 * Protocol management and registration routines
496 *******************************************************************************/
500 * Add a protocol ID to the list. Now that the input handler is
501 * smarter we can dispense with all the messy stuff that used to be
504 * BEWARE!!! Protocol handlers, mangling input packets,
505 * MUST BE last in hash buckets and checking protocol handlers
506 * MUST start from promiscuous ptype_all chain in net_bh.
507 * It is true now, do not change it.
508 * Explanation follows: if protocol handler, mangling packet, will
509 * be the first on list, it is not able to sense, that packet
510 * is cloned and should be copied-on-write, so that it will
511 * change it and subsequent readers will get broken packet.
515 static inline struct list_head *ptype_head(const struct packet_type *pt)
517 if (pt->type == htons(ETH_P_ALL))
518 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
520 return pt->dev ? &pt->dev->ptype_specific :
521 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
525 * dev_add_pack - add packet handler
526 * @pt: packet type declaration
528 * Add a protocol handler to the networking stack. The passed &packet_type
529 * is linked into kernel lists and may not be freed until it has been
530 * removed from the kernel lists.
532 * This call does not sleep therefore it can not
533 * guarantee all CPU's that are in middle of receiving packets
534 * will see the new packet type (until the next received packet).
537 void dev_add_pack(struct packet_type *pt)
539 struct list_head *head = ptype_head(pt);
541 spin_lock(&ptype_lock);
542 list_add_rcu(&pt->list, head);
543 spin_unlock(&ptype_lock);
545 EXPORT_SYMBOL(dev_add_pack);
548 * __dev_remove_pack - remove packet handler
549 * @pt: packet type declaration
551 * Remove a protocol handler that was previously added to the kernel
552 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
553 * from the kernel lists and can be freed or reused once this function
556 * The packet type might still be in use by receivers
557 * and must not be freed until after all the CPU's have gone
558 * through a quiescent state.
560 void __dev_remove_pack(struct packet_type *pt)
562 struct list_head *head = ptype_head(pt);
563 struct packet_type *pt1;
565 spin_lock(&ptype_lock);
567 list_for_each_entry(pt1, head, list) {
569 list_del_rcu(&pt->list);
574 pr_warn("dev_remove_pack: %p not found\n", pt);
576 spin_unlock(&ptype_lock);
578 EXPORT_SYMBOL(__dev_remove_pack);
581 * dev_remove_pack - remove packet handler
582 * @pt: packet type declaration
584 * Remove a protocol handler that was previously added to the kernel
585 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
586 * from the kernel lists and can be freed or reused once this function
589 * This call sleeps to guarantee that no CPU is looking at the packet
592 void dev_remove_pack(struct packet_type *pt)
594 __dev_remove_pack(pt);
598 EXPORT_SYMBOL(dev_remove_pack);
601 /*******************************************************************************
603 * Device Interface Subroutines
605 *******************************************************************************/
608 * dev_get_iflink - get 'iflink' value of a interface
609 * @dev: targeted interface
611 * Indicates the ifindex the interface is linked to.
612 * Physical interfaces have the same 'ifindex' and 'iflink' values.
615 int dev_get_iflink(const struct net_device *dev)
617 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
618 return dev->netdev_ops->ndo_get_iflink(dev);
622 EXPORT_SYMBOL(dev_get_iflink);
625 * dev_fill_metadata_dst - Retrieve tunnel egress information.
626 * @dev: targeted interface
629 * For better visibility of tunnel traffic OVS needs to retrieve
630 * egress tunnel information for a packet. Following API allows
631 * user to get this info.
633 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
635 struct ip_tunnel_info *info;
637 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
640 info = skb_tunnel_info_unclone(skb);
643 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
646 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
648 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
650 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
652 int k = stack->num_paths++;
654 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
657 return &stack->path[k];
660 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
661 struct net_device_path_stack *stack)
663 const struct net_device *last_dev;
664 struct net_device_path_ctx ctx = {
668 struct net_device_path *path;
671 stack->num_paths = 0;
672 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
674 path = dev_fwd_path(stack);
678 memset(path, 0, sizeof(struct net_device_path));
679 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
683 if (WARN_ON_ONCE(last_dev == ctx.dev))
686 path = dev_fwd_path(stack);
689 path->type = DEV_PATH_ETHERNET;
694 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
697 * __dev_get_by_name - find a device by its name
698 * @net: the applicable net namespace
699 * @name: name to find
701 * Find an interface by name. Must be called under RTNL semaphore
702 * or @dev_base_lock. If the name is found a pointer to the device
703 * is returned. If the name is not found then %NULL is returned. The
704 * reference counters are not incremented so the caller must be
705 * careful with locks.
708 struct net_device *__dev_get_by_name(struct net *net, const char *name)
710 struct netdev_name_node *node_name;
712 node_name = netdev_name_node_lookup(net, name);
713 return node_name ? node_name->dev : NULL;
715 EXPORT_SYMBOL(__dev_get_by_name);
718 * dev_get_by_name_rcu - find a device by its name
719 * @net: the applicable net namespace
720 * @name: name to find
722 * Find an interface by name.
723 * If the name is found a pointer to the device is returned.
724 * If the name is not found then %NULL is returned.
725 * The reference counters are not incremented so the caller must be
726 * careful with locks. The caller must hold RCU lock.
729 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
731 struct netdev_name_node *node_name;
733 node_name = netdev_name_node_lookup_rcu(net, name);
734 return node_name ? node_name->dev : NULL;
736 EXPORT_SYMBOL(dev_get_by_name_rcu);
739 * dev_get_by_name - find a device by its name
740 * @net: the applicable net namespace
741 * @name: name to find
743 * Find an interface by name. This can be called from any
744 * context and does its own locking. The returned handle has
745 * the usage count incremented and the caller must use dev_put() to
746 * release it when it is no longer needed. %NULL is returned if no
747 * matching device is found.
750 struct net_device *dev_get_by_name(struct net *net, const char *name)
752 struct net_device *dev;
755 dev = dev_get_by_name_rcu(net, name);
760 EXPORT_SYMBOL(dev_get_by_name);
763 * __dev_get_by_index - find a device by its ifindex
764 * @net: the applicable net namespace
765 * @ifindex: index of device
767 * Search for an interface by index. Returns %NULL if the device
768 * is not found or a pointer to the device. The device has not
769 * had its reference counter increased so the caller must be careful
770 * about locking. The caller must hold either the RTNL semaphore
774 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
776 struct net_device *dev;
777 struct hlist_head *head = dev_index_hash(net, ifindex);
779 hlist_for_each_entry(dev, head, index_hlist)
780 if (dev->ifindex == ifindex)
785 EXPORT_SYMBOL(__dev_get_by_index);
788 * dev_get_by_index_rcu - find a device by its ifindex
789 * @net: the applicable net namespace
790 * @ifindex: index of device
792 * Search for an interface by index. Returns %NULL if the device
793 * is not found or a pointer to the device. The device has not
794 * had its reference counter increased so the caller must be careful
795 * about locking. The caller must hold RCU lock.
798 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
800 struct net_device *dev;
801 struct hlist_head *head = dev_index_hash(net, ifindex);
803 hlist_for_each_entry_rcu(dev, head, index_hlist)
804 if (dev->ifindex == ifindex)
809 EXPORT_SYMBOL(dev_get_by_index_rcu);
813 * dev_get_by_index - find a device by its ifindex
814 * @net: the applicable net namespace
815 * @ifindex: index of device
817 * Search for an interface by index. Returns NULL if the device
818 * is not found or a pointer to the device. The device returned has
819 * had a reference added and the pointer is safe until the user calls
820 * dev_put to indicate they have finished with it.
823 struct net_device *dev_get_by_index(struct net *net, int ifindex)
825 struct net_device *dev;
828 dev = dev_get_by_index_rcu(net, ifindex);
833 EXPORT_SYMBOL(dev_get_by_index);
836 * dev_get_by_napi_id - find a device by napi_id
837 * @napi_id: ID of the NAPI struct
839 * Search for an interface by NAPI ID. Returns %NULL if the device
840 * is not found or a pointer to the device. The device has not had
841 * its reference counter increased so the caller must be careful
842 * about locking. The caller must hold RCU lock.
845 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
847 struct napi_struct *napi;
849 WARN_ON_ONCE(!rcu_read_lock_held());
851 if (napi_id < MIN_NAPI_ID)
854 napi = napi_by_id(napi_id);
856 return napi ? napi->dev : NULL;
858 EXPORT_SYMBOL(dev_get_by_napi_id);
861 * netdev_get_name - get a netdevice name, knowing its ifindex.
862 * @net: network namespace
863 * @name: a pointer to the buffer where the name will be stored.
864 * @ifindex: the ifindex of the interface to get the name from.
866 int netdev_get_name(struct net *net, char *name, int ifindex)
868 struct net_device *dev;
871 down_read(&devnet_rename_sem);
874 dev = dev_get_by_index_rcu(net, ifindex);
880 strcpy(name, dev->name);
885 up_read(&devnet_rename_sem);
890 * dev_getbyhwaddr_rcu - find a device by its hardware address
891 * @net: the applicable net namespace
892 * @type: media type of device
893 * @ha: hardware address
895 * Search for an interface by MAC address. Returns NULL if the device
896 * is not found or a pointer to the device.
897 * The caller must hold RCU or RTNL.
898 * The returned device has not had its ref count increased
899 * and the caller must therefore be careful about locking
903 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
906 struct net_device *dev;
908 for_each_netdev_rcu(net, dev)
909 if (dev->type == type &&
910 !memcmp(dev->dev_addr, ha, dev->addr_len))
915 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
917 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
919 struct net_device *dev, *ret = NULL;
922 for_each_netdev_rcu(net, dev)
923 if (dev->type == type) {
931 EXPORT_SYMBOL(dev_getfirstbyhwtype);
934 * __dev_get_by_flags - find any device with given flags
935 * @net: the applicable net namespace
936 * @if_flags: IFF_* values
937 * @mask: bitmask of bits in if_flags to check
939 * Search for any interface with the given flags. Returns NULL if a device
940 * is not found or a pointer to the device. Must be called inside
941 * rtnl_lock(), and result refcount is unchanged.
944 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
947 struct net_device *dev, *ret;
952 for_each_netdev(net, dev) {
953 if (((dev->flags ^ if_flags) & mask) == 0) {
960 EXPORT_SYMBOL(__dev_get_by_flags);
963 * dev_valid_name - check if name is okay for network device
966 * Network device names need to be valid file names to
967 * allow sysfs to work. We also disallow any kind of
970 bool dev_valid_name(const char *name)
974 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
976 if (!strcmp(name, ".") || !strcmp(name, ".."))
980 if (*name == '/' || *name == ':' || isspace(*name))
986 EXPORT_SYMBOL(dev_valid_name);
989 * __dev_alloc_name - allocate a name for a device
990 * @net: network namespace to allocate the device name in
991 * @name: name format string
992 * @buf: scratch buffer and result name string
994 * Passed a format string - eg "lt%d" it will try and find a suitable
995 * id. It scans list of devices to build up a free map, then chooses
996 * the first empty slot. The caller must hold the dev_base or rtnl lock
997 * while allocating the name and adding the device in order to avoid
999 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1000 * Returns the number of the unit assigned or a negative errno code.
1003 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1007 const int max_netdevices = 8*PAGE_SIZE;
1008 unsigned long *inuse;
1009 struct net_device *d;
1011 if (!dev_valid_name(name))
1014 p = strchr(name, '%');
1017 * Verify the string as this thing may have come from
1018 * the user. There must be either one "%d" and no other "%"
1021 if (p[1] != 'd' || strchr(p + 2, '%'))
1024 /* Use one page as a bit array of possible slots */
1025 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1029 for_each_netdev(net, d) {
1030 struct netdev_name_node *name_node;
1031 list_for_each_entry(name_node, &d->name_node->list, list) {
1032 if (!sscanf(name_node->name, name, &i))
1034 if (i < 0 || i >= max_netdevices)
1037 /* avoid cases where sscanf is not exact inverse of printf */
1038 snprintf(buf, IFNAMSIZ, name, i);
1039 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1042 if (!sscanf(d->name, name, &i))
1044 if (i < 0 || i >= max_netdevices)
1047 /* avoid cases where sscanf is not exact inverse of printf */
1048 snprintf(buf, IFNAMSIZ, name, i);
1049 if (!strncmp(buf, d->name, IFNAMSIZ))
1053 i = find_first_zero_bit(inuse, max_netdevices);
1054 free_page((unsigned long) inuse);
1057 snprintf(buf, IFNAMSIZ, name, i);
1058 if (!netdev_name_in_use(net, buf))
1061 /* It is possible to run out of possible slots
1062 * when the name is long and there isn't enough space left
1063 * for the digits, or if all bits are used.
1068 static int dev_alloc_name_ns(struct net *net,
1069 struct net_device *dev,
1076 ret = __dev_alloc_name(net, name, buf);
1078 strlcpy(dev->name, buf, IFNAMSIZ);
1083 * dev_alloc_name - allocate a name for a device
1085 * @name: name format string
1087 * Passed a format string - eg "lt%d" it will try and find a suitable
1088 * id. It scans list of devices to build up a free map, then chooses
1089 * the first empty slot. The caller must hold the dev_base or rtnl lock
1090 * while allocating the name and adding the device in order to avoid
1092 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1093 * Returns the number of the unit assigned or a negative errno code.
1096 int dev_alloc_name(struct net_device *dev, const char *name)
1098 return dev_alloc_name_ns(dev_net(dev), dev, name);
1100 EXPORT_SYMBOL(dev_alloc_name);
1102 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1107 if (!dev_valid_name(name))
1110 if (strchr(name, '%'))
1111 return dev_alloc_name_ns(net, dev, name);
1112 else if (netdev_name_in_use(net, name))
1114 else if (dev->name != name)
1115 strlcpy(dev->name, name, IFNAMSIZ);
1121 * dev_change_name - change name of a device
1123 * @newname: name (or format string) must be at least IFNAMSIZ
1125 * Change name of a device, can pass format strings "eth%d".
1128 int dev_change_name(struct net_device *dev, const char *newname)
1130 unsigned char old_assign_type;
1131 char oldname[IFNAMSIZ];
1137 BUG_ON(!dev_net(dev));
1141 /* Some auto-enslaved devices e.g. failover slaves are
1142 * special, as userspace might rename the device after
1143 * the interface had been brought up and running since
1144 * the point kernel initiated auto-enslavement. Allow
1145 * live name change even when these slave devices are
1148 * Typically, users of these auto-enslaving devices
1149 * don't actually care about slave name change, as
1150 * they are supposed to operate on master interface
1153 if (dev->flags & IFF_UP &&
1154 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1157 down_write(&devnet_rename_sem);
1159 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1160 up_write(&devnet_rename_sem);
1164 memcpy(oldname, dev->name, IFNAMSIZ);
1166 err = dev_get_valid_name(net, dev, newname);
1168 up_write(&devnet_rename_sem);
1172 if (oldname[0] && !strchr(oldname, '%'))
1173 netdev_info(dev, "renamed from %s\n", oldname);
1175 old_assign_type = dev->name_assign_type;
1176 dev->name_assign_type = NET_NAME_RENAMED;
1179 ret = device_rename(&dev->dev, dev->name);
1181 memcpy(dev->name, oldname, IFNAMSIZ);
1182 dev->name_assign_type = old_assign_type;
1183 up_write(&devnet_rename_sem);
1187 up_write(&devnet_rename_sem);
1189 netdev_adjacent_rename_links(dev, oldname);
1191 write_lock_bh(&dev_base_lock);
1192 netdev_name_node_del(dev->name_node);
1193 write_unlock_bh(&dev_base_lock);
1197 write_lock_bh(&dev_base_lock);
1198 netdev_name_node_add(net, dev->name_node);
1199 write_unlock_bh(&dev_base_lock);
1201 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1202 ret = notifier_to_errno(ret);
1205 /* err >= 0 after dev_alloc_name() or stores the first errno */
1208 down_write(&devnet_rename_sem);
1209 memcpy(dev->name, oldname, IFNAMSIZ);
1210 memcpy(oldname, newname, IFNAMSIZ);
1211 dev->name_assign_type = old_assign_type;
1212 old_assign_type = NET_NAME_RENAMED;
1215 netdev_err(dev, "name change rollback failed: %d\n",
1224 * dev_set_alias - change ifalias of a device
1226 * @alias: name up to IFALIASZ
1227 * @len: limit of bytes to copy from info
1229 * Set ifalias for a device,
1231 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1233 struct dev_ifalias *new_alias = NULL;
1235 if (len >= IFALIASZ)
1239 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1243 memcpy(new_alias->ifalias, alias, len);
1244 new_alias->ifalias[len] = 0;
1247 mutex_lock(&ifalias_mutex);
1248 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1249 mutex_is_locked(&ifalias_mutex));
1250 mutex_unlock(&ifalias_mutex);
1253 kfree_rcu(new_alias, rcuhead);
1257 EXPORT_SYMBOL(dev_set_alias);
1260 * dev_get_alias - get ifalias of a device
1262 * @name: buffer to store name of ifalias
1263 * @len: size of buffer
1265 * get ifalias for a device. Caller must make sure dev cannot go
1266 * away, e.g. rcu read lock or own a reference count to device.
1268 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1270 const struct dev_ifalias *alias;
1274 alias = rcu_dereference(dev->ifalias);
1276 ret = snprintf(name, len, "%s", alias->ifalias);
1283 * netdev_features_change - device changes features
1284 * @dev: device to cause notification
1286 * Called to indicate a device has changed features.
1288 void netdev_features_change(struct net_device *dev)
1290 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1292 EXPORT_SYMBOL(netdev_features_change);
1295 * netdev_state_change - device changes state
1296 * @dev: device to cause notification
1298 * Called to indicate a device has changed state. This function calls
1299 * the notifier chains for netdev_chain and sends a NEWLINK message
1300 * to the routing socket.
1302 void netdev_state_change(struct net_device *dev)
1304 if (dev->flags & IFF_UP) {
1305 struct netdev_notifier_change_info change_info = {
1309 call_netdevice_notifiers_info(NETDEV_CHANGE,
1311 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1314 EXPORT_SYMBOL(netdev_state_change);
1317 * __netdev_notify_peers - notify network peers about existence of @dev,
1318 * to be called when rtnl lock is already held.
1319 * @dev: network device
1321 * Generate traffic such that interested network peers are aware of
1322 * @dev, such as by generating a gratuitous ARP. This may be used when
1323 * a device wants to inform the rest of the network about some sort of
1324 * reconfiguration such as a failover event or virtual machine
1327 void __netdev_notify_peers(struct net_device *dev)
1330 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1331 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1333 EXPORT_SYMBOL(__netdev_notify_peers);
1336 * netdev_notify_peers - notify network peers about existence of @dev
1337 * @dev: network device
1339 * Generate traffic such that interested network peers are aware of
1340 * @dev, such as by generating a gratuitous ARP. This may be used when
1341 * a device wants to inform the rest of the network about some sort of
1342 * reconfiguration such as a failover event or virtual machine
1345 void netdev_notify_peers(struct net_device *dev)
1348 __netdev_notify_peers(dev);
1351 EXPORT_SYMBOL(netdev_notify_peers);
1353 static int napi_threaded_poll(void *data);
1355 static int napi_kthread_create(struct napi_struct *n)
1359 /* Create and wake up the kthread once to put it in
1360 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1361 * warning and work with loadavg.
1363 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1364 n->dev->name, n->napi_id);
1365 if (IS_ERR(n->thread)) {
1366 err = PTR_ERR(n->thread);
1367 pr_err("kthread_run failed with err %d\n", err);
1374 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1376 const struct net_device_ops *ops = dev->netdev_ops;
1381 if (!netif_device_present(dev)) {
1382 /* may be detached because parent is runtime-suspended */
1383 if (dev->dev.parent)
1384 pm_runtime_resume(dev->dev.parent);
1385 if (!netif_device_present(dev))
1389 /* Block netpoll from trying to do any rx path servicing.
1390 * If we don't do this there is a chance ndo_poll_controller
1391 * or ndo_poll may be running while we open the device
1393 netpoll_poll_disable(dev);
1395 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1396 ret = notifier_to_errno(ret);
1400 set_bit(__LINK_STATE_START, &dev->state);
1402 if (ops->ndo_validate_addr)
1403 ret = ops->ndo_validate_addr(dev);
1405 if (!ret && ops->ndo_open)
1406 ret = ops->ndo_open(dev);
1408 netpoll_poll_enable(dev);
1411 clear_bit(__LINK_STATE_START, &dev->state);
1413 dev->flags |= IFF_UP;
1414 dev_set_rx_mode(dev);
1416 add_device_randomness(dev->dev_addr, dev->addr_len);
1423 * dev_open - prepare an interface for use.
1424 * @dev: device to open
1425 * @extack: netlink extended ack
1427 * Takes a device from down to up state. The device's private open
1428 * function is invoked and then the multicast lists are loaded. Finally
1429 * the device is moved into the up state and a %NETDEV_UP message is
1430 * sent to the netdev notifier chain.
1432 * Calling this function on an active interface is a nop. On a failure
1433 * a negative errno code is returned.
1435 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1439 if (dev->flags & IFF_UP)
1442 ret = __dev_open(dev, extack);
1446 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1447 call_netdevice_notifiers(NETDEV_UP, dev);
1451 EXPORT_SYMBOL(dev_open);
1453 static void __dev_close_many(struct list_head *head)
1455 struct net_device *dev;
1460 list_for_each_entry(dev, head, close_list) {
1461 /* Temporarily disable netpoll until the interface is down */
1462 netpoll_poll_disable(dev);
1464 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1466 clear_bit(__LINK_STATE_START, &dev->state);
1468 /* Synchronize to scheduled poll. We cannot touch poll list, it
1469 * can be even on different cpu. So just clear netif_running().
1471 * dev->stop() will invoke napi_disable() on all of it's
1472 * napi_struct instances on this device.
1474 smp_mb__after_atomic(); /* Commit netif_running(). */
1477 dev_deactivate_many(head);
1479 list_for_each_entry(dev, head, close_list) {
1480 const struct net_device_ops *ops = dev->netdev_ops;
1483 * Call the device specific close. This cannot fail.
1484 * Only if device is UP
1486 * We allow it to be called even after a DETACH hot-plug
1492 dev->flags &= ~IFF_UP;
1493 netpoll_poll_enable(dev);
1497 static void __dev_close(struct net_device *dev)
1501 list_add(&dev->close_list, &single);
1502 __dev_close_many(&single);
1506 void dev_close_many(struct list_head *head, bool unlink)
1508 struct net_device *dev, *tmp;
1510 /* Remove the devices that don't need to be closed */
1511 list_for_each_entry_safe(dev, tmp, head, close_list)
1512 if (!(dev->flags & IFF_UP))
1513 list_del_init(&dev->close_list);
1515 __dev_close_many(head);
1517 list_for_each_entry_safe(dev, tmp, head, close_list) {
1518 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1519 call_netdevice_notifiers(NETDEV_DOWN, dev);
1521 list_del_init(&dev->close_list);
1524 EXPORT_SYMBOL(dev_close_many);
1527 * dev_close - shutdown an interface.
1528 * @dev: device to shutdown
1530 * This function moves an active device into down state. A
1531 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1532 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1535 void dev_close(struct net_device *dev)
1537 if (dev->flags & IFF_UP) {
1540 list_add(&dev->close_list, &single);
1541 dev_close_many(&single, true);
1545 EXPORT_SYMBOL(dev_close);
1549 * dev_disable_lro - disable Large Receive Offload on a device
1552 * Disable Large Receive Offload (LRO) on a net device. Must be
1553 * called under RTNL. This is needed if received packets may be
1554 * forwarded to another interface.
1556 void dev_disable_lro(struct net_device *dev)
1558 struct net_device *lower_dev;
1559 struct list_head *iter;
1561 dev->wanted_features &= ~NETIF_F_LRO;
1562 netdev_update_features(dev);
1564 if (unlikely(dev->features & NETIF_F_LRO))
1565 netdev_WARN(dev, "failed to disable LRO!\n");
1567 netdev_for_each_lower_dev(dev, lower_dev, iter)
1568 dev_disable_lro(lower_dev);
1570 EXPORT_SYMBOL(dev_disable_lro);
1573 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1576 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1577 * called under RTNL. This is needed if Generic XDP is installed on
1580 static void dev_disable_gro_hw(struct net_device *dev)
1582 dev->wanted_features &= ~NETIF_F_GRO_HW;
1583 netdev_update_features(dev);
1585 if (unlikely(dev->features & NETIF_F_GRO_HW))
1586 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1589 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1592 case NETDEV_##val: \
1593 return "NETDEV_" __stringify(val);
1595 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1596 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1597 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1598 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1599 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1600 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1601 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1602 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1603 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1607 return "UNKNOWN_NETDEV_EVENT";
1609 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1611 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1612 struct net_device *dev)
1614 struct netdev_notifier_info info = {
1618 return nb->notifier_call(nb, val, &info);
1621 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1622 struct net_device *dev)
1626 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1627 err = notifier_to_errno(err);
1631 if (!(dev->flags & IFF_UP))
1634 call_netdevice_notifier(nb, NETDEV_UP, dev);
1638 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1639 struct net_device *dev)
1641 if (dev->flags & IFF_UP) {
1642 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1644 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1646 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1649 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1652 struct net_device *dev;
1655 for_each_netdev(net, dev) {
1656 err = call_netdevice_register_notifiers(nb, dev);
1663 for_each_netdev_continue_reverse(net, dev)
1664 call_netdevice_unregister_notifiers(nb, dev);
1668 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1671 struct net_device *dev;
1673 for_each_netdev(net, dev)
1674 call_netdevice_unregister_notifiers(nb, dev);
1677 static int dev_boot_phase = 1;
1680 * register_netdevice_notifier - register a network notifier block
1683 * Register a notifier to be called when network device events occur.
1684 * The notifier passed is linked into the kernel structures and must
1685 * not be reused until it has been unregistered. A negative errno code
1686 * is returned on a failure.
1688 * When registered all registration and up events are replayed
1689 * to the new notifier to allow device to have a race free
1690 * view of the network device list.
1693 int register_netdevice_notifier(struct notifier_block *nb)
1698 /* Close race with setup_net() and cleanup_net() */
1699 down_write(&pernet_ops_rwsem);
1701 err = raw_notifier_chain_register(&netdev_chain, nb);
1707 err = call_netdevice_register_net_notifiers(nb, net);
1714 up_write(&pernet_ops_rwsem);
1718 for_each_net_continue_reverse(net)
1719 call_netdevice_unregister_net_notifiers(nb, net);
1721 raw_notifier_chain_unregister(&netdev_chain, nb);
1724 EXPORT_SYMBOL(register_netdevice_notifier);
1727 * unregister_netdevice_notifier - unregister a network notifier block
1730 * Unregister a notifier previously registered by
1731 * register_netdevice_notifier(). The notifier is unlinked into the
1732 * kernel structures and may then be reused. A negative errno code
1733 * is returned on a failure.
1735 * After unregistering unregister and down device events are synthesized
1736 * for all devices on the device list to the removed notifier to remove
1737 * the need for special case cleanup code.
1740 int unregister_netdevice_notifier(struct notifier_block *nb)
1745 /* Close race with setup_net() and cleanup_net() */
1746 down_write(&pernet_ops_rwsem);
1748 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1753 call_netdevice_unregister_net_notifiers(nb, net);
1757 up_write(&pernet_ops_rwsem);
1760 EXPORT_SYMBOL(unregister_netdevice_notifier);
1762 static int __register_netdevice_notifier_net(struct net *net,
1763 struct notifier_block *nb,
1764 bool ignore_call_fail)
1768 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1774 err = call_netdevice_register_net_notifiers(nb, net);
1775 if (err && !ignore_call_fail)
1776 goto chain_unregister;
1781 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1785 static int __unregister_netdevice_notifier_net(struct net *net,
1786 struct notifier_block *nb)
1790 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1794 call_netdevice_unregister_net_notifiers(nb, net);
1799 * register_netdevice_notifier_net - register a per-netns network notifier block
1800 * @net: network namespace
1803 * Register a notifier to be called when network device events occur.
1804 * The notifier passed is linked into the kernel structures and must
1805 * not be reused until it has been unregistered. A negative errno code
1806 * is returned on a failure.
1808 * When registered all registration and up events are replayed
1809 * to the new notifier to allow device to have a race free
1810 * view of the network device list.
1813 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1818 err = __register_netdevice_notifier_net(net, nb, false);
1822 EXPORT_SYMBOL(register_netdevice_notifier_net);
1825 * unregister_netdevice_notifier_net - unregister a per-netns
1826 * network notifier block
1827 * @net: network namespace
1830 * Unregister a notifier previously registered by
1831 * register_netdevice_notifier(). The notifier is unlinked into the
1832 * kernel structures and may then be reused. A negative errno code
1833 * is returned on a failure.
1835 * After unregistering unregister and down device events are synthesized
1836 * for all devices on the device list to the removed notifier to remove
1837 * the need for special case cleanup code.
1840 int unregister_netdevice_notifier_net(struct net *net,
1841 struct notifier_block *nb)
1846 err = __unregister_netdevice_notifier_net(net, nb);
1850 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1852 int register_netdevice_notifier_dev_net(struct net_device *dev,
1853 struct notifier_block *nb,
1854 struct netdev_net_notifier *nn)
1859 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1862 list_add(&nn->list, &dev->net_notifier_list);
1867 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1869 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1870 struct notifier_block *nb,
1871 struct netdev_net_notifier *nn)
1876 list_del(&nn->list);
1877 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1881 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1883 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1886 struct netdev_net_notifier *nn;
1888 list_for_each_entry(nn, &dev->net_notifier_list, list) {
1889 __unregister_netdevice_notifier_net(dev_net(dev), nn->nb);
1890 __register_netdevice_notifier_net(net, nn->nb, true);
1895 * call_netdevice_notifiers_info - call all network notifier blocks
1896 * @val: value passed unmodified to notifier function
1897 * @info: notifier information data
1899 * Call all network notifier blocks. Parameters and return value
1900 * are as for raw_notifier_call_chain().
1903 static int call_netdevice_notifiers_info(unsigned long val,
1904 struct netdev_notifier_info *info)
1906 struct net *net = dev_net(info->dev);
1911 /* Run per-netns notifier block chain first, then run the global one.
1912 * Hopefully, one day, the global one is going to be removed after
1913 * all notifier block registrators get converted to be per-netns.
1915 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1916 if (ret & NOTIFY_STOP_MASK)
1918 return raw_notifier_call_chain(&netdev_chain, val, info);
1921 static int call_netdevice_notifiers_extack(unsigned long val,
1922 struct net_device *dev,
1923 struct netlink_ext_ack *extack)
1925 struct netdev_notifier_info info = {
1930 return call_netdevice_notifiers_info(val, &info);
1934 * call_netdevice_notifiers - call all network notifier blocks
1935 * @val: value passed unmodified to notifier function
1936 * @dev: net_device pointer passed unmodified to notifier function
1938 * Call all network notifier blocks. Parameters and return value
1939 * are as for raw_notifier_call_chain().
1942 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1944 return call_netdevice_notifiers_extack(val, dev, NULL);
1946 EXPORT_SYMBOL(call_netdevice_notifiers);
1949 * call_netdevice_notifiers_mtu - call all network notifier blocks
1950 * @val: value passed unmodified to notifier function
1951 * @dev: net_device pointer passed unmodified to notifier function
1952 * @arg: additional u32 argument passed to the notifier function
1954 * Call all network notifier blocks. Parameters and return value
1955 * are as for raw_notifier_call_chain().
1957 static int call_netdevice_notifiers_mtu(unsigned long val,
1958 struct net_device *dev, u32 arg)
1960 struct netdev_notifier_info_ext info = {
1965 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
1967 return call_netdevice_notifiers_info(val, &info.info);
1970 #ifdef CONFIG_NET_INGRESS
1971 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
1973 void net_inc_ingress_queue(void)
1975 static_branch_inc(&ingress_needed_key);
1977 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
1979 void net_dec_ingress_queue(void)
1981 static_branch_dec(&ingress_needed_key);
1983 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
1986 #ifdef CONFIG_NET_EGRESS
1987 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
1989 void net_inc_egress_queue(void)
1991 static_branch_inc(&egress_needed_key);
1993 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
1995 void net_dec_egress_queue(void)
1997 static_branch_dec(&egress_needed_key);
1999 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2002 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2003 #ifdef CONFIG_JUMP_LABEL
2004 static atomic_t netstamp_needed_deferred;
2005 static atomic_t netstamp_wanted;
2006 static void netstamp_clear(struct work_struct *work)
2008 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2011 wanted = atomic_add_return(deferred, &netstamp_wanted);
2013 static_branch_enable(&netstamp_needed_key);
2015 static_branch_disable(&netstamp_needed_key);
2017 static DECLARE_WORK(netstamp_work, netstamp_clear);
2020 void net_enable_timestamp(void)
2022 #ifdef CONFIG_JUMP_LABEL
2026 wanted = atomic_read(&netstamp_wanted);
2029 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2032 atomic_inc(&netstamp_needed_deferred);
2033 schedule_work(&netstamp_work);
2035 static_branch_inc(&netstamp_needed_key);
2038 EXPORT_SYMBOL(net_enable_timestamp);
2040 void net_disable_timestamp(void)
2042 #ifdef CONFIG_JUMP_LABEL
2046 wanted = atomic_read(&netstamp_wanted);
2049 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2052 atomic_dec(&netstamp_needed_deferred);
2053 schedule_work(&netstamp_work);
2055 static_branch_dec(&netstamp_needed_key);
2058 EXPORT_SYMBOL(net_disable_timestamp);
2060 static inline void net_timestamp_set(struct sk_buff *skb)
2063 if (static_branch_unlikely(&netstamp_needed_key))
2064 __net_timestamp(skb);
2067 #define net_timestamp_check(COND, SKB) \
2068 if (static_branch_unlikely(&netstamp_needed_key)) { \
2069 if ((COND) && !(SKB)->tstamp) \
2070 __net_timestamp(SKB); \
2073 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2075 return __is_skb_forwardable(dev, skb, true);
2077 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2079 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2082 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2085 skb->protocol = eth_type_trans(skb, dev);
2086 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2092 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2094 return __dev_forward_skb2(dev, skb, true);
2096 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2099 * dev_forward_skb - loopback an skb to another netif
2101 * @dev: destination network device
2102 * @skb: buffer to forward
2105 * NET_RX_SUCCESS (no congestion)
2106 * NET_RX_DROP (packet was dropped, but freed)
2108 * dev_forward_skb can be used for injecting an skb from the
2109 * start_xmit function of one device into the receive queue
2110 * of another device.
2112 * The receiving device may be in another namespace, so
2113 * we have to clear all information in the skb that could
2114 * impact namespace isolation.
2116 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2118 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2120 EXPORT_SYMBOL_GPL(dev_forward_skb);
2122 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2124 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2127 static inline int deliver_skb(struct sk_buff *skb,
2128 struct packet_type *pt_prev,
2129 struct net_device *orig_dev)
2131 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2133 refcount_inc(&skb->users);
2134 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2137 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2138 struct packet_type **pt,
2139 struct net_device *orig_dev,
2141 struct list_head *ptype_list)
2143 struct packet_type *ptype, *pt_prev = *pt;
2145 list_for_each_entry_rcu(ptype, ptype_list, list) {
2146 if (ptype->type != type)
2149 deliver_skb(skb, pt_prev, orig_dev);
2155 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2157 if (!ptype->af_packet_priv || !skb->sk)
2160 if (ptype->id_match)
2161 return ptype->id_match(ptype, skb->sk);
2162 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2169 * dev_nit_active - return true if any network interface taps are in use
2171 * @dev: network device to check for the presence of taps
2173 bool dev_nit_active(struct net_device *dev)
2175 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2177 EXPORT_SYMBOL_GPL(dev_nit_active);
2180 * Support routine. Sends outgoing frames to any network
2181 * taps currently in use.
2184 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2186 struct packet_type *ptype;
2187 struct sk_buff *skb2 = NULL;
2188 struct packet_type *pt_prev = NULL;
2189 struct list_head *ptype_list = &ptype_all;
2193 list_for_each_entry_rcu(ptype, ptype_list, list) {
2194 if (ptype->ignore_outgoing)
2197 /* Never send packets back to the socket
2198 * they originated from - MvS (miquels@drinkel.ow.org)
2200 if (skb_loop_sk(ptype, skb))
2204 deliver_skb(skb2, pt_prev, skb->dev);
2209 /* need to clone skb, done only once */
2210 skb2 = skb_clone(skb, GFP_ATOMIC);
2214 net_timestamp_set(skb2);
2216 /* skb->nh should be correctly
2217 * set by sender, so that the second statement is
2218 * just protection against buggy protocols.
2220 skb_reset_mac_header(skb2);
2222 if (skb_network_header(skb2) < skb2->data ||
2223 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2224 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2225 ntohs(skb2->protocol),
2227 skb_reset_network_header(skb2);
2230 skb2->transport_header = skb2->network_header;
2231 skb2->pkt_type = PACKET_OUTGOING;
2235 if (ptype_list == &ptype_all) {
2236 ptype_list = &dev->ptype_all;
2241 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2242 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2248 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2251 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2252 * @dev: Network device
2253 * @txq: number of queues available
2255 * If real_num_tx_queues is changed the tc mappings may no longer be
2256 * valid. To resolve this verify the tc mapping remains valid and if
2257 * not NULL the mapping. With no priorities mapping to this
2258 * offset/count pair it will no longer be used. In the worst case TC0
2259 * is invalid nothing can be done so disable priority mappings. If is
2260 * expected that drivers will fix this mapping if they can before
2261 * calling netif_set_real_num_tx_queues.
2263 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2266 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2268 /* If TC0 is invalidated disable TC mapping */
2269 if (tc->offset + tc->count > txq) {
2270 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2275 /* Invalidated prio to tc mappings set to TC0 */
2276 for (i = 1; i < TC_BITMASK + 1; i++) {
2277 int q = netdev_get_prio_tc_map(dev, i);
2279 tc = &dev->tc_to_txq[q];
2280 if (tc->offset + tc->count > txq) {
2281 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",
2283 netdev_set_prio_tc_map(dev, i, 0);
2288 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2291 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2294 /* walk through the TCs and see if it falls into any of them */
2295 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2296 if ((txq - tc->offset) < tc->count)
2300 /* didn't find it, just return -1 to indicate no match */
2306 EXPORT_SYMBOL(netdev_txq_to_tc);
2309 static struct static_key xps_needed __read_mostly;
2310 static struct static_key xps_rxqs_needed __read_mostly;
2311 static DEFINE_MUTEX(xps_map_mutex);
2312 #define xmap_dereference(P) \
2313 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2315 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2316 struct xps_dev_maps *old_maps, int tci, u16 index)
2318 struct xps_map *map = NULL;
2322 map = xmap_dereference(dev_maps->attr_map[tci]);
2326 for (pos = map->len; pos--;) {
2327 if (map->queues[pos] != index)
2331 map->queues[pos] = map->queues[--map->len];
2336 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2337 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2338 kfree_rcu(map, rcu);
2345 static bool remove_xps_queue_cpu(struct net_device *dev,
2346 struct xps_dev_maps *dev_maps,
2347 int cpu, u16 offset, u16 count)
2349 int num_tc = dev_maps->num_tc;
2350 bool active = false;
2353 for (tci = cpu * num_tc; num_tc--; tci++) {
2356 for (i = count, j = offset; i--; j++) {
2357 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2367 static void reset_xps_maps(struct net_device *dev,
2368 struct xps_dev_maps *dev_maps,
2369 enum xps_map_type type)
2371 static_key_slow_dec_cpuslocked(&xps_needed);
2372 if (type == XPS_RXQS)
2373 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2375 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2377 kfree_rcu(dev_maps, rcu);
2380 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2381 u16 offset, u16 count)
2383 struct xps_dev_maps *dev_maps;
2384 bool active = false;
2387 dev_maps = xmap_dereference(dev->xps_maps[type]);
2391 for (j = 0; j < dev_maps->nr_ids; j++)
2392 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2394 reset_xps_maps(dev, dev_maps, type);
2396 if (type == XPS_CPUS) {
2397 for (i = offset + (count - 1); count--; i--)
2398 netdev_queue_numa_node_write(
2399 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2403 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2406 if (!static_key_false(&xps_needed))
2410 mutex_lock(&xps_map_mutex);
2412 if (static_key_false(&xps_rxqs_needed))
2413 clean_xps_maps(dev, XPS_RXQS, offset, count);
2415 clean_xps_maps(dev, XPS_CPUS, offset, count);
2417 mutex_unlock(&xps_map_mutex);
2421 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2423 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2426 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2427 u16 index, bool is_rxqs_map)
2429 struct xps_map *new_map;
2430 int alloc_len = XPS_MIN_MAP_ALLOC;
2433 for (pos = 0; map && pos < map->len; pos++) {
2434 if (map->queues[pos] != index)
2439 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2441 if (pos < map->alloc_len)
2444 alloc_len = map->alloc_len * 2;
2447 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2451 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2453 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2454 cpu_to_node(attr_index));
2458 for (i = 0; i < pos; i++)
2459 new_map->queues[i] = map->queues[i];
2460 new_map->alloc_len = alloc_len;
2466 /* Copy xps maps at a given index */
2467 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2468 struct xps_dev_maps *new_dev_maps, int index,
2469 int tc, bool skip_tc)
2471 int i, tci = index * dev_maps->num_tc;
2472 struct xps_map *map;
2474 /* copy maps belonging to foreign traffic classes */
2475 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2476 if (i == tc && skip_tc)
2479 /* fill in the new device map from the old device map */
2480 map = xmap_dereference(dev_maps->attr_map[tci]);
2481 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2485 /* Must be called under cpus_read_lock */
2486 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2487 u16 index, enum xps_map_type type)
2489 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2490 const unsigned long *online_mask = NULL;
2491 bool active = false, copy = false;
2492 int i, j, tci, numa_node_id = -2;
2493 int maps_sz, num_tc = 1, tc = 0;
2494 struct xps_map *map, *new_map;
2495 unsigned int nr_ids;
2498 /* Do not allow XPS on subordinate device directly */
2499 num_tc = dev->num_tc;
2503 /* If queue belongs to subordinate dev use its map */
2504 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2506 tc = netdev_txq_to_tc(dev, index);
2511 mutex_lock(&xps_map_mutex);
2513 dev_maps = xmap_dereference(dev->xps_maps[type]);
2514 if (type == XPS_RXQS) {
2515 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2516 nr_ids = dev->num_rx_queues;
2518 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2519 if (num_possible_cpus() > 1)
2520 online_mask = cpumask_bits(cpu_online_mask);
2521 nr_ids = nr_cpu_ids;
2524 if (maps_sz < L1_CACHE_BYTES)
2525 maps_sz = L1_CACHE_BYTES;
2527 /* The old dev_maps could be larger or smaller than the one we're
2528 * setting up now, as dev->num_tc or nr_ids could have been updated in
2529 * between. We could try to be smart, but let's be safe instead and only
2530 * copy foreign traffic classes if the two map sizes match.
2533 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2536 /* allocate memory for queue storage */
2537 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2539 if (!new_dev_maps) {
2540 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2541 if (!new_dev_maps) {
2542 mutex_unlock(&xps_map_mutex);
2546 new_dev_maps->nr_ids = nr_ids;
2547 new_dev_maps->num_tc = num_tc;
2550 tci = j * num_tc + tc;
2551 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2553 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2557 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2561 goto out_no_new_maps;
2564 /* Increment static keys at most once per type */
2565 static_key_slow_inc_cpuslocked(&xps_needed);
2566 if (type == XPS_RXQS)
2567 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2570 for (j = 0; j < nr_ids; j++) {
2571 bool skip_tc = false;
2573 tci = j * num_tc + tc;
2574 if (netif_attr_test_mask(j, mask, nr_ids) &&
2575 netif_attr_test_online(j, online_mask, nr_ids)) {
2576 /* add tx-queue to CPU/rx-queue maps */
2581 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2582 while ((pos < map->len) && (map->queues[pos] != index))
2585 if (pos == map->len)
2586 map->queues[map->len++] = index;
2588 if (type == XPS_CPUS) {
2589 if (numa_node_id == -2)
2590 numa_node_id = cpu_to_node(j);
2591 else if (numa_node_id != cpu_to_node(j))
2598 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2602 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2604 /* Cleanup old maps */
2606 goto out_no_old_maps;
2608 for (j = 0; j < dev_maps->nr_ids; j++) {
2609 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2610 map = xmap_dereference(dev_maps->attr_map[tci]);
2615 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2620 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2621 kfree_rcu(map, rcu);
2625 old_dev_maps = dev_maps;
2628 dev_maps = new_dev_maps;
2632 if (type == XPS_CPUS)
2633 /* update Tx queue numa node */
2634 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2635 (numa_node_id >= 0) ?
2636 numa_node_id : NUMA_NO_NODE);
2641 /* removes tx-queue from unused CPUs/rx-queues */
2642 for (j = 0; j < dev_maps->nr_ids; j++) {
2643 tci = j * dev_maps->num_tc;
2645 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2647 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2648 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2651 active |= remove_xps_queue(dev_maps,
2652 copy ? old_dev_maps : NULL,
2658 kfree_rcu(old_dev_maps, rcu);
2660 /* free map if not active */
2662 reset_xps_maps(dev, dev_maps, type);
2665 mutex_unlock(&xps_map_mutex);
2669 /* remove any maps that we added */
2670 for (j = 0; j < nr_ids; j++) {
2671 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2672 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2674 xmap_dereference(dev_maps->attr_map[tci]) :
2676 if (new_map && new_map != map)
2681 mutex_unlock(&xps_map_mutex);
2683 kfree(new_dev_maps);
2686 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2688 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2694 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2699 EXPORT_SYMBOL(netif_set_xps_queue);
2702 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2704 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2706 /* Unbind any subordinate channels */
2707 while (txq-- != &dev->_tx[0]) {
2709 netdev_unbind_sb_channel(dev, txq->sb_dev);
2713 void netdev_reset_tc(struct net_device *dev)
2716 netif_reset_xps_queues_gt(dev, 0);
2718 netdev_unbind_all_sb_channels(dev);
2720 /* Reset TC configuration of device */
2722 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2723 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2725 EXPORT_SYMBOL(netdev_reset_tc);
2727 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2729 if (tc >= dev->num_tc)
2733 netif_reset_xps_queues(dev, offset, count);
2735 dev->tc_to_txq[tc].count = count;
2736 dev->tc_to_txq[tc].offset = offset;
2739 EXPORT_SYMBOL(netdev_set_tc_queue);
2741 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2743 if (num_tc > TC_MAX_QUEUE)
2747 netif_reset_xps_queues_gt(dev, 0);
2749 netdev_unbind_all_sb_channels(dev);
2751 dev->num_tc = num_tc;
2754 EXPORT_SYMBOL(netdev_set_num_tc);
2756 void netdev_unbind_sb_channel(struct net_device *dev,
2757 struct net_device *sb_dev)
2759 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2762 netif_reset_xps_queues_gt(sb_dev, 0);
2764 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2765 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2767 while (txq-- != &dev->_tx[0]) {
2768 if (txq->sb_dev == sb_dev)
2772 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2774 int netdev_bind_sb_channel_queue(struct net_device *dev,
2775 struct net_device *sb_dev,
2776 u8 tc, u16 count, u16 offset)
2778 /* Make certain the sb_dev and dev are already configured */
2779 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2782 /* We cannot hand out queues we don't have */
2783 if ((offset + count) > dev->real_num_tx_queues)
2786 /* Record the mapping */
2787 sb_dev->tc_to_txq[tc].count = count;
2788 sb_dev->tc_to_txq[tc].offset = offset;
2790 /* Provide a way for Tx queue to find the tc_to_txq map or
2791 * XPS map for itself.
2794 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2798 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2800 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2802 /* Do not use a multiqueue device to represent a subordinate channel */
2803 if (netif_is_multiqueue(dev))
2806 /* We allow channels 1 - 32767 to be used for subordinate channels.
2807 * Channel 0 is meant to be "native" mode and used only to represent
2808 * the main root device. We allow writing 0 to reset the device back
2809 * to normal mode after being used as a subordinate channel.
2811 if (channel > S16_MAX)
2814 dev->num_tc = -channel;
2818 EXPORT_SYMBOL(netdev_set_sb_channel);
2821 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2822 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2824 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2829 disabling = txq < dev->real_num_tx_queues;
2831 if (txq < 1 || txq > dev->num_tx_queues)
2834 if (dev->reg_state == NETREG_REGISTERED ||
2835 dev->reg_state == NETREG_UNREGISTERING) {
2838 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2844 netif_setup_tc(dev, txq);
2846 dev_qdisc_change_real_num_tx(dev, txq);
2848 dev->real_num_tx_queues = txq;
2852 qdisc_reset_all_tx_gt(dev, txq);
2854 netif_reset_xps_queues_gt(dev, txq);
2858 dev->real_num_tx_queues = txq;
2863 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2867 * netif_set_real_num_rx_queues - set actual number of RX queues used
2868 * @dev: Network device
2869 * @rxq: Actual number of RX queues
2871 * This must be called either with the rtnl_lock held or before
2872 * registration of the net device. Returns 0 on success, or a
2873 * negative error code. If called before registration, it always
2876 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2880 if (rxq < 1 || rxq > dev->num_rx_queues)
2883 if (dev->reg_state == NETREG_REGISTERED) {
2886 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2892 dev->real_num_rx_queues = rxq;
2895 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2899 * netif_set_real_num_queues - set actual number of RX and TX queues used
2900 * @dev: Network device
2901 * @txq: Actual number of TX queues
2902 * @rxq: Actual number of RX queues
2904 * Set the real number of both TX and RX queues.
2905 * Does nothing if the number of queues is already correct.
2907 int netif_set_real_num_queues(struct net_device *dev,
2908 unsigned int txq, unsigned int rxq)
2910 unsigned int old_rxq = dev->real_num_rx_queues;
2913 if (txq < 1 || txq > dev->num_tx_queues ||
2914 rxq < 1 || rxq > dev->num_rx_queues)
2917 /* Start from increases, so the error path only does decreases -
2918 * decreases can't fail.
2920 if (rxq > dev->real_num_rx_queues) {
2921 err = netif_set_real_num_rx_queues(dev, rxq);
2925 if (txq > dev->real_num_tx_queues) {
2926 err = netif_set_real_num_tx_queues(dev, txq);
2930 if (rxq < dev->real_num_rx_queues)
2931 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
2932 if (txq < dev->real_num_tx_queues)
2933 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
2937 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
2940 EXPORT_SYMBOL(netif_set_real_num_queues);
2943 * netif_get_num_default_rss_queues - default number of RSS queues
2945 * This routine should set an upper limit on the number of RSS queues
2946 * used by default by multiqueue devices.
2948 int netif_get_num_default_rss_queues(void)
2950 return is_kdump_kernel() ?
2951 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2953 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2955 static void __netif_reschedule(struct Qdisc *q)
2957 struct softnet_data *sd;
2958 unsigned long flags;
2960 local_irq_save(flags);
2961 sd = this_cpu_ptr(&softnet_data);
2962 q->next_sched = NULL;
2963 *sd->output_queue_tailp = q;
2964 sd->output_queue_tailp = &q->next_sched;
2965 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2966 local_irq_restore(flags);
2969 void __netif_schedule(struct Qdisc *q)
2971 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2972 __netif_reschedule(q);
2974 EXPORT_SYMBOL(__netif_schedule);
2976 struct dev_kfree_skb_cb {
2977 enum skb_free_reason reason;
2980 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
2982 return (struct dev_kfree_skb_cb *)skb->cb;
2985 void netif_schedule_queue(struct netdev_queue *txq)
2988 if (!netif_xmit_stopped(txq)) {
2989 struct Qdisc *q = rcu_dereference(txq->qdisc);
2991 __netif_schedule(q);
2995 EXPORT_SYMBOL(netif_schedule_queue);
2997 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
2999 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3003 q = rcu_dereference(dev_queue->qdisc);
3004 __netif_schedule(q);
3008 EXPORT_SYMBOL(netif_tx_wake_queue);
3010 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3012 unsigned long flags;
3017 if (likely(refcount_read(&skb->users) == 1)) {
3019 refcount_set(&skb->users, 0);
3020 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3023 get_kfree_skb_cb(skb)->reason = reason;
3024 local_irq_save(flags);
3025 skb->next = __this_cpu_read(softnet_data.completion_queue);
3026 __this_cpu_write(softnet_data.completion_queue, skb);
3027 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3028 local_irq_restore(flags);
3030 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3032 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3034 if (in_hardirq() || irqs_disabled())
3035 __dev_kfree_skb_irq(skb, reason);
3039 EXPORT_SYMBOL(__dev_kfree_skb_any);
3043 * netif_device_detach - mark device as removed
3044 * @dev: network device
3046 * Mark device as removed from system and therefore no longer available.
3048 void netif_device_detach(struct net_device *dev)
3050 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3051 netif_running(dev)) {
3052 netif_tx_stop_all_queues(dev);
3055 EXPORT_SYMBOL(netif_device_detach);
3058 * netif_device_attach - mark device as attached
3059 * @dev: network device
3061 * Mark device as attached from system and restart if needed.
3063 void netif_device_attach(struct net_device *dev)
3065 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3066 netif_running(dev)) {
3067 netif_tx_wake_all_queues(dev);
3068 __netdev_watchdog_up(dev);
3071 EXPORT_SYMBOL(netif_device_attach);
3074 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3075 * to be used as a distribution range.
3077 static u16 skb_tx_hash(const struct net_device *dev,
3078 const struct net_device *sb_dev,
3079 struct sk_buff *skb)
3083 u16 qcount = dev->real_num_tx_queues;
3086 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3088 qoffset = sb_dev->tc_to_txq[tc].offset;
3089 qcount = sb_dev->tc_to_txq[tc].count;
3090 if (unlikely(!qcount)) {
3091 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3092 sb_dev->name, qoffset, tc);
3094 qcount = dev->real_num_tx_queues;
3098 if (skb_rx_queue_recorded(skb)) {
3099 hash = skb_get_rx_queue(skb);
3100 if (hash >= qoffset)
3102 while (unlikely(hash >= qcount))
3104 return hash + qoffset;
3107 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3110 static void skb_warn_bad_offload(const struct sk_buff *skb)
3112 static const netdev_features_t null_features;
3113 struct net_device *dev = skb->dev;
3114 const char *name = "";
3116 if (!net_ratelimit())
3120 if (dev->dev.parent)
3121 name = dev_driver_string(dev->dev.parent);
3123 name = netdev_name(dev);
3125 skb_dump(KERN_WARNING, skb, false);
3126 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3127 name, dev ? &dev->features : &null_features,
3128 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3132 * Invalidate hardware checksum when packet is to be mangled, and
3133 * complete checksum manually on outgoing path.
3135 int skb_checksum_help(struct sk_buff *skb)
3138 int ret = 0, offset;
3140 if (skb->ip_summed == CHECKSUM_COMPLETE)
3141 goto out_set_summed;
3143 if (unlikely(skb_is_gso(skb))) {
3144 skb_warn_bad_offload(skb);
3148 /* Before computing a checksum, we should make sure no frag could
3149 * be modified by an external entity : checksum could be wrong.
3151 if (skb_has_shared_frag(skb)) {
3152 ret = __skb_linearize(skb);
3157 offset = skb_checksum_start_offset(skb);
3158 BUG_ON(offset >= skb_headlen(skb));
3159 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3161 offset += skb->csum_offset;
3162 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3164 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3168 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3170 skb->ip_summed = CHECKSUM_NONE;
3174 EXPORT_SYMBOL(skb_checksum_help);
3176 int skb_crc32c_csum_help(struct sk_buff *skb)
3179 int ret = 0, offset, start;
3181 if (skb->ip_summed != CHECKSUM_PARTIAL)
3184 if (unlikely(skb_is_gso(skb)))
3187 /* Before computing a checksum, we should make sure no frag could
3188 * be modified by an external entity : checksum could be wrong.
3190 if (unlikely(skb_has_shared_frag(skb))) {
3191 ret = __skb_linearize(skb);
3195 start = skb_checksum_start_offset(skb);
3196 offset = start + offsetof(struct sctphdr, checksum);
3197 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3202 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3206 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3207 skb->len - start, ~(__u32)0,
3209 *(__le32 *)(skb->data + offset) = crc32c_csum;
3210 skb->ip_summed = CHECKSUM_NONE;
3211 skb->csum_not_inet = 0;
3216 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3218 __be16 type = skb->protocol;
3220 /* Tunnel gso handlers can set protocol to ethernet. */
3221 if (type == htons(ETH_P_TEB)) {
3224 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3227 eth = (struct ethhdr *)skb->data;
3228 type = eth->h_proto;
3231 return __vlan_get_protocol(skb, type, depth);
3234 /* openvswitch calls this on rx path, so we need a different check.
3236 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3239 return skb->ip_summed != CHECKSUM_PARTIAL &&
3240 skb->ip_summed != CHECKSUM_UNNECESSARY;
3242 return skb->ip_summed == CHECKSUM_NONE;
3246 * __skb_gso_segment - Perform segmentation on skb.
3247 * @skb: buffer to segment
3248 * @features: features for the output path (see dev->features)
3249 * @tx_path: whether it is called in TX path
3251 * This function segments the given skb and returns a list of segments.
3253 * It may return NULL if the skb requires no segmentation. This is
3254 * only possible when GSO is used for verifying header integrity.
3256 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3258 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3259 netdev_features_t features, bool tx_path)
3261 struct sk_buff *segs;
3263 if (unlikely(skb_needs_check(skb, tx_path))) {
3266 /* We're going to init ->check field in TCP or UDP header */
3267 err = skb_cow_head(skb, 0);
3269 return ERR_PTR(err);
3272 /* Only report GSO partial support if it will enable us to
3273 * support segmentation on this frame without needing additional
3276 if (features & NETIF_F_GSO_PARTIAL) {
3277 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3278 struct net_device *dev = skb->dev;
3280 partial_features |= dev->features & dev->gso_partial_features;
3281 if (!skb_gso_ok(skb, features | partial_features))
3282 features &= ~NETIF_F_GSO_PARTIAL;
3285 BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3286 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3288 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3289 SKB_GSO_CB(skb)->encap_level = 0;
3291 skb_reset_mac_header(skb);
3292 skb_reset_mac_len(skb);
3294 segs = skb_mac_gso_segment(skb, features);
3296 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3297 skb_warn_bad_offload(skb);
3301 EXPORT_SYMBOL(__skb_gso_segment);
3303 /* Take action when hardware reception checksum errors are detected. */
3305 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3307 netdev_err(dev, "hw csum failure\n");
3308 skb_dump(KERN_ERR, skb, true);
3312 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3314 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3316 EXPORT_SYMBOL(netdev_rx_csum_fault);
3319 /* XXX: check that highmem exists at all on the given machine. */
3320 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3322 #ifdef CONFIG_HIGHMEM
3325 if (!(dev->features & NETIF_F_HIGHDMA)) {
3326 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3327 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3329 if (PageHighMem(skb_frag_page(frag)))
3337 /* If MPLS offload request, verify we are testing hardware MPLS features
3338 * instead of standard features for the netdev.
3340 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3341 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3342 netdev_features_t features,
3345 if (eth_p_mpls(type))
3346 features &= skb->dev->mpls_features;
3351 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3352 netdev_features_t features,
3359 static netdev_features_t harmonize_features(struct sk_buff *skb,
3360 netdev_features_t features)
3364 type = skb_network_protocol(skb, NULL);
3365 features = net_mpls_features(skb, features, type);
3367 if (skb->ip_summed != CHECKSUM_NONE &&
3368 !can_checksum_protocol(features, type)) {
3369 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3371 if (illegal_highdma(skb->dev, skb))
3372 features &= ~NETIF_F_SG;
3377 netdev_features_t passthru_features_check(struct sk_buff *skb,
3378 struct net_device *dev,
3379 netdev_features_t features)
3383 EXPORT_SYMBOL(passthru_features_check);
3385 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3386 struct net_device *dev,
3387 netdev_features_t features)
3389 return vlan_features_check(skb, features);
3392 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3393 struct net_device *dev,
3394 netdev_features_t features)
3396 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3398 if (gso_segs > dev->gso_max_segs)
3399 return features & ~NETIF_F_GSO_MASK;
3401 if (!skb_shinfo(skb)->gso_type) {
3402 skb_warn_bad_offload(skb);
3403 return features & ~NETIF_F_GSO_MASK;
3406 /* Support for GSO partial features requires software
3407 * intervention before we can actually process the packets
3408 * so we need to strip support for any partial features now
3409 * and we can pull them back in after we have partially
3410 * segmented the frame.
3412 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3413 features &= ~dev->gso_partial_features;
3415 /* Make sure to clear the IPv4 ID mangling feature if the
3416 * IPv4 header has the potential to be fragmented.
3418 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3419 struct iphdr *iph = skb->encapsulation ?
3420 inner_ip_hdr(skb) : ip_hdr(skb);
3422 if (!(iph->frag_off & htons(IP_DF)))
3423 features &= ~NETIF_F_TSO_MANGLEID;
3429 netdev_features_t netif_skb_features(struct sk_buff *skb)
3431 struct net_device *dev = skb->dev;
3432 netdev_features_t features = dev->features;
3434 if (skb_is_gso(skb))
3435 features = gso_features_check(skb, dev, features);
3437 /* If encapsulation offload request, verify we are testing
3438 * hardware encapsulation features instead of standard
3439 * features for the netdev
3441 if (skb->encapsulation)
3442 features &= dev->hw_enc_features;
3444 if (skb_vlan_tagged(skb))
3445 features = netdev_intersect_features(features,
3446 dev->vlan_features |
3447 NETIF_F_HW_VLAN_CTAG_TX |
3448 NETIF_F_HW_VLAN_STAG_TX);
3450 if (dev->netdev_ops->ndo_features_check)
3451 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3454 features &= dflt_features_check(skb, dev, features);
3456 return harmonize_features(skb, features);
3458 EXPORT_SYMBOL(netif_skb_features);
3460 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3461 struct netdev_queue *txq, bool more)
3466 if (dev_nit_active(dev))
3467 dev_queue_xmit_nit(skb, dev);
3470 PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies);
3471 trace_net_dev_start_xmit(skb, dev);
3472 rc = netdev_start_xmit(skb, dev, txq, more);
3473 trace_net_dev_xmit(skb, rc, dev, len);
3478 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3479 struct netdev_queue *txq, int *ret)
3481 struct sk_buff *skb = first;
3482 int rc = NETDEV_TX_OK;
3485 struct sk_buff *next = skb->next;
3487 skb_mark_not_on_list(skb);
3488 rc = xmit_one(skb, dev, txq, next != NULL);
3489 if (unlikely(!dev_xmit_complete(rc))) {
3495 if (netif_tx_queue_stopped(txq) && skb) {
3496 rc = NETDEV_TX_BUSY;
3506 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3507 netdev_features_t features)
3509 if (skb_vlan_tag_present(skb) &&
3510 !vlan_hw_offload_capable(features, skb->vlan_proto))
3511 skb = __vlan_hwaccel_push_inside(skb);
3515 int skb_csum_hwoffload_help(struct sk_buff *skb,
3516 const netdev_features_t features)
3518 if (unlikely(skb_csum_is_sctp(skb)))
3519 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3520 skb_crc32c_csum_help(skb);
3522 if (features & NETIF_F_HW_CSUM)
3525 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3526 switch (skb->csum_offset) {
3527 case offsetof(struct tcphdr, check):
3528 case offsetof(struct udphdr, check):
3533 return skb_checksum_help(skb);
3535 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3537 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3539 netdev_features_t features;
3541 features = netif_skb_features(skb);
3542 skb = validate_xmit_vlan(skb, features);
3546 skb = sk_validate_xmit_skb(skb, dev);
3550 if (netif_needs_gso(skb, features)) {
3551 struct sk_buff *segs;
3553 segs = skb_gso_segment(skb, features);
3561 if (skb_needs_linearize(skb, features) &&
3562 __skb_linearize(skb))
3565 /* If packet is not checksummed and device does not
3566 * support checksumming for this protocol, complete
3567 * checksumming here.
3569 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3570 if (skb->encapsulation)
3571 skb_set_inner_transport_header(skb,
3572 skb_checksum_start_offset(skb));
3574 skb_set_transport_header(skb,
3575 skb_checksum_start_offset(skb));
3576 if (skb_csum_hwoffload_help(skb, features))
3581 skb = validate_xmit_xfrm(skb, features, again);
3588 atomic_long_inc(&dev->tx_dropped);
3592 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3594 struct sk_buff *next, *head = NULL, *tail;
3596 for (; skb != NULL; skb = next) {
3598 skb_mark_not_on_list(skb);
3600 /* in case skb wont be segmented, point to itself */
3603 skb = validate_xmit_skb(skb, dev, again);
3611 /* If skb was segmented, skb->prev points to
3612 * the last segment. If not, it still contains skb.
3618 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3620 static void qdisc_pkt_len_init(struct sk_buff *skb)
3622 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3624 qdisc_skb_cb(skb)->pkt_len = skb->len;
3626 /* To get more precise estimation of bytes sent on wire,
3627 * we add to pkt_len the headers size of all segments
3629 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3630 unsigned int hdr_len;
3631 u16 gso_segs = shinfo->gso_segs;
3633 /* mac layer + network layer */
3634 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3636 /* + transport layer */
3637 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3638 const struct tcphdr *th;
3639 struct tcphdr _tcphdr;
3641 th = skb_header_pointer(skb, skb_transport_offset(skb),
3642 sizeof(_tcphdr), &_tcphdr);
3644 hdr_len += __tcp_hdrlen(th);
3646 struct udphdr _udphdr;
3648 if (skb_header_pointer(skb, skb_transport_offset(skb),
3649 sizeof(_udphdr), &_udphdr))
3650 hdr_len += sizeof(struct udphdr);
3653 if (shinfo->gso_type & SKB_GSO_DODGY)
3654 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3657 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3661 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3662 struct sk_buff **to_free,
3663 struct netdev_queue *txq)
3667 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3668 if (rc == NET_XMIT_SUCCESS)
3669 trace_qdisc_enqueue(q, txq, skb);
3673 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3674 struct net_device *dev,
3675 struct netdev_queue *txq)
3677 spinlock_t *root_lock = qdisc_lock(q);
3678 struct sk_buff *to_free = NULL;
3682 qdisc_calculate_pkt_len(skb, q);
3684 if (q->flags & TCQ_F_NOLOCK) {
3685 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3686 qdisc_run_begin(q)) {
3687 /* Retest nolock_qdisc_is_empty() within the protection
3688 * of q->seqlock to protect from racing with requeuing.
3690 if (unlikely(!nolock_qdisc_is_empty(q))) {
3691 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3698 qdisc_bstats_cpu_update(q, skb);
3699 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3700 !nolock_qdisc_is_empty(q))
3704 return NET_XMIT_SUCCESS;
3707 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3711 if (unlikely(to_free))
3712 kfree_skb_list(to_free);
3717 * Heuristic to force contended enqueues to serialize on a
3718 * separate lock before trying to get qdisc main lock.
3719 * This permits qdisc->running owner to get the lock more
3720 * often and dequeue packets faster.
3722 contended = qdisc_is_running(q);
3723 if (unlikely(contended))
3724 spin_lock(&q->busylock);
3726 spin_lock(root_lock);
3727 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3728 __qdisc_drop(skb, &to_free);
3730 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3731 qdisc_run_begin(q)) {
3733 * This is a work-conserving queue; there are no old skbs
3734 * waiting to be sent out; and the qdisc is not running -
3735 * xmit the skb directly.
3738 qdisc_bstats_update(q, skb);
3740 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3741 if (unlikely(contended)) {
3742 spin_unlock(&q->busylock);
3749 rc = NET_XMIT_SUCCESS;
3751 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3752 if (qdisc_run_begin(q)) {
3753 if (unlikely(contended)) {
3754 spin_unlock(&q->busylock);
3761 spin_unlock(root_lock);
3762 if (unlikely(to_free))
3763 kfree_skb_list(to_free);
3764 if (unlikely(contended))
3765 spin_unlock(&q->busylock);
3769 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3770 static void skb_update_prio(struct sk_buff *skb)
3772 const struct netprio_map *map;
3773 const struct sock *sk;
3774 unsigned int prioidx;
3778 map = rcu_dereference_bh(skb->dev->priomap);
3781 sk = skb_to_full_sk(skb);
3785 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3787 if (prioidx < map->priomap_len)
3788 skb->priority = map->priomap[prioidx];
3791 #define skb_update_prio(skb)
3795 * dev_loopback_xmit - loop back @skb
3796 * @net: network namespace this loopback is happening in
3797 * @sk: sk needed to be a netfilter okfn
3798 * @skb: buffer to transmit
3800 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3802 skb_reset_mac_header(skb);
3803 __skb_pull(skb, skb_network_offset(skb));
3804 skb->pkt_type = PACKET_LOOPBACK;
3805 if (skb->ip_summed == CHECKSUM_NONE)
3806 skb->ip_summed = CHECKSUM_UNNECESSARY;
3807 WARN_ON(!skb_dst(skb));
3812 EXPORT_SYMBOL(dev_loopback_xmit);
3814 #ifdef CONFIG_NET_EGRESS
3815 static struct sk_buff *
3816 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3818 #ifdef CONFIG_NET_CLS_ACT
3819 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3820 struct tcf_result cl_res;
3825 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3826 qdisc_skb_cb(skb)->mru = 0;
3827 qdisc_skb_cb(skb)->post_ct = false;
3828 mini_qdisc_bstats_cpu_update(miniq, skb);
3830 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
3832 case TC_ACT_RECLASSIFY:
3833 skb->tc_index = TC_H_MIN(cl_res.classid);
3836 mini_qdisc_qstats_cpu_drop(miniq);
3837 *ret = NET_XMIT_DROP;
3843 *ret = NET_XMIT_SUCCESS;
3846 case TC_ACT_REDIRECT:
3847 /* No need to push/pop skb's mac_header here on egress! */
3848 skb_do_redirect(skb);
3849 *ret = NET_XMIT_SUCCESS;
3854 #endif /* CONFIG_NET_CLS_ACT */
3858 #endif /* CONFIG_NET_EGRESS */
3861 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3862 struct xps_dev_maps *dev_maps, unsigned int tci)
3864 int tc = netdev_get_prio_tc_map(dev, skb->priority);
3865 struct xps_map *map;
3866 int queue_index = -1;
3868 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
3871 tci *= dev_maps->num_tc;
3874 map = rcu_dereference(dev_maps->attr_map[tci]);
3877 queue_index = map->queues[0];
3879 queue_index = map->queues[reciprocal_scale(
3880 skb_get_hash(skb), map->len)];
3881 if (unlikely(queue_index >= dev->real_num_tx_queues))
3888 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3889 struct sk_buff *skb)
3892 struct xps_dev_maps *dev_maps;
3893 struct sock *sk = skb->sk;
3894 int queue_index = -1;
3896 if (!static_key_false(&xps_needed))
3900 if (!static_key_false(&xps_rxqs_needed))
3903 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
3905 int tci = sk_rx_queue_get(sk);
3908 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3913 if (queue_index < 0) {
3914 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
3916 unsigned int tci = skb->sender_cpu - 1;
3918 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3930 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3931 struct net_device *sb_dev)
3935 EXPORT_SYMBOL(dev_pick_tx_zero);
3937 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3938 struct net_device *sb_dev)
3940 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
3942 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
3944 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
3945 struct net_device *sb_dev)
3947 struct sock *sk = skb->sk;
3948 int queue_index = sk_tx_queue_get(sk);
3950 sb_dev = sb_dev ? : dev;
3952 if (queue_index < 0 || skb->ooo_okay ||
3953 queue_index >= dev->real_num_tx_queues) {
3954 int new_index = get_xps_queue(dev, sb_dev, skb);
3957 new_index = skb_tx_hash(dev, sb_dev, skb);
3959 if (queue_index != new_index && sk &&
3961 rcu_access_pointer(sk->sk_dst_cache))
3962 sk_tx_queue_set(sk, new_index);
3964 queue_index = new_index;
3969 EXPORT_SYMBOL(netdev_pick_tx);
3971 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
3972 struct sk_buff *skb,
3973 struct net_device *sb_dev)
3975 int queue_index = 0;
3978 u32 sender_cpu = skb->sender_cpu - 1;
3980 if (sender_cpu >= (u32)NR_CPUS)
3981 skb->sender_cpu = raw_smp_processor_id() + 1;
3984 if (dev->real_num_tx_queues != 1) {
3985 const struct net_device_ops *ops = dev->netdev_ops;
3987 if (ops->ndo_select_queue)
3988 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
3990 queue_index = netdev_pick_tx(dev, skb, sb_dev);
3992 queue_index = netdev_cap_txqueue(dev, queue_index);
3995 skb_set_queue_mapping(skb, queue_index);
3996 return netdev_get_tx_queue(dev, queue_index);
4000 * __dev_queue_xmit - transmit a buffer
4001 * @skb: buffer to transmit
4002 * @sb_dev: suboordinate device used for L2 forwarding offload
4004 * Queue a buffer for transmission to a network device. The caller must
4005 * have set the device and priority and built the buffer before calling
4006 * this function. The function can be called from an interrupt.
4008 * A negative errno code is returned on a failure. A success does not
4009 * guarantee the frame will be transmitted as it may be dropped due
4010 * to congestion or traffic shaping.
4012 * -----------------------------------------------------------------------------------
4013 * I notice this method can also return errors from the queue disciplines,
4014 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4017 * Regardless of the return value, the skb is consumed, so it is currently
4018 * difficult to retry a send to this method. (You can bump the ref count
4019 * before sending to hold a reference for retry if you are careful.)
4021 * When calling this method, interrupts MUST be enabled. This is because
4022 * the BH enable code must have IRQs enabled so that it will not deadlock.
4025 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4027 struct net_device *dev = skb->dev;
4028 struct netdev_queue *txq;
4033 skb_reset_mac_header(skb);
4035 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4036 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4038 /* Disable soft irqs for various locks below. Also
4039 * stops preemption for RCU.
4043 skb_update_prio(skb);
4045 qdisc_pkt_len_init(skb);
4046 #ifdef CONFIG_NET_CLS_ACT
4047 skb->tc_at_ingress = 0;
4049 #ifdef CONFIG_NET_EGRESS
4050 if (static_branch_unlikely(&egress_needed_key)) {
4051 if (nf_hook_egress_active()) {
4052 skb = nf_hook_egress(skb, &rc, dev);
4056 nf_skip_egress(skb, true);
4057 skb = sch_handle_egress(skb, &rc, dev);
4060 nf_skip_egress(skb, false);
4063 /* If device/qdisc don't need skb->dst, release it right now while
4064 * its hot in this cpu cache.
4066 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4071 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4072 q = rcu_dereference_bh(txq->qdisc);
4074 trace_net_dev_queue(skb);
4076 rc = __dev_xmit_skb(skb, q, dev, txq);
4080 /* The device has no queue. Common case for software devices:
4081 * loopback, all the sorts of tunnels...
4083 * Really, it is unlikely that netif_tx_lock protection is necessary
4084 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4086 * However, it is possible, that they rely on protection
4089 * Check this and shot the lock. It is not prone from deadlocks.
4090 *Either shot noqueue qdisc, it is even simpler 8)
4092 if (dev->flags & IFF_UP) {
4093 int cpu = smp_processor_id(); /* ok because BHs are off */
4095 if (txq->xmit_lock_owner != cpu) {
4096 if (dev_xmit_recursion())
4097 goto recursion_alert;
4099 skb = validate_xmit_skb(skb, dev, &again);
4103 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4104 HARD_TX_LOCK(dev, txq, cpu);
4106 if (!netif_xmit_stopped(txq)) {
4107 dev_xmit_recursion_inc();
4108 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4109 dev_xmit_recursion_dec();
4110 if (dev_xmit_complete(rc)) {
4111 HARD_TX_UNLOCK(dev, txq);
4115 HARD_TX_UNLOCK(dev, txq);
4116 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4119 /* Recursion is detected! It is possible,
4123 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4129 rcu_read_unlock_bh();
4131 atomic_long_inc(&dev->tx_dropped);
4132 kfree_skb_list(skb);
4135 rcu_read_unlock_bh();
4139 int dev_queue_xmit(struct sk_buff *skb)
4141 return __dev_queue_xmit(skb, NULL);
4143 EXPORT_SYMBOL(dev_queue_xmit);
4145 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4147 return __dev_queue_xmit(skb, sb_dev);
4149 EXPORT_SYMBOL(dev_queue_xmit_accel);
4151 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4153 struct net_device *dev = skb->dev;
4154 struct sk_buff *orig_skb = skb;
4155 struct netdev_queue *txq;
4156 int ret = NETDEV_TX_BUSY;
4159 if (unlikely(!netif_running(dev) ||
4160 !netif_carrier_ok(dev)))
4163 skb = validate_xmit_skb_list(skb, dev, &again);
4164 if (skb != orig_skb)
4167 skb_set_queue_mapping(skb, queue_id);
4168 txq = skb_get_tx_queue(dev, skb);
4169 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4173 dev_xmit_recursion_inc();
4174 HARD_TX_LOCK(dev, txq, smp_processor_id());
4175 if (!netif_xmit_frozen_or_drv_stopped(txq))
4176 ret = netdev_start_xmit(skb, dev, txq, false);
4177 HARD_TX_UNLOCK(dev, txq);
4178 dev_xmit_recursion_dec();
4183 atomic_long_inc(&dev->tx_dropped);
4184 kfree_skb_list(skb);
4185 return NET_XMIT_DROP;
4187 EXPORT_SYMBOL(__dev_direct_xmit);
4189 /*************************************************************************
4191 *************************************************************************/
4193 int netdev_max_backlog __read_mostly = 1000;
4194 EXPORT_SYMBOL(netdev_max_backlog);
4196 int netdev_tstamp_prequeue __read_mostly = 1;
4197 int netdev_budget __read_mostly = 300;
4198 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4199 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4200 int weight_p __read_mostly = 64; /* old backlog weight */
4201 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4202 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4203 int dev_rx_weight __read_mostly = 64;
4204 int dev_tx_weight __read_mostly = 64;
4206 /* Called with irq disabled */
4207 static inline void ____napi_schedule(struct softnet_data *sd,
4208 struct napi_struct *napi)
4210 struct task_struct *thread;
4212 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4213 /* Paired with smp_mb__before_atomic() in
4214 * napi_enable()/dev_set_threaded().
4215 * Use READ_ONCE() to guarantee a complete
4216 * read on napi->thread. Only call
4217 * wake_up_process() when it's not NULL.
4219 thread = READ_ONCE(napi->thread);
4221 /* Avoid doing set_bit() if the thread is in
4222 * INTERRUPTIBLE state, cause napi_thread_wait()
4223 * makes sure to proceed with napi polling
4224 * if the thread is explicitly woken from here.
4226 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4227 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4228 wake_up_process(thread);
4233 list_add_tail(&napi->poll_list, &sd->poll_list);
4234 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4239 /* One global table that all flow-based protocols share. */
4240 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4241 EXPORT_SYMBOL(rps_sock_flow_table);
4242 u32 rps_cpu_mask __read_mostly;
4243 EXPORT_SYMBOL(rps_cpu_mask);
4245 struct static_key_false rps_needed __read_mostly;
4246 EXPORT_SYMBOL(rps_needed);
4247 struct static_key_false rfs_needed __read_mostly;
4248 EXPORT_SYMBOL(rfs_needed);
4250 static struct rps_dev_flow *
4251 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4252 struct rps_dev_flow *rflow, u16 next_cpu)
4254 if (next_cpu < nr_cpu_ids) {
4255 #ifdef CONFIG_RFS_ACCEL
4256 struct netdev_rx_queue *rxqueue;
4257 struct rps_dev_flow_table *flow_table;
4258 struct rps_dev_flow *old_rflow;
4263 /* Should we steer this flow to a different hardware queue? */
4264 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4265 !(dev->features & NETIF_F_NTUPLE))
4267 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4268 if (rxq_index == skb_get_rx_queue(skb))
4271 rxqueue = dev->_rx + rxq_index;
4272 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4275 flow_id = skb_get_hash(skb) & flow_table->mask;
4276 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4277 rxq_index, flow_id);
4281 rflow = &flow_table->flows[flow_id];
4283 if (old_rflow->filter == rflow->filter)
4284 old_rflow->filter = RPS_NO_FILTER;
4288 per_cpu(softnet_data, next_cpu).input_queue_head;
4291 rflow->cpu = next_cpu;
4296 * get_rps_cpu is called from netif_receive_skb and returns the target
4297 * CPU from the RPS map of the receiving queue for a given skb.
4298 * rcu_read_lock must be held on entry.
4300 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4301 struct rps_dev_flow **rflowp)
4303 const struct rps_sock_flow_table *sock_flow_table;
4304 struct netdev_rx_queue *rxqueue = dev->_rx;
4305 struct rps_dev_flow_table *flow_table;
4306 struct rps_map *map;
4311 if (skb_rx_queue_recorded(skb)) {
4312 u16 index = skb_get_rx_queue(skb);
4314 if (unlikely(index >= dev->real_num_rx_queues)) {
4315 WARN_ONCE(dev->real_num_rx_queues > 1,
4316 "%s received packet on queue %u, but number "
4317 "of RX queues is %u\n",
4318 dev->name, index, dev->real_num_rx_queues);
4324 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4326 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4327 map = rcu_dereference(rxqueue->rps_map);
4328 if (!flow_table && !map)
4331 skb_reset_network_header(skb);
4332 hash = skb_get_hash(skb);
4336 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4337 if (flow_table && sock_flow_table) {
4338 struct rps_dev_flow *rflow;
4342 /* First check into global flow table if there is a match */
4343 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4344 if ((ident ^ hash) & ~rps_cpu_mask)
4347 next_cpu = ident & rps_cpu_mask;
4349 /* OK, now we know there is a match,
4350 * we can look at the local (per receive queue) flow table
4352 rflow = &flow_table->flows[hash & flow_table->mask];
4356 * If the desired CPU (where last recvmsg was done) is
4357 * different from current CPU (one in the rx-queue flow
4358 * table entry), switch if one of the following holds:
4359 * - Current CPU is unset (>= nr_cpu_ids).
4360 * - Current CPU is offline.
4361 * - The current CPU's queue tail has advanced beyond the
4362 * last packet that was enqueued using this table entry.
4363 * This guarantees that all previous packets for the flow
4364 * have been dequeued, thus preserving in order delivery.
4366 if (unlikely(tcpu != next_cpu) &&
4367 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4368 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4369 rflow->last_qtail)) >= 0)) {
4371 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4374 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4384 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4385 if (cpu_online(tcpu)) {
4395 #ifdef CONFIG_RFS_ACCEL
4398 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4399 * @dev: Device on which the filter was set
4400 * @rxq_index: RX queue index
4401 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4402 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4404 * Drivers that implement ndo_rx_flow_steer() should periodically call
4405 * this function for each installed filter and remove the filters for
4406 * which it returns %true.
4408 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4409 u32 flow_id, u16 filter_id)
4411 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4412 struct rps_dev_flow_table *flow_table;
4413 struct rps_dev_flow *rflow;
4418 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4419 if (flow_table && flow_id <= flow_table->mask) {
4420 rflow = &flow_table->flows[flow_id];
4421 cpu = READ_ONCE(rflow->cpu);
4422 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4423 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4424 rflow->last_qtail) <
4425 (int)(10 * flow_table->mask)))
4431 EXPORT_SYMBOL(rps_may_expire_flow);
4433 #endif /* CONFIG_RFS_ACCEL */
4435 /* Called from hardirq (IPI) context */
4436 static void rps_trigger_softirq(void *data)
4438 struct softnet_data *sd = data;
4440 ____napi_schedule(sd, &sd->backlog);
4444 #endif /* CONFIG_RPS */
4447 * Check if this softnet_data structure is another cpu one
4448 * If yes, queue it to our IPI list and return 1
4451 static int rps_ipi_queued(struct softnet_data *sd)
4454 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4457 sd->rps_ipi_next = mysd->rps_ipi_list;
4458 mysd->rps_ipi_list = sd;
4460 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4463 #endif /* CONFIG_RPS */
4467 #ifdef CONFIG_NET_FLOW_LIMIT
4468 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4471 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4473 #ifdef CONFIG_NET_FLOW_LIMIT
4474 struct sd_flow_limit *fl;
4475 struct softnet_data *sd;
4476 unsigned int old_flow, new_flow;
4478 if (qlen < (netdev_max_backlog >> 1))
4481 sd = this_cpu_ptr(&softnet_data);
4484 fl = rcu_dereference(sd->flow_limit);
4486 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4487 old_flow = fl->history[fl->history_head];
4488 fl->history[fl->history_head] = new_flow;
4491 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4493 if (likely(fl->buckets[old_flow]))
4494 fl->buckets[old_flow]--;
4496 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4508 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4509 * queue (may be a remote CPU queue).
4511 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4512 unsigned int *qtail)
4514 struct softnet_data *sd;
4515 unsigned long flags;
4518 sd = &per_cpu(softnet_data, cpu);
4520 local_irq_save(flags);
4523 if (!netif_running(skb->dev))
4525 qlen = skb_queue_len(&sd->input_pkt_queue);
4526 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4529 __skb_queue_tail(&sd->input_pkt_queue, skb);
4530 input_queue_tail_incr_save(sd, qtail);
4532 local_irq_restore(flags);
4533 return NET_RX_SUCCESS;
4536 /* Schedule NAPI for backlog device
4537 * We can use non atomic operation since we own the queue lock
4539 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4540 if (!rps_ipi_queued(sd))
4541 ____napi_schedule(sd, &sd->backlog);
4550 local_irq_restore(flags);
4552 atomic_long_inc(&skb->dev->rx_dropped);
4557 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4559 struct net_device *dev = skb->dev;
4560 struct netdev_rx_queue *rxqueue;
4564 if (skb_rx_queue_recorded(skb)) {
4565 u16 index = skb_get_rx_queue(skb);
4567 if (unlikely(index >= dev->real_num_rx_queues)) {
4568 WARN_ONCE(dev->real_num_rx_queues > 1,
4569 "%s received packet on queue %u, but number "
4570 "of RX queues is %u\n",
4571 dev->name, index, dev->real_num_rx_queues);
4573 return rxqueue; /* Return first rxqueue */
4580 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4581 struct bpf_prog *xdp_prog)
4583 void *orig_data, *orig_data_end, *hard_start;
4584 struct netdev_rx_queue *rxqueue;
4585 bool orig_bcast, orig_host;
4586 u32 mac_len, frame_sz;
4587 __be16 orig_eth_type;
4592 /* The XDP program wants to see the packet starting at the MAC
4595 mac_len = skb->data - skb_mac_header(skb);
4596 hard_start = skb->data - skb_headroom(skb);
4598 /* SKB "head" area always have tailroom for skb_shared_info */
4599 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4600 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4602 rxqueue = netif_get_rxqueue(skb);
4603 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4604 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4605 skb_headlen(skb) + mac_len, true);
4607 orig_data_end = xdp->data_end;
4608 orig_data = xdp->data;
4609 eth = (struct ethhdr *)xdp->data;
4610 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4611 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4612 orig_eth_type = eth->h_proto;
4614 act = bpf_prog_run_xdp(xdp_prog, xdp);
4616 /* check if bpf_xdp_adjust_head was used */
4617 off = xdp->data - orig_data;
4620 __skb_pull(skb, off);
4622 __skb_push(skb, -off);
4624 skb->mac_header += off;
4625 skb_reset_network_header(skb);
4628 /* check if bpf_xdp_adjust_tail was used */
4629 off = xdp->data_end - orig_data_end;
4631 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4632 skb->len += off; /* positive on grow, negative on shrink */
4635 /* check if XDP changed eth hdr such SKB needs update */
4636 eth = (struct ethhdr *)xdp->data;
4637 if ((orig_eth_type != eth->h_proto) ||
4638 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4639 skb->dev->dev_addr)) ||
4640 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4641 __skb_push(skb, ETH_HLEN);
4642 skb->pkt_type = PACKET_HOST;
4643 skb->protocol = eth_type_trans(skb, skb->dev);
4646 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4647 * before calling us again on redirect path. We do not call do_redirect
4648 * as we leave that up to the caller.
4650 * Caller is responsible for managing lifetime of skb (i.e. calling
4651 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4656 __skb_push(skb, mac_len);
4659 metalen = xdp->data - xdp->data_meta;
4661 skb_metadata_set(skb, metalen);
4668 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4669 struct xdp_buff *xdp,
4670 struct bpf_prog *xdp_prog)
4674 /* Reinjected packets coming from act_mirred or similar should
4675 * not get XDP generic processing.
4677 if (skb_is_redirected(skb))
4680 /* XDP packets must be linear and must have sufficient headroom
4681 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4682 * native XDP provides, thus we need to do it here as well.
4684 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4685 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4686 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4687 int troom = skb->tail + skb->data_len - skb->end;
4689 /* In case we have to go down the path and also linearize,
4690 * then lets do the pskb_expand_head() work just once here.
4692 if (pskb_expand_head(skb,
4693 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4694 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4696 if (skb_linearize(skb))
4700 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4707 bpf_warn_invalid_xdp_action(act);
4710 trace_xdp_exception(skb->dev, xdp_prog, act);
4721 /* When doing generic XDP we have to bypass the qdisc layer and the
4722 * network taps in order to match in-driver-XDP behavior.
4724 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4726 struct net_device *dev = skb->dev;
4727 struct netdev_queue *txq;
4728 bool free_skb = true;
4731 txq = netdev_core_pick_tx(dev, skb, NULL);
4732 cpu = smp_processor_id();
4733 HARD_TX_LOCK(dev, txq, cpu);
4734 if (!netif_xmit_stopped(txq)) {
4735 rc = netdev_start_xmit(skb, dev, txq, 0);
4736 if (dev_xmit_complete(rc))
4739 HARD_TX_UNLOCK(dev, txq);
4741 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4746 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4748 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4751 struct xdp_buff xdp;
4755 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4756 if (act != XDP_PASS) {
4759 err = xdp_do_generic_redirect(skb->dev, skb,
4765 generic_xdp_tx(skb, xdp_prog);
4776 EXPORT_SYMBOL_GPL(do_xdp_generic);
4778 static int netif_rx_internal(struct sk_buff *skb)
4782 net_timestamp_check(netdev_tstamp_prequeue, skb);
4784 trace_netif_rx(skb);
4787 if (static_branch_unlikely(&rps_needed)) {
4788 struct rps_dev_flow voidflow, *rflow = &voidflow;
4794 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4796 cpu = smp_processor_id();
4798 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4807 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4814 * netif_rx - post buffer to the network code
4815 * @skb: buffer to post
4817 * This function receives a packet from a device driver and queues it for
4818 * the upper (protocol) levels to process. It always succeeds. The buffer
4819 * may be dropped during processing for congestion control or by the
4823 * NET_RX_SUCCESS (no congestion)
4824 * NET_RX_DROP (packet was dropped)
4828 int netif_rx(struct sk_buff *skb)
4832 trace_netif_rx_entry(skb);
4834 ret = netif_rx_internal(skb);
4835 trace_netif_rx_exit(ret);
4839 EXPORT_SYMBOL(netif_rx);
4841 int netif_rx_ni(struct sk_buff *skb)
4845 trace_netif_rx_ni_entry(skb);
4848 err = netif_rx_internal(skb);
4849 if (local_softirq_pending())
4852 trace_netif_rx_ni_exit(err);
4856 EXPORT_SYMBOL(netif_rx_ni);
4858 int netif_rx_any_context(struct sk_buff *skb)
4861 * If invoked from contexts which do not invoke bottom half
4862 * processing either at return from interrupt or when softrqs are
4863 * reenabled, use netif_rx_ni() which invokes bottomhalf processing
4867 return netif_rx(skb);
4869 return netif_rx_ni(skb);
4871 EXPORT_SYMBOL(netif_rx_any_context);
4873 static __latent_entropy void net_tx_action(struct softirq_action *h)
4875 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4877 if (sd->completion_queue) {
4878 struct sk_buff *clist;
4880 local_irq_disable();
4881 clist = sd->completion_queue;
4882 sd->completion_queue = NULL;
4886 struct sk_buff *skb = clist;
4888 clist = clist->next;
4890 WARN_ON(refcount_read(&skb->users));
4891 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4892 trace_consume_skb(skb);
4894 trace_kfree_skb(skb, net_tx_action);
4896 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4899 __kfree_skb_defer(skb);
4903 if (sd->output_queue) {
4906 local_irq_disable();
4907 head = sd->output_queue;
4908 sd->output_queue = NULL;
4909 sd->output_queue_tailp = &sd->output_queue;
4915 struct Qdisc *q = head;
4916 spinlock_t *root_lock = NULL;
4918 head = head->next_sched;
4920 /* We need to make sure head->next_sched is read
4921 * before clearing __QDISC_STATE_SCHED
4923 smp_mb__before_atomic();
4925 if (!(q->flags & TCQ_F_NOLOCK)) {
4926 root_lock = qdisc_lock(q);
4927 spin_lock(root_lock);
4928 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
4930 /* There is a synchronize_net() between
4931 * STATE_DEACTIVATED flag being set and
4932 * qdisc_reset()/some_qdisc_is_busy() in
4933 * dev_deactivate(), so we can safely bail out
4934 * early here to avoid data race between
4935 * qdisc_deactivate() and some_qdisc_is_busy()
4936 * for lockless qdisc.
4938 clear_bit(__QDISC_STATE_SCHED, &q->state);
4942 clear_bit(__QDISC_STATE_SCHED, &q->state);
4945 spin_unlock(root_lock);
4951 xfrm_dev_backlog(sd);
4954 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4955 /* This hook is defined here for ATM LANE */
4956 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4957 unsigned char *addr) __read_mostly;
4958 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4961 static inline struct sk_buff *
4962 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4963 struct net_device *orig_dev, bool *another)
4965 #ifdef CONFIG_NET_CLS_ACT
4966 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4967 struct tcf_result cl_res;
4969 /* If there's at least one ingress present somewhere (so
4970 * we get here via enabled static key), remaining devices
4971 * that are not configured with an ingress qdisc will bail
4978 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4982 qdisc_skb_cb(skb)->pkt_len = skb->len;
4983 qdisc_skb_cb(skb)->mru = 0;
4984 qdisc_skb_cb(skb)->post_ct = false;
4985 skb->tc_at_ingress = 1;
4986 mini_qdisc_bstats_cpu_update(miniq, skb);
4988 switch (tcf_classify(skb, miniq->block, miniq->filter_list, &cl_res, false)) {
4990 case TC_ACT_RECLASSIFY:
4991 skb->tc_index = TC_H_MIN(cl_res.classid);
4994 mini_qdisc_qstats_cpu_drop(miniq);
5002 case TC_ACT_REDIRECT:
5003 /* skb_mac_header check was done by cls/act_bpf, so
5004 * we can safely push the L2 header back before
5005 * redirecting to another netdev
5007 __skb_push(skb, skb->mac_len);
5008 if (skb_do_redirect(skb) == -EAGAIN) {
5009 __skb_pull(skb, skb->mac_len);
5014 case TC_ACT_CONSUMED:
5019 #endif /* CONFIG_NET_CLS_ACT */
5024 * netdev_is_rx_handler_busy - check if receive handler is registered
5025 * @dev: device to check
5027 * Check if a receive handler is already registered for a given device.
5028 * Return true if there one.
5030 * The caller must hold the rtnl_mutex.
5032 bool netdev_is_rx_handler_busy(struct net_device *dev)
5035 return dev && rtnl_dereference(dev->rx_handler);
5037 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5040 * netdev_rx_handler_register - register receive handler
5041 * @dev: device to register a handler for
5042 * @rx_handler: receive handler to register
5043 * @rx_handler_data: data pointer that is used by rx handler
5045 * Register a receive handler for a device. This handler will then be
5046 * called from __netif_receive_skb. A negative errno code is returned
5049 * The caller must hold the rtnl_mutex.
5051 * For a general description of rx_handler, see enum rx_handler_result.
5053 int netdev_rx_handler_register(struct net_device *dev,
5054 rx_handler_func_t *rx_handler,
5055 void *rx_handler_data)
5057 if (netdev_is_rx_handler_busy(dev))
5060 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5063 /* Note: rx_handler_data must be set before rx_handler */
5064 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5065 rcu_assign_pointer(dev->rx_handler, rx_handler);
5069 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5072 * netdev_rx_handler_unregister - unregister receive handler
5073 * @dev: device to unregister a handler from
5075 * Unregister a receive handler from a device.
5077 * The caller must hold the rtnl_mutex.
5079 void netdev_rx_handler_unregister(struct net_device *dev)
5083 RCU_INIT_POINTER(dev->rx_handler, NULL);
5084 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5085 * section has a guarantee to see a non NULL rx_handler_data
5089 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5091 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5094 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5095 * the special handling of PFMEMALLOC skbs.
5097 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5099 switch (skb->protocol) {
5100 case htons(ETH_P_ARP):
5101 case htons(ETH_P_IP):
5102 case htons(ETH_P_IPV6):
5103 case htons(ETH_P_8021Q):
5104 case htons(ETH_P_8021AD):
5111 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5112 int *ret, struct net_device *orig_dev)
5114 if (nf_hook_ingress_active(skb)) {
5118 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5123 ingress_retval = nf_hook_ingress(skb);
5125 return ingress_retval;
5130 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5131 struct packet_type **ppt_prev)
5133 struct packet_type *ptype, *pt_prev;
5134 rx_handler_func_t *rx_handler;
5135 struct sk_buff *skb = *pskb;
5136 struct net_device *orig_dev;
5137 bool deliver_exact = false;
5138 int ret = NET_RX_DROP;
5141 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5143 trace_netif_receive_skb(skb);
5145 orig_dev = skb->dev;
5147 skb_reset_network_header(skb);
5148 if (!skb_transport_header_was_set(skb))
5149 skb_reset_transport_header(skb);
5150 skb_reset_mac_len(skb);
5155 skb->skb_iif = skb->dev->ifindex;
5157 __this_cpu_inc(softnet_data.processed);
5159 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5163 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5166 if (ret2 != XDP_PASS) {
5172 if (eth_type_vlan(skb->protocol)) {
5173 skb = skb_vlan_untag(skb);
5178 if (skb_skip_tc_classify(skb))
5184 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5186 ret = deliver_skb(skb, pt_prev, orig_dev);
5190 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5192 ret = deliver_skb(skb, pt_prev, orig_dev);
5197 #ifdef CONFIG_NET_INGRESS
5198 if (static_branch_unlikely(&ingress_needed_key)) {
5199 bool another = false;
5201 nf_skip_egress(skb, true);
5202 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5209 nf_skip_egress(skb, false);
5210 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5214 skb_reset_redirect(skb);
5216 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5219 if (skb_vlan_tag_present(skb)) {
5221 ret = deliver_skb(skb, pt_prev, orig_dev);
5224 if (vlan_do_receive(&skb))
5226 else if (unlikely(!skb))
5230 rx_handler = rcu_dereference(skb->dev->rx_handler);
5233 ret = deliver_skb(skb, pt_prev, orig_dev);
5236 switch (rx_handler(&skb)) {
5237 case RX_HANDLER_CONSUMED:
5238 ret = NET_RX_SUCCESS;
5240 case RX_HANDLER_ANOTHER:
5242 case RX_HANDLER_EXACT:
5243 deliver_exact = true;
5245 case RX_HANDLER_PASS:
5252 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5254 if (skb_vlan_tag_get_id(skb)) {
5255 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5258 skb->pkt_type = PACKET_OTHERHOST;
5259 } else if (eth_type_vlan(skb->protocol)) {
5260 /* Outer header is 802.1P with vlan 0, inner header is
5261 * 802.1Q or 802.1AD and vlan_do_receive() above could
5262 * not find vlan dev for vlan id 0.
5264 __vlan_hwaccel_clear_tag(skb);
5265 skb = skb_vlan_untag(skb);
5268 if (vlan_do_receive(&skb))
5269 /* After stripping off 802.1P header with vlan 0
5270 * vlan dev is found for inner header.
5273 else if (unlikely(!skb))
5276 /* We have stripped outer 802.1P vlan 0 header.
5277 * But could not find vlan dev.
5278 * check again for vlan id to set OTHERHOST.
5282 /* Note: we might in the future use prio bits
5283 * and set skb->priority like in vlan_do_receive()
5284 * For the time being, just ignore Priority Code Point
5286 __vlan_hwaccel_clear_tag(skb);
5289 type = skb->protocol;
5291 /* deliver only exact match when indicated */
5292 if (likely(!deliver_exact)) {
5293 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5294 &ptype_base[ntohs(type) &
5298 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5299 &orig_dev->ptype_specific);
5301 if (unlikely(skb->dev != orig_dev)) {
5302 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5303 &skb->dev->ptype_specific);
5307 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5309 *ppt_prev = pt_prev;
5313 atomic_long_inc(&skb->dev->rx_dropped);
5315 atomic_long_inc(&skb->dev->rx_nohandler);
5317 /* Jamal, now you will not able to escape explaining
5318 * me how you were going to use this. :-)
5324 /* The invariant here is that if *ppt_prev is not NULL
5325 * then skb should also be non-NULL.
5327 * Apparently *ppt_prev assignment above holds this invariant due to
5328 * skb dereferencing near it.
5334 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5336 struct net_device *orig_dev = skb->dev;
5337 struct packet_type *pt_prev = NULL;
5340 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5342 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5343 skb->dev, pt_prev, orig_dev);
5348 * netif_receive_skb_core - special purpose version of netif_receive_skb
5349 * @skb: buffer to process
5351 * More direct receive version of netif_receive_skb(). It should
5352 * only be used by callers that have a need to skip RPS and Generic XDP.
5353 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5355 * This function may only be called from softirq context and interrupts
5356 * should be enabled.
5358 * Return values (usually ignored):
5359 * NET_RX_SUCCESS: no congestion
5360 * NET_RX_DROP: packet was dropped
5362 int netif_receive_skb_core(struct sk_buff *skb)
5367 ret = __netif_receive_skb_one_core(skb, false);
5372 EXPORT_SYMBOL(netif_receive_skb_core);
5374 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5375 struct packet_type *pt_prev,
5376 struct net_device *orig_dev)
5378 struct sk_buff *skb, *next;
5382 if (list_empty(head))
5384 if (pt_prev->list_func != NULL)
5385 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5386 ip_list_rcv, head, pt_prev, orig_dev);
5388 list_for_each_entry_safe(skb, next, head, list) {
5389 skb_list_del_init(skb);
5390 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5394 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5396 /* Fast-path assumptions:
5397 * - There is no RX handler.
5398 * - Only one packet_type matches.
5399 * If either of these fails, we will end up doing some per-packet
5400 * processing in-line, then handling the 'last ptype' for the whole
5401 * sublist. This can't cause out-of-order delivery to any single ptype,
5402 * because the 'last ptype' must be constant across the sublist, and all
5403 * other ptypes are handled per-packet.
5405 /* Current (common) ptype of sublist */
5406 struct packet_type *pt_curr = NULL;
5407 /* Current (common) orig_dev of sublist */
5408 struct net_device *od_curr = NULL;
5409 struct list_head sublist;
5410 struct sk_buff *skb, *next;
5412 INIT_LIST_HEAD(&sublist);
5413 list_for_each_entry_safe(skb, next, head, list) {
5414 struct net_device *orig_dev = skb->dev;
5415 struct packet_type *pt_prev = NULL;
5417 skb_list_del_init(skb);
5418 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5421 if (pt_curr != pt_prev || od_curr != orig_dev) {
5422 /* dispatch old sublist */
5423 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5424 /* start new sublist */
5425 INIT_LIST_HEAD(&sublist);
5429 list_add_tail(&skb->list, &sublist);
5432 /* dispatch final sublist */
5433 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5436 static int __netif_receive_skb(struct sk_buff *skb)
5440 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5441 unsigned int noreclaim_flag;
5444 * PFMEMALLOC skbs are special, they should
5445 * - be delivered to SOCK_MEMALLOC sockets only
5446 * - stay away from userspace
5447 * - have bounded memory usage
5449 * Use PF_MEMALLOC as this saves us from propagating the allocation
5450 * context down to all allocation sites.
5452 noreclaim_flag = memalloc_noreclaim_save();
5453 ret = __netif_receive_skb_one_core(skb, true);
5454 memalloc_noreclaim_restore(noreclaim_flag);
5456 ret = __netif_receive_skb_one_core(skb, false);
5461 static void __netif_receive_skb_list(struct list_head *head)
5463 unsigned long noreclaim_flag = 0;
5464 struct sk_buff *skb, *next;
5465 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5467 list_for_each_entry_safe(skb, next, head, list) {
5468 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5469 struct list_head sublist;
5471 /* Handle the previous sublist */
5472 list_cut_before(&sublist, head, &skb->list);
5473 if (!list_empty(&sublist))
5474 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5475 pfmemalloc = !pfmemalloc;
5476 /* See comments in __netif_receive_skb */
5478 noreclaim_flag = memalloc_noreclaim_save();
5480 memalloc_noreclaim_restore(noreclaim_flag);
5483 /* Handle the remaining sublist */
5484 if (!list_empty(head))
5485 __netif_receive_skb_list_core(head, pfmemalloc);
5486 /* Restore pflags */
5488 memalloc_noreclaim_restore(noreclaim_flag);
5491 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5493 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5494 struct bpf_prog *new = xdp->prog;
5497 switch (xdp->command) {
5498 case XDP_SETUP_PROG:
5499 rcu_assign_pointer(dev->xdp_prog, new);
5504 static_branch_dec(&generic_xdp_needed_key);
5505 } else if (new && !old) {
5506 static_branch_inc(&generic_xdp_needed_key);
5507 dev_disable_lro(dev);
5508 dev_disable_gro_hw(dev);
5520 static int netif_receive_skb_internal(struct sk_buff *skb)
5524 net_timestamp_check(netdev_tstamp_prequeue, skb);
5526 if (skb_defer_rx_timestamp(skb))
5527 return NET_RX_SUCCESS;
5531 if (static_branch_unlikely(&rps_needed)) {
5532 struct rps_dev_flow voidflow, *rflow = &voidflow;
5533 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5536 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5542 ret = __netif_receive_skb(skb);
5547 void netif_receive_skb_list_internal(struct list_head *head)
5549 struct sk_buff *skb, *next;
5550 struct list_head sublist;
5552 INIT_LIST_HEAD(&sublist);
5553 list_for_each_entry_safe(skb, next, head, list) {
5554 net_timestamp_check(netdev_tstamp_prequeue, skb);
5555 skb_list_del_init(skb);
5556 if (!skb_defer_rx_timestamp(skb))
5557 list_add_tail(&skb->list, &sublist);
5559 list_splice_init(&sublist, head);
5563 if (static_branch_unlikely(&rps_needed)) {
5564 list_for_each_entry_safe(skb, next, head, list) {
5565 struct rps_dev_flow voidflow, *rflow = &voidflow;
5566 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5569 /* Will be handled, remove from list */
5570 skb_list_del_init(skb);
5571 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5576 __netif_receive_skb_list(head);
5581 * netif_receive_skb - process receive buffer from network
5582 * @skb: buffer to process
5584 * netif_receive_skb() is the main receive data processing function.
5585 * It always succeeds. The buffer may be dropped during processing
5586 * for congestion control or by the protocol layers.
5588 * This function may only be called from softirq context and interrupts
5589 * should be enabled.
5591 * Return values (usually ignored):
5592 * NET_RX_SUCCESS: no congestion
5593 * NET_RX_DROP: packet was dropped
5595 int netif_receive_skb(struct sk_buff *skb)
5599 trace_netif_receive_skb_entry(skb);
5601 ret = netif_receive_skb_internal(skb);
5602 trace_netif_receive_skb_exit(ret);
5606 EXPORT_SYMBOL(netif_receive_skb);
5609 * netif_receive_skb_list - process many receive buffers from network
5610 * @head: list of skbs to process.
5612 * Since return value of netif_receive_skb() is normally ignored, and
5613 * wouldn't be meaningful for a list, this function returns void.
5615 * This function may only be called from softirq context and interrupts
5616 * should be enabled.
5618 void netif_receive_skb_list(struct list_head *head)
5620 struct sk_buff *skb;
5622 if (list_empty(head))
5624 if (trace_netif_receive_skb_list_entry_enabled()) {
5625 list_for_each_entry(skb, head, list)
5626 trace_netif_receive_skb_list_entry(skb);
5628 netif_receive_skb_list_internal(head);
5629 trace_netif_receive_skb_list_exit(0);
5631 EXPORT_SYMBOL(netif_receive_skb_list);
5633 static DEFINE_PER_CPU(struct work_struct, flush_works);
5635 /* Network device is going away, flush any packets still pending */
5636 static void flush_backlog(struct work_struct *work)
5638 struct sk_buff *skb, *tmp;
5639 struct softnet_data *sd;
5642 sd = this_cpu_ptr(&softnet_data);
5644 local_irq_disable();
5646 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5647 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5648 __skb_unlink(skb, &sd->input_pkt_queue);
5649 dev_kfree_skb_irq(skb);
5650 input_queue_head_incr(sd);
5656 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5657 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5658 __skb_unlink(skb, &sd->process_queue);
5660 input_queue_head_incr(sd);
5666 static bool flush_required(int cpu)
5668 #if IS_ENABLED(CONFIG_RPS)
5669 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5672 local_irq_disable();
5675 /* as insertion into process_queue happens with the rps lock held,
5676 * process_queue access may race only with dequeue
5678 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5679 !skb_queue_empty_lockless(&sd->process_queue);
5685 /* without RPS we can't safely check input_pkt_queue: during a
5686 * concurrent remote skb_queue_splice() we can detect as empty both
5687 * input_pkt_queue and process_queue even if the latter could end-up
5688 * containing a lot of packets.
5693 static void flush_all_backlogs(void)
5695 static cpumask_t flush_cpus;
5698 /* since we are under rtnl lock protection we can use static data
5699 * for the cpumask and avoid allocating on stack the possibly
5706 cpumask_clear(&flush_cpus);
5707 for_each_online_cpu(cpu) {
5708 if (flush_required(cpu)) {
5709 queue_work_on(cpu, system_highpri_wq,
5710 per_cpu_ptr(&flush_works, cpu));
5711 cpumask_set_cpu(cpu, &flush_cpus);
5715 /* we can have in flight packet[s] on the cpus we are not flushing,
5716 * synchronize_net() in unregister_netdevice_many() will take care of
5719 for_each_cpu(cpu, &flush_cpus)
5720 flush_work(per_cpu_ptr(&flush_works, cpu));
5725 static void net_rps_send_ipi(struct softnet_data *remsd)
5729 struct softnet_data *next = remsd->rps_ipi_next;
5731 if (cpu_online(remsd->cpu))
5732 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5739 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5740 * Note: called with local irq disabled, but exits with local irq enabled.
5742 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5745 struct softnet_data *remsd = sd->rps_ipi_list;
5748 sd->rps_ipi_list = NULL;
5752 /* Send pending IPI's to kick RPS processing on remote cpus. */
5753 net_rps_send_ipi(remsd);
5759 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5762 return sd->rps_ipi_list != NULL;
5768 static int process_backlog(struct napi_struct *napi, int quota)
5770 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5774 /* Check if we have pending ipi, its better to send them now,
5775 * not waiting net_rx_action() end.
5777 if (sd_has_rps_ipi_waiting(sd)) {
5778 local_irq_disable();
5779 net_rps_action_and_irq_enable(sd);
5782 napi->weight = dev_rx_weight;
5784 struct sk_buff *skb;
5786 while ((skb = __skb_dequeue(&sd->process_queue))) {
5788 __netif_receive_skb(skb);
5790 input_queue_head_incr(sd);
5791 if (++work >= quota)
5796 local_irq_disable();
5798 if (skb_queue_empty(&sd->input_pkt_queue)) {
5800 * Inline a custom version of __napi_complete().
5801 * only current cpu owns and manipulates this napi,
5802 * and NAPI_STATE_SCHED is the only possible flag set
5804 * We can use a plain write instead of clear_bit(),
5805 * and we dont need an smp_mb() memory barrier.
5810 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5811 &sd->process_queue);
5821 * __napi_schedule - schedule for receive
5822 * @n: entry to schedule
5824 * The entry's receive function will be scheduled to run.
5825 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5827 void __napi_schedule(struct napi_struct *n)
5829 unsigned long flags;
5831 local_irq_save(flags);
5832 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5833 local_irq_restore(flags);
5835 EXPORT_SYMBOL(__napi_schedule);
5838 * napi_schedule_prep - check if napi can be scheduled
5841 * Test if NAPI routine is already running, and if not mark
5842 * it as running. This is used as a condition variable to
5843 * insure only one NAPI poll instance runs. We also make
5844 * sure there is no pending NAPI disable.
5846 bool napi_schedule_prep(struct napi_struct *n)
5848 unsigned long val, new;
5851 val = READ_ONCE(n->state);
5852 if (unlikely(val & NAPIF_STATE_DISABLE))
5854 new = val | NAPIF_STATE_SCHED;
5856 /* Sets STATE_MISSED bit if STATE_SCHED was already set
5857 * This was suggested by Alexander Duyck, as compiler
5858 * emits better code than :
5859 * if (val & NAPIF_STATE_SCHED)
5860 * new |= NAPIF_STATE_MISSED;
5862 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
5864 } while (cmpxchg(&n->state, val, new) != val);
5866 return !(val & NAPIF_STATE_SCHED);
5868 EXPORT_SYMBOL(napi_schedule_prep);
5871 * __napi_schedule_irqoff - schedule for receive
5872 * @n: entry to schedule
5874 * Variant of __napi_schedule() assuming hard irqs are masked.
5876 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
5877 * because the interrupt disabled assumption might not be true
5878 * due to force-threaded interrupts and spinlock substitution.
5880 void __napi_schedule_irqoff(struct napi_struct *n)
5882 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
5883 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
5887 EXPORT_SYMBOL(__napi_schedule_irqoff);
5889 bool napi_complete_done(struct napi_struct *n, int work_done)
5891 unsigned long flags, val, new, timeout = 0;
5895 * 1) Don't let napi dequeue from the cpu poll list
5896 * just in case its running on a different cpu.
5897 * 2) If we are busy polling, do nothing here, we have
5898 * the guarantee we will be called later.
5900 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
5901 NAPIF_STATE_IN_BUSY_POLL)))
5906 timeout = READ_ONCE(n->dev->gro_flush_timeout);
5907 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
5909 if (n->defer_hard_irqs_count > 0) {
5910 n->defer_hard_irqs_count--;
5911 timeout = READ_ONCE(n->dev->gro_flush_timeout);
5915 if (n->gro_bitmask) {
5916 /* When the NAPI instance uses a timeout and keeps postponing
5917 * it, we need to bound somehow the time packets are kept in
5920 napi_gro_flush(n, !!timeout);
5925 if (unlikely(!list_empty(&n->poll_list))) {
5926 /* If n->poll_list is not empty, we need to mask irqs */
5927 local_irq_save(flags);
5928 list_del_init(&n->poll_list);
5929 local_irq_restore(flags);
5933 val = READ_ONCE(n->state);
5935 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
5937 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
5938 NAPIF_STATE_SCHED_THREADED |
5939 NAPIF_STATE_PREFER_BUSY_POLL);
5941 /* If STATE_MISSED was set, leave STATE_SCHED set,
5942 * because we will call napi->poll() one more time.
5943 * This C code was suggested by Alexander Duyck to help gcc.
5945 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
5947 } while (cmpxchg(&n->state, val, new) != val);
5949 if (unlikely(val & NAPIF_STATE_MISSED)) {
5955 hrtimer_start(&n->timer, ns_to_ktime(timeout),
5956 HRTIMER_MODE_REL_PINNED);
5959 EXPORT_SYMBOL(napi_complete_done);
5961 /* must be called under rcu_read_lock(), as we dont take a reference */
5962 static struct napi_struct *napi_by_id(unsigned int napi_id)
5964 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
5965 struct napi_struct *napi;
5967 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
5968 if (napi->napi_id == napi_id)
5974 #if defined(CONFIG_NET_RX_BUSY_POLL)
5976 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
5978 if (!skip_schedule) {
5979 gro_normal_list(napi);
5980 __napi_schedule(napi);
5984 if (napi->gro_bitmask) {
5985 /* flush too old packets
5986 * If HZ < 1000, flush all packets.
5988 napi_gro_flush(napi, HZ >= 1000);
5991 gro_normal_list(napi);
5992 clear_bit(NAPI_STATE_SCHED, &napi->state);
5995 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
5998 bool skip_schedule = false;
5999 unsigned long timeout;
6002 /* Busy polling means there is a high chance device driver hard irq
6003 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6004 * set in napi_schedule_prep().
6005 * Since we are about to call napi->poll() once more, we can safely
6006 * clear NAPI_STATE_MISSED.
6008 * Note: x86 could use a single "lock and ..." instruction
6009 * to perform these two clear_bit()
6011 clear_bit(NAPI_STATE_MISSED, &napi->state);
6012 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6016 if (prefer_busy_poll) {
6017 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6018 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6019 if (napi->defer_hard_irqs_count && timeout) {
6020 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6021 skip_schedule = true;
6025 /* All we really want here is to re-enable device interrupts.
6026 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6028 rc = napi->poll(napi, budget);
6029 /* We can't gro_normal_list() here, because napi->poll() might have
6030 * rearmed the napi (napi_complete_done()) in which case it could
6031 * already be running on another CPU.
6033 trace_napi_poll(napi, rc, budget);
6034 netpoll_poll_unlock(have_poll_lock);
6036 __busy_poll_stop(napi, skip_schedule);
6040 void napi_busy_loop(unsigned int napi_id,
6041 bool (*loop_end)(void *, unsigned long),
6042 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6044 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6045 int (*napi_poll)(struct napi_struct *napi, int budget);
6046 void *have_poll_lock = NULL;
6047 struct napi_struct *napi;
6054 napi = napi_by_id(napi_id);
6064 unsigned long val = READ_ONCE(napi->state);
6066 /* If multiple threads are competing for this napi,
6067 * we avoid dirtying napi->state as much as we can.
6069 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6070 NAPIF_STATE_IN_BUSY_POLL)) {
6071 if (prefer_busy_poll)
6072 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6075 if (cmpxchg(&napi->state, val,
6076 val | NAPIF_STATE_IN_BUSY_POLL |
6077 NAPIF_STATE_SCHED) != val) {
6078 if (prefer_busy_poll)
6079 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6082 have_poll_lock = netpoll_poll_lock(napi);
6083 napi_poll = napi->poll;
6085 work = napi_poll(napi, budget);
6086 trace_napi_poll(napi, work, budget);
6087 gro_normal_list(napi);
6090 __NET_ADD_STATS(dev_net(napi->dev),
6091 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6094 if (!loop_end || loop_end(loop_end_arg, start_time))
6097 if (unlikely(need_resched())) {
6099 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6103 if (loop_end(loop_end_arg, start_time))
6110 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6115 EXPORT_SYMBOL(napi_busy_loop);
6117 #endif /* CONFIG_NET_RX_BUSY_POLL */
6119 static void napi_hash_add(struct napi_struct *napi)
6121 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6124 spin_lock(&napi_hash_lock);
6126 /* 0..NR_CPUS range is reserved for sender_cpu use */
6128 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6129 napi_gen_id = MIN_NAPI_ID;
6130 } while (napi_by_id(napi_gen_id));
6131 napi->napi_id = napi_gen_id;
6133 hlist_add_head_rcu(&napi->napi_hash_node,
6134 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6136 spin_unlock(&napi_hash_lock);
6139 /* Warning : caller is responsible to make sure rcu grace period
6140 * is respected before freeing memory containing @napi
6142 static void napi_hash_del(struct napi_struct *napi)
6144 spin_lock(&napi_hash_lock);
6146 hlist_del_init_rcu(&napi->napi_hash_node);
6148 spin_unlock(&napi_hash_lock);
6151 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6153 struct napi_struct *napi;
6155 napi = container_of(timer, struct napi_struct, timer);
6157 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6158 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6160 if (!napi_disable_pending(napi) &&
6161 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6162 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6163 __napi_schedule_irqoff(napi);
6166 return HRTIMER_NORESTART;
6169 static void init_gro_hash(struct napi_struct *napi)
6173 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6174 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6175 napi->gro_hash[i].count = 0;
6177 napi->gro_bitmask = 0;
6180 int dev_set_threaded(struct net_device *dev, bool threaded)
6182 struct napi_struct *napi;
6185 if (dev->threaded == threaded)
6189 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6190 if (!napi->thread) {
6191 err = napi_kthread_create(napi);
6200 dev->threaded = threaded;
6202 /* Make sure kthread is created before THREADED bit
6205 smp_mb__before_atomic();
6207 /* Setting/unsetting threaded mode on a napi might not immediately
6208 * take effect, if the current napi instance is actively being
6209 * polled. In this case, the switch between threaded mode and
6210 * softirq mode will happen in the next round of napi_schedule().
6211 * This should not cause hiccups/stalls to the live traffic.
6213 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6215 set_bit(NAPI_STATE_THREADED, &napi->state);
6217 clear_bit(NAPI_STATE_THREADED, &napi->state);
6222 EXPORT_SYMBOL(dev_set_threaded);
6224 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6225 int (*poll)(struct napi_struct *, int), int weight)
6227 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6230 INIT_LIST_HEAD(&napi->poll_list);
6231 INIT_HLIST_NODE(&napi->napi_hash_node);
6232 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6233 napi->timer.function = napi_watchdog;
6234 init_gro_hash(napi);
6236 INIT_LIST_HEAD(&napi->rx_list);
6239 if (weight > NAPI_POLL_WEIGHT)
6240 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6242 napi->weight = weight;
6244 #ifdef CONFIG_NETPOLL
6245 napi->poll_owner = -1;
6247 set_bit(NAPI_STATE_SCHED, &napi->state);
6248 set_bit(NAPI_STATE_NPSVC, &napi->state);
6249 list_add_rcu(&napi->dev_list, &dev->napi_list);
6250 napi_hash_add(napi);
6251 /* Create kthread for this napi if dev->threaded is set.
6252 * Clear dev->threaded if kthread creation failed so that
6253 * threaded mode will not be enabled in napi_enable().
6255 if (dev->threaded && napi_kthread_create(napi))
6258 EXPORT_SYMBOL(netif_napi_add);
6260 void napi_disable(struct napi_struct *n)
6262 unsigned long val, new;
6265 set_bit(NAPI_STATE_DISABLE, &n->state);
6268 val = READ_ONCE(n->state);
6269 if (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6270 usleep_range(20, 200);
6274 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6275 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6277 if (cmpxchg(&n->state, val, new) == val)
6281 hrtimer_cancel(&n->timer);
6283 clear_bit(NAPI_STATE_DISABLE, &n->state);
6285 EXPORT_SYMBOL(napi_disable);
6288 * napi_enable - enable NAPI scheduling
6291 * Resume NAPI from being scheduled on this context.
6292 * Must be paired with napi_disable.
6294 void napi_enable(struct napi_struct *n)
6296 unsigned long val, new;
6299 val = READ_ONCE(n->state);
6300 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6302 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6303 if (n->dev->threaded && n->thread)
6304 new |= NAPIF_STATE_THREADED;
6305 } while (cmpxchg(&n->state, val, new) != val);
6307 EXPORT_SYMBOL(napi_enable);
6309 static void flush_gro_hash(struct napi_struct *napi)
6313 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6314 struct sk_buff *skb, *n;
6316 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6318 napi->gro_hash[i].count = 0;
6322 /* Must be called in process context */
6323 void __netif_napi_del(struct napi_struct *napi)
6325 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6328 napi_hash_del(napi);
6329 list_del_rcu(&napi->dev_list);
6330 napi_free_frags(napi);
6332 flush_gro_hash(napi);
6333 napi->gro_bitmask = 0;
6336 kthread_stop(napi->thread);
6337 napi->thread = NULL;
6340 EXPORT_SYMBOL(__netif_napi_del);
6342 static int __napi_poll(struct napi_struct *n, bool *repoll)
6348 /* This NAPI_STATE_SCHED test is for avoiding a race
6349 * with netpoll's poll_napi(). Only the entity which
6350 * obtains the lock and sees NAPI_STATE_SCHED set will
6351 * actually make the ->poll() call. Therefore we avoid
6352 * accidentally calling ->poll() when NAPI is not scheduled.
6355 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6356 work = n->poll(n, weight);
6357 trace_napi_poll(n, work, weight);
6360 if (unlikely(work > weight))
6361 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6362 n->poll, work, weight);
6364 if (likely(work < weight))
6367 /* Drivers must not modify the NAPI state if they
6368 * consume the entire weight. In such cases this code
6369 * still "owns" the NAPI instance and therefore can
6370 * move the instance around on the list at-will.
6372 if (unlikely(napi_disable_pending(n))) {
6377 /* The NAPI context has more processing work, but busy-polling
6378 * is preferred. Exit early.
6380 if (napi_prefer_busy_poll(n)) {
6381 if (napi_complete_done(n, work)) {
6382 /* If timeout is not set, we need to make sure
6383 * that the NAPI is re-scheduled.
6390 if (n->gro_bitmask) {
6391 /* flush too old packets
6392 * If HZ < 1000, flush all packets.
6394 napi_gro_flush(n, HZ >= 1000);
6399 /* Some drivers may have called napi_schedule
6400 * prior to exhausting their budget.
6402 if (unlikely(!list_empty(&n->poll_list))) {
6403 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6404 n->dev ? n->dev->name : "backlog");
6413 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6415 bool do_repoll = false;
6419 list_del_init(&n->poll_list);
6421 have = netpoll_poll_lock(n);
6423 work = __napi_poll(n, &do_repoll);
6426 list_add_tail(&n->poll_list, repoll);
6428 netpoll_poll_unlock(have);
6433 static int napi_thread_wait(struct napi_struct *napi)
6437 set_current_state(TASK_INTERRUPTIBLE);
6439 while (!kthread_should_stop()) {
6440 /* Testing SCHED_THREADED bit here to make sure the current
6441 * kthread owns this napi and could poll on this napi.
6442 * Testing SCHED bit is not enough because SCHED bit might be
6443 * set by some other busy poll thread or by napi_disable().
6445 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6446 WARN_ON(!list_empty(&napi->poll_list));
6447 __set_current_state(TASK_RUNNING);
6452 /* woken being true indicates this thread owns this napi. */
6454 set_current_state(TASK_INTERRUPTIBLE);
6456 __set_current_state(TASK_RUNNING);
6461 static int napi_threaded_poll(void *data)
6463 struct napi_struct *napi = data;
6466 while (!napi_thread_wait(napi)) {
6468 bool repoll = false;
6472 have = netpoll_poll_lock(napi);
6473 __napi_poll(napi, &repoll);
6474 netpoll_poll_unlock(have);
6487 static __latent_entropy void net_rx_action(struct softirq_action *h)
6489 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6490 unsigned long time_limit = jiffies +
6491 usecs_to_jiffies(netdev_budget_usecs);
6492 int budget = netdev_budget;
6496 local_irq_disable();
6497 list_splice_init(&sd->poll_list, &list);
6501 struct napi_struct *n;
6503 if (list_empty(&list)) {
6504 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6509 n = list_first_entry(&list, struct napi_struct, poll_list);
6510 budget -= napi_poll(n, &repoll);
6512 /* If softirq window is exhausted then punt.
6513 * Allow this to run for 2 jiffies since which will allow
6514 * an average latency of 1.5/HZ.
6516 if (unlikely(budget <= 0 ||
6517 time_after_eq(jiffies, time_limit))) {
6523 local_irq_disable();
6525 list_splice_tail_init(&sd->poll_list, &list);
6526 list_splice_tail(&repoll, &list);
6527 list_splice(&list, &sd->poll_list);
6528 if (!list_empty(&sd->poll_list))
6529 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6531 net_rps_action_and_irq_enable(sd);
6534 struct netdev_adjacent {
6535 struct net_device *dev;
6537 /* upper master flag, there can only be one master device per list */
6540 /* lookup ignore flag */
6543 /* counter for the number of times this device was added to us */
6546 /* private field for the users */
6549 struct list_head list;
6550 struct rcu_head rcu;
6553 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6554 struct list_head *adj_list)
6556 struct netdev_adjacent *adj;
6558 list_for_each_entry(adj, adj_list, list) {
6559 if (adj->dev == adj_dev)
6565 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6566 struct netdev_nested_priv *priv)
6568 struct net_device *dev = (struct net_device *)priv->data;
6570 return upper_dev == dev;
6574 * netdev_has_upper_dev - Check if device is linked to an upper device
6576 * @upper_dev: upper device to check
6578 * Find out if a device is linked to specified upper device and return true
6579 * in case it is. Note that this checks only immediate upper device,
6580 * not through a complete stack of devices. The caller must hold the RTNL lock.
6582 bool netdev_has_upper_dev(struct net_device *dev,
6583 struct net_device *upper_dev)
6585 struct netdev_nested_priv priv = {
6586 .data = (void *)upper_dev,
6591 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6594 EXPORT_SYMBOL(netdev_has_upper_dev);
6597 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6599 * @upper_dev: upper device to check
6601 * Find out if a device is linked to specified upper device and return true
6602 * in case it is. Note that this checks the entire upper device chain.
6603 * The caller must hold rcu lock.
6606 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6607 struct net_device *upper_dev)
6609 struct netdev_nested_priv priv = {
6610 .data = (void *)upper_dev,
6613 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6616 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6619 * netdev_has_any_upper_dev - Check if device is linked to some device
6622 * Find out if a device is linked to an upper device and return true in case
6623 * it is. The caller must hold the RTNL lock.
6625 bool netdev_has_any_upper_dev(struct net_device *dev)
6629 return !list_empty(&dev->adj_list.upper);
6631 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6634 * netdev_master_upper_dev_get - Get master upper device
6637 * Find a master upper device and return pointer to it or NULL in case
6638 * it's not there. The caller must hold the RTNL lock.
6640 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6642 struct netdev_adjacent *upper;
6646 if (list_empty(&dev->adj_list.upper))
6649 upper = list_first_entry(&dev->adj_list.upper,
6650 struct netdev_adjacent, list);
6651 if (likely(upper->master))
6655 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6657 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6659 struct netdev_adjacent *upper;
6663 if (list_empty(&dev->adj_list.upper))
6666 upper = list_first_entry(&dev->adj_list.upper,
6667 struct netdev_adjacent, list);
6668 if (likely(upper->master) && !upper->ignore)
6674 * netdev_has_any_lower_dev - Check if device is linked to some device
6677 * Find out if a device is linked to a lower device and return true in case
6678 * it is. The caller must hold the RTNL lock.
6680 static bool netdev_has_any_lower_dev(struct net_device *dev)
6684 return !list_empty(&dev->adj_list.lower);
6687 void *netdev_adjacent_get_private(struct list_head *adj_list)
6689 struct netdev_adjacent *adj;
6691 adj = list_entry(adj_list, struct netdev_adjacent, list);
6693 return adj->private;
6695 EXPORT_SYMBOL(netdev_adjacent_get_private);
6698 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6700 * @iter: list_head ** of the current position
6702 * Gets the next device from the dev's upper list, starting from iter
6703 * position. The caller must hold RCU read lock.
6705 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6706 struct list_head **iter)
6708 struct netdev_adjacent *upper;
6710 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6712 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6714 if (&upper->list == &dev->adj_list.upper)
6717 *iter = &upper->list;
6721 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6723 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6724 struct list_head **iter,
6727 struct netdev_adjacent *upper;
6729 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6731 if (&upper->list == &dev->adj_list.upper)
6734 *iter = &upper->list;
6735 *ignore = upper->ignore;
6740 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6741 struct list_head **iter)
6743 struct netdev_adjacent *upper;
6745 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6747 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6749 if (&upper->list == &dev->adj_list.upper)
6752 *iter = &upper->list;
6757 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6758 int (*fn)(struct net_device *dev,
6759 struct netdev_nested_priv *priv),
6760 struct netdev_nested_priv *priv)
6762 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6763 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6768 iter = &dev->adj_list.upper;
6772 ret = fn(now, priv);
6779 udev = __netdev_next_upper_dev(now, &iter, &ignore);
6786 niter = &udev->adj_list.upper;
6787 dev_stack[cur] = now;
6788 iter_stack[cur++] = iter;
6795 next = dev_stack[--cur];
6796 niter = iter_stack[cur];
6806 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6807 int (*fn)(struct net_device *dev,
6808 struct netdev_nested_priv *priv),
6809 struct netdev_nested_priv *priv)
6811 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6812 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6816 iter = &dev->adj_list.upper;
6820 ret = fn(now, priv);
6827 udev = netdev_next_upper_dev_rcu(now, &iter);
6832 niter = &udev->adj_list.upper;
6833 dev_stack[cur] = now;
6834 iter_stack[cur++] = iter;
6841 next = dev_stack[--cur];
6842 niter = iter_stack[cur];
6851 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6853 static bool __netdev_has_upper_dev(struct net_device *dev,
6854 struct net_device *upper_dev)
6856 struct netdev_nested_priv priv = {
6858 .data = (void *)upper_dev,
6863 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
6868 * netdev_lower_get_next_private - Get the next ->private from the
6869 * lower neighbour list
6871 * @iter: list_head ** of the current position
6873 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6874 * list, starting from iter position. The caller must hold either hold the
6875 * RTNL lock or its own locking that guarantees that the neighbour lower
6876 * list will remain unchanged.
6878 void *netdev_lower_get_next_private(struct net_device *dev,
6879 struct list_head **iter)
6881 struct netdev_adjacent *lower;
6883 lower = list_entry(*iter, struct netdev_adjacent, list);
6885 if (&lower->list == &dev->adj_list.lower)
6888 *iter = lower->list.next;
6890 return lower->private;
6892 EXPORT_SYMBOL(netdev_lower_get_next_private);
6895 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6896 * lower neighbour list, RCU
6899 * @iter: list_head ** of the current position
6901 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6902 * list, starting from iter position. The caller must hold RCU read lock.
6904 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6905 struct list_head **iter)
6907 struct netdev_adjacent *lower;
6909 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
6911 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6913 if (&lower->list == &dev->adj_list.lower)
6916 *iter = &lower->list;
6918 return lower->private;
6920 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6923 * netdev_lower_get_next - Get the next device from the lower neighbour
6926 * @iter: list_head ** of the current position
6928 * Gets the next netdev_adjacent from the dev's lower neighbour
6929 * list, starting from iter position. The caller must hold RTNL lock or
6930 * its own locking that guarantees that the neighbour lower
6931 * list will remain unchanged.
6933 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6935 struct netdev_adjacent *lower;
6937 lower = list_entry(*iter, struct netdev_adjacent, list);
6939 if (&lower->list == &dev->adj_list.lower)
6942 *iter = lower->list.next;
6946 EXPORT_SYMBOL(netdev_lower_get_next);
6948 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
6949 struct list_head **iter)
6951 struct netdev_adjacent *lower;
6953 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
6955 if (&lower->list == &dev->adj_list.lower)
6958 *iter = &lower->list;
6963 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
6964 struct list_head **iter,
6967 struct netdev_adjacent *lower;
6969 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
6971 if (&lower->list == &dev->adj_list.lower)
6974 *iter = &lower->list;
6975 *ignore = lower->ignore;
6980 int netdev_walk_all_lower_dev(struct net_device *dev,
6981 int (*fn)(struct net_device *dev,
6982 struct netdev_nested_priv *priv),
6983 struct netdev_nested_priv *priv)
6985 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6986 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6990 iter = &dev->adj_list.lower;
6994 ret = fn(now, priv);
7001 ldev = netdev_next_lower_dev(now, &iter);
7006 niter = &ldev->adj_list.lower;
7007 dev_stack[cur] = now;
7008 iter_stack[cur++] = iter;
7015 next = dev_stack[--cur];
7016 niter = iter_stack[cur];
7025 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7027 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7028 int (*fn)(struct net_device *dev,
7029 struct netdev_nested_priv *priv),
7030 struct netdev_nested_priv *priv)
7032 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7033 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7038 iter = &dev->adj_list.lower;
7042 ret = fn(now, priv);
7049 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7056 niter = &ldev->adj_list.lower;
7057 dev_stack[cur] = now;
7058 iter_stack[cur++] = iter;
7065 next = dev_stack[--cur];
7066 niter = iter_stack[cur];
7076 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7077 struct list_head **iter)
7079 struct netdev_adjacent *lower;
7081 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7082 if (&lower->list == &dev->adj_list.lower)
7085 *iter = &lower->list;
7089 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7091 static u8 __netdev_upper_depth(struct net_device *dev)
7093 struct net_device *udev;
7094 struct list_head *iter;
7098 for (iter = &dev->adj_list.upper,
7099 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7101 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7104 if (max_depth < udev->upper_level)
7105 max_depth = udev->upper_level;
7111 static u8 __netdev_lower_depth(struct net_device *dev)
7113 struct net_device *ldev;
7114 struct list_head *iter;
7118 for (iter = &dev->adj_list.lower,
7119 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7121 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7124 if (max_depth < ldev->lower_level)
7125 max_depth = ldev->lower_level;
7131 static int __netdev_update_upper_level(struct net_device *dev,
7132 struct netdev_nested_priv *__unused)
7134 dev->upper_level = __netdev_upper_depth(dev) + 1;
7138 static int __netdev_update_lower_level(struct net_device *dev,
7139 struct netdev_nested_priv *priv)
7141 dev->lower_level = __netdev_lower_depth(dev) + 1;
7143 #ifdef CONFIG_LOCKDEP
7147 if (priv->flags & NESTED_SYNC_IMM)
7148 dev->nested_level = dev->lower_level - 1;
7149 if (priv->flags & NESTED_SYNC_TODO)
7150 net_unlink_todo(dev);
7155 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7156 int (*fn)(struct net_device *dev,
7157 struct netdev_nested_priv *priv),
7158 struct netdev_nested_priv *priv)
7160 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7161 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7165 iter = &dev->adj_list.lower;
7169 ret = fn(now, priv);
7176 ldev = netdev_next_lower_dev_rcu(now, &iter);
7181 niter = &ldev->adj_list.lower;
7182 dev_stack[cur] = now;
7183 iter_stack[cur++] = iter;
7190 next = dev_stack[--cur];
7191 niter = iter_stack[cur];
7200 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7203 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7204 * lower neighbour list, RCU
7208 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7209 * list. The caller must hold RCU read lock.
7211 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7213 struct netdev_adjacent *lower;
7215 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7216 struct netdev_adjacent, list);
7218 return lower->private;
7221 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7224 * netdev_master_upper_dev_get_rcu - Get master upper device
7227 * Find a master upper device and return pointer to it or NULL in case
7228 * it's not there. The caller must hold the RCU read lock.
7230 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7232 struct netdev_adjacent *upper;
7234 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7235 struct netdev_adjacent, list);
7236 if (upper && likely(upper->master))
7240 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7242 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7243 struct net_device *adj_dev,
7244 struct list_head *dev_list)
7246 char linkname[IFNAMSIZ+7];
7248 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7249 "upper_%s" : "lower_%s", adj_dev->name);
7250 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7253 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7255 struct list_head *dev_list)
7257 char linkname[IFNAMSIZ+7];
7259 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7260 "upper_%s" : "lower_%s", name);
7261 sysfs_remove_link(&(dev->dev.kobj), linkname);
7264 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7265 struct net_device *adj_dev,
7266 struct list_head *dev_list)
7268 return (dev_list == &dev->adj_list.upper ||
7269 dev_list == &dev->adj_list.lower) &&
7270 net_eq(dev_net(dev), dev_net(adj_dev));
7273 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7274 struct net_device *adj_dev,
7275 struct list_head *dev_list,
7276 void *private, bool master)
7278 struct netdev_adjacent *adj;
7281 adj = __netdev_find_adj(adj_dev, dev_list);
7285 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7286 dev->name, adj_dev->name, adj->ref_nr);
7291 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7296 adj->master = master;
7298 adj->private = private;
7299 adj->ignore = false;
7302 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7303 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7305 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7306 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7311 /* Ensure that master link is always the first item in list. */
7313 ret = sysfs_create_link(&(dev->dev.kobj),
7314 &(adj_dev->dev.kobj), "master");
7316 goto remove_symlinks;
7318 list_add_rcu(&adj->list, dev_list);
7320 list_add_tail_rcu(&adj->list, dev_list);
7326 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7327 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7335 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7336 struct net_device *adj_dev,
7338 struct list_head *dev_list)
7340 struct netdev_adjacent *adj;
7342 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7343 dev->name, adj_dev->name, ref_nr);
7345 adj = __netdev_find_adj(adj_dev, dev_list);
7348 pr_err("Adjacency does not exist for device %s from %s\n",
7349 dev->name, adj_dev->name);
7354 if (adj->ref_nr > ref_nr) {
7355 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7356 dev->name, adj_dev->name, ref_nr,
7357 adj->ref_nr - ref_nr);
7358 adj->ref_nr -= ref_nr;
7363 sysfs_remove_link(&(dev->dev.kobj), "master");
7365 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7366 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7368 list_del_rcu(&adj->list);
7369 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7370 adj_dev->name, dev->name, adj_dev->name);
7372 kfree_rcu(adj, rcu);
7375 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7376 struct net_device *upper_dev,
7377 struct list_head *up_list,
7378 struct list_head *down_list,
7379 void *private, bool master)
7383 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7388 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7391 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7398 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7399 struct net_device *upper_dev,
7401 struct list_head *up_list,
7402 struct list_head *down_list)
7404 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7405 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7408 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7409 struct net_device *upper_dev,
7410 void *private, bool master)
7412 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7413 &dev->adj_list.upper,
7414 &upper_dev->adj_list.lower,
7418 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7419 struct net_device *upper_dev)
7421 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7422 &dev->adj_list.upper,
7423 &upper_dev->adj_list.lower);
7426 static int __netdev_upper_dev_link(struct net_device *dev,
7427 struct net_device *upper_dev, bool master,
7428 void *upper_priv, void *upper_info,
7429 struct netdev_nested_priv *priv,
7430 struct netlink_ext_ack *extack)
7432 struct netdev_notifier_changeupper_info changeupper_info = {
7437 .upper_dev = upper_dev,
7440 .upper_info = upper_info,
7442 struct net_device *master_dev;
7447 if (dev == upper_dev)
7450 /* To prevent loops, check if dev is not upper device to upper_dev. */
7451 if (__netdev_has_upper_dev(upper_dev, dev))
7454 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7458 if (__netdev_has_upper_dev(dev, upper_dev))
7461 master_dev = __netdev_master_upper_dev_get(dev);
7463 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7466 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7467 &changeupper_info.info);
7468 ret = notifier_to_errno(ret);
7472 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7477 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7478 &changeupper_info.info);
7479 ret = notifier_to_errno(ret);
7483 __netdev_update_upper_level(dev, NULL);
7484 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7486 __netdev_update_lower_level(upper_dev, priv);
7487 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7493 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7499 * netdev_upper_dev_link - Add a link to the upper device
7501 * @upper_dev: new upper device
7502 * @extack: netlink extended ack
7504 * Adds a link to device which is upper to this one. The caller must hold
7505 * the RTNL lock. On a failure a negative errno code is returned.
7506 * On success the reference counts are adjusted and the function
7509 int netdev_upper_dev_link(struct net_device *dev,
7510 struct net_device *upper_dev,
7511 struct netlink_ext_ack *extack)
7513 struct netdev_nested_priv priv = {
7514 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7518 return __netdev_upper_dev_link(dev, upper_dev, false,
7519 NULL, NULL, &priv, extack);
7521 EXPORT_SYMBOL(netdev_upper_dev_link);
7524 * netdev_master_upper_dev_link - Add a master link to the upper device
7526 * @upper_dev: new upper device
7527 * @upper_priv: upper device private
7528 * @upper_info: upper info to be passed down via notifier
7529 * @extack: netlink extended ack
7531 * Adds a link to device which is upper to this one. In this case, only
7532 * one master upper device can be linked, although other non-master devices
7533 * might be linked as well. The caller must hold the RTNL lock.
7534 * On a failure a negative errno code is returned. On success the reference
7535 * counts are adjusted and the function returns zero.
7537 int netdev_master_upper_dev_link(struct net_device *dev,
7538 struct net_device *upper_dev,
7539 void *upper_priv, void *upper_info,
7540 struct netlink_ext_ack *extack)
7542 struct netdev_nested_priv priv = {
7543 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7547 return __netdev_upper_dev_link(dev, upper_dev, true,
7548 upper_priv, upper_info, &priv, extack);
7550 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7552 static void __netdev_upper_dev_unlink(struct net_device *dev,
7553 struct net_device *upper_dev,
7554 struct netdev_nested_priv *priv)
7556 struct netdev_notifier_changeupper_info changeupper_info = {
7560 .upper_dev = upper_dev,
7566 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7568 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7569 &changeupper_info.info);
7571 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7573 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7574 &changeupper_info.info);
7576 __netdev_update_upper_level(dev, NULL);
7577 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7579 __netdev_update_lower_level(upper_dev, priv);
7580 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7585 * netdev_upper_dev_unlink - Removes a link to upper device
7587 * @upper_dev: new upper device
7589 * Removes a link to device which is upper to this one. The caller must hold
7592 void netdev_upper_dev_unlink(struct net_device *dev,
7593 struct net_device *upper_dev)
7595 struct netdev_nested_priv priv = {
7596 .flags = NESTED_SYNC_TODO,
7600 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7602 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7604 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7605 struct net_device *lower_dev,
7608 struct netdev_adjacent *adj;
7610 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7614 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7619 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7620 struct net_device *lower_dev)
7622 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7625 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7626 struct net_device *lower_dev)
7628 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7631 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7632 struct net_device *new_dev,
7633 struct net_device *dev,
7634 struct netlink_ext_ack *extack)
7636 struct netdev_nested_priv priv = {
7645 if (old_dev && new_dev != old_dev)
7646 netdev_adjacent_dev_disable(dev, old_dev);
7647 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7650 if (old_dev && new_dev != old_dev)
7651 netdev_adjacent_dev_enable(dev, old_dev);
7657 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7659 void netdev_adjacent_change_commit(struct net_device *old_dev,
7660 struct net_device *new_dev,
7661 struct net_device *dev)
7663 struct netdev_nested_priv priv = {
7664 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7668 if (!new_dev || !old_dev)
7671 if (new_dev == old_dev)
7674 netdev_adjacent_dev_enable(dev, old_dev);
7675 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7677 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7679 void netdev_adjacent_change_abort(struct net_device *old_dev,
7680 struct net_device *new_dev,
7681 struct net_device *dev)
7683 struct netdev_nested_priv priv = {
7691 if (old_dev && new_dev != old_dev)
7692 netdev_adjacent_dev_enable(dev, old_dev);
7694 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7696 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7699 * netdev_bonding_info_change - Dispatch event about slave change
7701 * @bonding_info: info to dispatch
7703 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7704 * The caller must hold the RTNL lock.
7706 void netdev_bonding_info_change(struct net_device *dev,
7707 struct netdev_bonding_info *bonding_info)
7709 struct netdev_notifier_bonding_info info = {
7713 memcpy(&info.bonding_info, bonding_info,
7714 sizeof(struct netdev_bonding_info));
7715 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7718 EXPORT_SYMBOL(netdev_bonding_info_change);
7721 * netdev_get_xmit_slave - Get the xmit slave of master device
7724 * @all_slaves: assume all the slaves are active
7726 * The reference counters are not incremented so the caller must be
7727 * careful with locks. The caller must hold RCU lock.
7728 * %NULL is returned if no slave is found.
7731 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
7732 struct sk_buff *skb,
7735 const struct net_device_ops *ops = dev->netdev_ops;
7737 if (!ops->ndo_get_xmit_slave)
7739 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
7741 EXPORT_SYMBOL(netdev_get_xmit_slave);
7743 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
7746 const struct net_device_ops *ops = dev->netdev_ops;
7748 if (!ops->ndo_sk_get_lower_dev)
7750 return ops->ndo_sk_get_lower_dev(dev, sk);
7754 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
7758 * %NULL is returned if no lower device is found.
7761 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
7764 struct net_device *lower;
7766 lower = netdev_sk_get_lower_dev(dev, sk);
7769 lower = netdev_sk_get_lower_dev(dev, sk);
7774 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
7776 static void netdev_adjacent_add_links(struct net_device *dev)
7778 struct netdev_adjacent *iter;
7780 struct net *net = dev_net(dev);
7782 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7783 if (!net_eq(net, dev_net(iter->dev)))
7785 netdev_adjacent_sysfs_add(iter->dev, dev,
7786 &iter->dev->adj_list.lower);
7787 netdev_adjacent_sysfs_add(dev, iter->dev,
7788 &dev->adj_list.upper);
7791 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7792 if (!net_eq(net, dev_net(iter->dev)))
7794 netdev_adjacent_sysfs_add(iter->dev, dev,
7795 &iter->dev->adj_list.upper);
7796 netdev_adjacent_sysfs_add(dev, iter->dev,
7797 &dev->adj_list.lower);
7801 static void netdev_adjacent_del_links(struct net_device *dev)
7803 struct netdev_adjacent *iter;
7805 struct net *net = dev_net(dev);
7807 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7808 if (!net_eq(net, dev_net(iter->dev)))
7810 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7811 &iter->dev->adj_list.lower);
7812 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7813 &dev->adj_list.upper);
7816 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7817 if (!net_eq(net, dev_net(iter->dev)))
7819 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7820 &iter->dev->adj_list.upper);
7821 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7822 &dev->adj_list.lower);
7826 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
7828 struct netdev_adjacent *iter;
7830 struct net *net = dev_net(dev);
7832 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7833 if (!net_eq(net, dev_net(iter->dev)))
7835 netdev_adjacent_sysfs_del(iter->dev, oldname,
7836 &iter->dev->adj_list.lower);
7837 netdev_adjacent_sysfs_add(iter->dev, dev,
7838 &iter->dev->adj_list.lower);
7841 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7842 if (!net_eq(net, dev_net(iter->dev)))
7844 netdev_adjacent_sysfs_del(iter->dev, oldname,
7845 &iter->dev->adj_list.upper);
7846 netdev_adjacent_sysfs_add(iter->dev, dev,
7847 &iter->dev->adj_list.upper);
7851 void *netdev_lower_dev_get_private(struct net_device *dev,
7852 struct net_device *lower_dev)
7854 struct netdev_adjacent *lower;
7858 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
7862 return lower->private;
7864 EXPORT_SYMBOL(netdev_lower_dev_get_private);
7868 * netdev_lower_state_changed - Dispatch event about lower device state change
7869 * @lower_dev: device
7870 * @lower_state_info: state to dispatch
7872 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
7873 * The caller must hold the RTNL lock.
7875 void netdev_lower_state_changed(struct net_device *lower_dev,
7876 void *lower_state_info)
7878 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
7879 .info.dev = lower_dev,
7883 changelowerstate_info.lower_state_info = lower_state_info;
7884 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
7885 &changelowerstate_info.info);
7887 EXPORT_SYMBOL(netdev_lower_state_changed);
7889 static void dev_change_rx_flags(struct net_device *dev, int flags)
7891 const struct net_device_ops *ops = dev->netdev_ops;
7893 if (ops->ndo_change_rx_flags)
7894 ops->ndo_change_rx_flags(dev, flags);
7897 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
7899 unsigned int old_flags = dev->flags;
7905 dev->flags |= IFF_PROMISC;
7906 dev->promiscuity += inc;
7907 if (dev->promiscuity == 0) {
7910 * If inc causes overflow, untouch promisc and return error.
7913 dev->flags &= ~IFF_PROMISC;
7915 dev->promiscuity -= inc;
7916 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
7920 if (dev->flags != old_flags) {
7921 pr_info("device %s %s promiscuous mode\n",
7923 dev->flags & IFF_PROMISC ? "entered" : "left");
7924 if (audit_enabled) {
7925 current_uid_gid(&uid, &gid);
7926 audit_log(audit_context(), GFP_ATOMIC,
7927 AUDIT_ANOM_PROMISCUOUS,
7928 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
7929 dev->name, (dev->flags & IFF_PROMISC),
7930 (old_flags & IFF_PROMISC),
7931 from_kuid(&init_user_ns, audit_get_loginuid(current)),
7932 from_kuid(&init_user_ns, uid),
7933 from_kgid(&init_user_ns, gid),
7934 audit_get_sessionid(current));
7937 dev_change_rx_flags(dev, IFF_PROMISC);
7940 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
7945 * dev_set_promiscuity - update promiscuity count on a device
7949 * Add or remove promiscuity from a device. While the count in the device
7950 * remains above zero the interface remains promiscuous. Once it hits zero
7951 * the device reverts back to normal filtering operation. A negative inc
7952 * value is used to drop promiscuity on the device.
7953 * Return 0 if successful or a negative errno code on error.
7955 int dev_set_promiscuity(struct net_device *dev, int inc)
7957 unsigned int old_flags = dev->flags;
7960 err = __dev_set_promiscuity(dev, inc, true);
7963 if (dev->flags != old_flags)
7964 dev_set_rx_mode(dev);
7967 EXPORT_SYMBOL(dev_set_promiscuity);
7969 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
7971 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
7975 dev->flags |= IFF_ALLMULTI;
7976 dev->allmulti += inc;
7977 if (dev->allmulti == 0) {
7980 * If inc causes overflow, untouch allmulti and return error.
7983 dev->flags &= ~IFF_ALLMULTI;
7985 dev->allmulti -= inc;
7986 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
7990 if (dev->flags ^ old_flags) {
7991 dev_change_rx_flags(dev, IFF_ALLMULTI);
7992 dev_set_rx_mode(dev);
7994 __dev_notify_flags(dev, old_flags,
7995 dev->gflags ^ old_gflags);
8001 * dev_set_allmulti - update allmulti count on a device
8005 * Add or remove reception of all multicast frames to a device. While the
8006 * count in the device remains above zero the interface remains listening
8007 * to all interfaces. Once it hits zero the device reverts back to normal
8008 * filtering operation. A negative @inc value is used to drop the counter
8009 * when releasing a resource needing all multicasts.
8010 * Return 0 if successful or a negative errno code on error.
8013 int dev_set_allmulti(struct net_device *dev, int inc)
8015 return __dev_set_allmulti(dev, inc, true);
8017 EXPORT_SYMBOL(dev_set_allmulti);
8020 * Upload unicast and multicast address lists to device and
8021 * configure RX filtering. When the device doesn't support unicast
8022 * filtering it is put in promiscuous mode while unicast addresses
8025 void __dev_set_rx_mode(struct net_device *dev)
8027 const struct net_device_ops *ops = dev->netdev_ops;
8029 /* dev_open will call this function so the list will stay sane. */
8030 if (!(dev->flags&IFF_UP))
8033 if (!netif_device_present(dev))
8036 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8037 /* Unicast addresses changes may only happen under the rtnl,
8038 * therefore calling __dev_set_promiscuity here is safe.
8040 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8041 __dev_set_promiscuity(dev, 1, false);
8042 dev->uc_promisc = true;
8043 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8044 __dev_set_promiscuity(dev, -1, false);
8045 dev->uc_promisc = false;
8049 if (ops->ndo_set_rx_mode)
8050 ops->ndo_set_rx_mode(dev);
8053 void dev_set_rx_mode(struct net_device *dev)
8055 netif_addr_lock_bh(dev);
8056 __dev_set_rx_mode(dev);
8057 netif_addr_unlock_bh(dev);
8061 * dev_get_flags - get flags reported to userspace
8064 * Get the combination of flag bits exported through APIs to userspace.
8066 unsigned int dev_get_flags(const struct net_device *dev)
8070 flags = (dev->flags & ~(IFF_PROMISC |
8075 (dev->gflags & (IFF_PROMISC |
8078 if (netif_running(dev)) {
8079 if (netif_oper_up(dev))
8080 flags |= IFF_RUNNING;
8081 if (netif_carrier_ok(dev))
8082 flags |= IFF_LOWER_UP;
8083 if (netif_dormant(dev))
8084 flags |= IFF_DORMANT;
8089 EXPORT_SYMBOL(dev_get_flags);
8091 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8092 struct netlink_ext_ack *extack)
8094 unsigned int old_flags = dev->flags;
8100 * Set the flags on our device.
8103 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8104 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8106 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8110 * Load in the correct multicast list now the flags have changed.
8113 if ((old_flags ^ flags) & IFF_MULTICAST)
8114 dev_change_rx_flags(dev, IFF_MULTICAST);
8116 dev_set_rx_mode(dev);
8119 * Have we downed the interface. We handle IFF_UP ourselves
8120 * according to user attempts to set it, rather than blindly
8125 if ((old_flags ^ flags) & IFF_UP) {
8126 if (old_flags & IFF_UP)
8129 ret = __dev_open(dev, extack);
8132 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8133 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8134 unsigned int old_flags = dev->flags;
8136 dev->gflags ^= IFF_PROMISC;
8138 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8139 if (dev->flags != old_flags)
8140 dev_set_rx_mode(dev);
8143 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8144 * is important. Some (broken) drivers set IFF_PROMISC, when
8145 * IFF_ALLMULTI is requested not asking us and not reporting.
8147 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8148 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8150 dev->gflags ^= IFF_ALLMULTI;
8151 __dev_set_allmulti(dev, inc, false);
8157 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8158 unsigned int gchanges)
8160 unsigned int changes = dev->flags ^ old_flags;
8163 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8165 if (changes & IFF_UP) {
8166 if (dev->flags & IFF_UP)
8167 call_netdevice_notifiers(NETDEV_UP, dev);
8169 call_netdevice_notifiers(NETDEV_DOWN, dev);
8172 if (dev->flags & IFF_UP &&
8173 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8174 struct netdev_notifier_change_info change_info = {
8178 .flags_changed = changes,
8181 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8186 * dev_change_flags - change device settings
8188 * @flags: device state flags
8189 * @extack: netlink extended ack
8191 * Change settings on device based state flags. The flags are
8192 * in the userspace exported format.
8194 int dev_change_flags(struct net_device *dev, unsigned int flags,
8195 struct netlink_ext_ack *extack)
8198 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8200 ret = __dev_change_flags(dev, flags, extack);
8204 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8205 __dev_notify_flags(dev, old_flags, changes);
8208 EXPORT_SYMBOL(dev_change_flags);
8210 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8212 const struct net_device_ops *ops = dev->netdev_ops;
8214 if (ops->ndo_change_mtu)
8215 return ops->ndo_change_mtu(dev, new_mtu);
8217 /* Pairs with all the lockless reads of dev->mtu in the stack */
8218 WRITE_ONCE(dev->mtu, new_mtu);
8221 EXPORT_SYMBOL(__dev_set_mtu);
8223 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8224 struct netlink_ext_ack *extack)
8226 /* MTU must be positive, and in range */
8227 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8228 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8232 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8233 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8240 * dev_set_mtu_ext - Change maximum transfer unit
8242 * @new_mtu: new transfer unit
8243 * @extack: netlink extended ack
8245 * Change the maximum transfer size of the network device.
8247 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8248 struct netlink_ext_ack *extack)
8252 if (new_mtu == dev->mtu)
8255 err = dev_validate_mtu(dev, new_mtu, extack);
8259 if (!netif_device_present(dev))
8262 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8263 err = notifier_to_errno(err);
8267 orig_mtu = dev->mtu;
8268 err = __dev_set_mtu(dev, new_mtu);
8271 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8273 err = notifier_to_errno(err);
8275 /* setting mtu back and notifying everyone again,
8276 * so that they have a chance to revert changes.
8278 __dev_set_mtu(dev, orig_mtu);
8279 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8286 int dev_set_mtu(struct net_device *dev, int new_mtu)
8288 struct netlink_ext_ack extack;
8291 memset(&extack, 0, sizeof(extack));
8292 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8293 if (err && extack._msg)
8294 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8297 EXPORT_SYMBOL(dev_set_mtu);
8300 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8302 * @new_len: new tx queue length
8304 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8306 unsigned int orig_len = dev->tx_queue_len;
8309 if (new_len != (unsigned int)new_len)
8312 if (new_len != orig_len) {
8313 dev->tx_queue_len = new_len;
8314 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8315 res = notifier_to_errno(res);
8318 res = dev_qdisc_change_tx_queue_len(dev);
8326 netdev_err(dev, "refused to change device tx_queue_len\n");
8327 dev->tx_queue_len = orig_len;
8332 * dev_set_group - Change group this device belongs to
8334 * @new_group: group this device should belong to
8336 void dev_set_group(struct net_device *dev, int new_group)
8338 dev->group = new_group;
8340 EXPORT_SYMBOL(dev_set_group);
8343 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8345 * @addr: new address
8346 * @extack: netlink extended ack
8348 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8349 struct netlink_ext_ack *extack)
8351 struct netdev_notifier_pre_changeaddr_info info = {
8353 .info.extack = extack,
8358 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8359 return notifier_to_errno(rc);
8361 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8364 * dev_set_mac_address - Change Media Access Control Address
8367 * @extack: netlink extended ack
8369 * Change the hardware (MAC) address of the device
8371 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8372 struct netlink_ext_ack *extack)
8374 const struct net_device_ops *ops = dev->netdev_ops;
8377 if (!ops->ndo_set_mac_address)
8379 if (sa->sa_family != dev->type)
8381 if (!netif_device_present(dev))
8383 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8386 err = ops->ndo_set_mac_address(dev, sa);
8389 dev->addr_assign_type = NET_ADDR_SET;
8390 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8391 add_device_randomness(dev->dev_addr, dev->addr_len);
8394 EXPORT_SYMBOL(dev_set_mac_address);
8396 static DECLARE_RWSEM(dev_addr_sem);
8398 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8399 struct netlink_ext_ack *extack)
8403 down_write(&dev_addr_sem);
8404 ret = dev_set_mac_address(dev, sa, extack);
8405 up_write(&dev_addr_sem);
8408 EXPORT_SYMBOL(dev_set_mac_address_user);
8410 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8412 size_t size = sizeof(sa->sa_data);
8413 struct net_device *dev;
8416 down_read(&dev_addr_sem);
8419 dev = dev_get_by_name_rcu(net, dev_name);
8425 memset(sa->sa_data, 0, size);
8427 memcpy(sa->sa_data, dev->dev_addr,
8428 min_t(size_t, size, dev->addr_len));
8429 sa->sa_family = dev->type;
8433 up_read(&dev_addr_sem);
8436 EXPORT_SYMBOL(dev_get_mac_address);
8439 * dev_change_carrier - Change device carrier
8441 * @new_carrier: new value
8443 * Change device carrier
8445 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8447 const struct net_device_ops *ops = dev->netdev_ops;
8449 if (!ops->ndo_change_carrier)
8451 if (!netif_device_present(dev))
8453 return ops->ndo_change_carrier(dev, new_carrier);
8455 EXPORT_SYMBOL(dev_change_carrier);
8458 * dev_get_phys_port_id - Get device physical port ID
8462 * Get device physical port ID
8464 int dev_get_phys_port_id(struct net_device *dev,
8465 struct netdev_phys_item_id *ppid)
8467 const struct net_device_ops *ops = dev->netdev_ops;
8469 if (!ops->ndo_get_phys_port_id)
8471 return ops->ndo_get_phys_port_id(dev, ppid);
8473 EXPORT_SYMBOL(dev_get_phys_port_id);
8476 * dev_get_phys_port_name - Get device physical port name
8479 * @len: limit of bytes to copy to name
8481 * Get device physical port name
8483 int dev_get_phys_port_name(struct net_device *dev,
8484 char *name, size_t len)
8486 const struct net_device_ops *ops = dev->netdev_ops;
8489 if (ops->ndo_get_phys_port_name) {
8490 err = ops->ndo_get_phys_port_name(dev, name, len);
8491 if (err != -EOPNOTSUPP)
8494 return devlink_compat_phys_port_name_get(dev, name, len);
8496 EXPORT_SYMBOL(dev_get_phys_port_name);
8499 * dev_get_port_parent_id - Get the device's port parent identifier
8500 * @dev: network device
8501 * @ppid: pointer to a storage for the port's parent identifier
8502 * @recurse: allow/disallow recursion to lower devices
8504 * Get the devices's port parent identifier
8506 int dev_get_port_parent_id(struct net_device *dev,
8507 struct netdev_phys_item_id *ppid,
8510 const struct net_device_ops *ops = dev->netdev_ops;
8511 struct netdev_phys_item_id first = { };
8512 struct net_device *lower_dev;
8513 struct list_head *iter;
8516 if (ops->ndo_get_port_parent_id) {
8517 err = ops->ndo_get_port_parent_id(dev, ppid);
8518 if (err != -EOPNOTSUPP)
8522 err = devlink_compat_switch_id_get(dev, ppid);
8523 if (!recurse || err != -EOPNOTSUPP)
8526 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8527 err = dev_get_port_parent_id(lower_dev, ppid, true);
8532 else if (memcmp(&first, ppid, sizeof(*ppid)))
8538 EXPORT_SYMBOL(dev_get_port_parent_id);
8541 * netdev_port_same_parent_id - Indicate if two network devices have
8542 * the same port parent identifier
8543 * @a: first network device
8544 * @b: second network device
8546 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8548 struct netdev_phys_item_id a_id = { };
8549 struct netdev_phys_item_id b_id = { };
8551 if (dev_get_port_parent_id(a, &a_id, true) ||
8552 dev_get_port_parent_id(b, &b_id, true))
8555 return netdev_phys_item_id_same(&a_id, &b_id);
8557 EXPORT_SYMBOL(netdev_port_same_parent_id);
8560 * dev_change_proto_down - update protocol port state information
8562 * @proto_down: new value
8564 * This info can be used by switch drivers to set the phys state of the
8567 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8569 const struct net_device_ops *ops = dev->netdev_ops;
8571 if (!ops->ndo_change_proto_down)
8573 if (!netif_device_present(dev))
8575 return ops->ndo_change_proto_down(dev, proto_down);
8577 EXPORT_SYMBOL(dev_change_proto_down);
8580 * dev_change_proto_down_generic - generic implementation for
8581 * ndo_change_proto_down that sets carrier according to
8585 * @proto_down: new value
8587 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8590 netif_carrier_off(dev);
8592 netif_carrier_on(dev);
8593 dev->proto_down = proto_down;
8596 EXPORT_SYMBOL(dev_change_proto_down_generic);
8599 * dev_change_proto_down_reason - proto down reason
8602 * @mask: proto down mask
8603 * @value: proto down value
8605 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8611 dev->proto_down_reason = value;
8613 for_each_set_bit(b, &mask, 32) {
8614 if (value & (1 << b))
8615 dev->proto_down_reason |= BIT(b);
8617 dev->proto_down_reason &= ~BIT(b);
8621 EXPORT_SYMBOL(dev_change_proto_down_reason);
8623 struct bpf_xdp_link {
8624 struct bpf_link link;
8625 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8629 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8631 if (flags & XDP_FLAGS_HW_MODE)
8633 if (flags & XDP_FLAGS_DRV_MODE)
8634 return XDP_MODE_DRV;
8635 if (flags & XDP_FLAGS_SKB_MODE)
8636 return XDP_MODE_SKB;
8637 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
8640 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
8644 return generic_xdp_install;
8647 return dev->netdev_ops->ndo_bpf;
8653 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
8654 enum bpf_xdp_mode mode)
8656 return dev->xdp_state[mode].link;
8659 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
8660 enum bpf_xdp_mode mode)
8662 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
8665 return link->link.prog;
8666 return dev->xdp_state[mode].prog;
8669 u8 dev_xdp_prog_count(struct net_device *dev)
8674 for (i = 0; i < __MAX_XDP_MODE; i++)
8675 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
8679 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
8681 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
8683 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
8685 return prog ? prog->aux->id : 0;
8688 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
8689 struct bpf_xdp_link *link)
8691 dev->xdp_state[mode].link = link;
8692 dev->xdp_state[mode].prog = NULL;
8695 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
8696 struct bpf_prog *prog)
8698 dev->xdp_state[mode].link = NULL;
8699 dev->xdp_state[mode].prog = prog;
8702 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
8703 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
8704 u32 flags, struct bpf_prog *prog)
8706 struct netdev_bpf xdp;
8709 memset(&xdp, 0, sizeof(xdp));
8710 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
8711 xdp.extack = extack;
8715 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
8716 * "moved" into driver), so they don't increment it on their own, but
8717 * they do decrement refcnt when program is detached or replaced.
8718 * Given net_device also owns link/prog, we need to bump refcnt here
8719 * to prevent drivers from underflowing it.
8723 err = bpf_op(dev, &xdp);
8730 if (mode != XDP_MODE_HW)
8731 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
8736 static void dev_xdp_uninstall(struct net_device *dev)
8738 struct bpf_xdp_link *link;
8739 struct bpf_prog *prog;
8740 enum bpf_xdp_mode mode;
8745 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
8746 prog = dev_xdp_prog(dev, mode);
8750 bpf_op = dev_xdp_bpf_op(dev, mode);
8754 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
8756 /* auto-detach link from net device */
8757 link = dev_xdp_link(dev, mode);
8763 dev_xdp_set_link(dev, mode, NULL);
8767 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
8768 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
8769 struct bpf_prog *old_prog, u32 flags)
8771 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
8772 struct bpf_prog *cur_prog;
8773 struct net_device *upper;
8774 struct list_head *iter;
8775 enum bpf_xdp_mode mode;
8781 /* either link or prog attachment, never both */
8782 if (link && (new_prog || old_prog))
8784 /* link supports only XDP mode flags */
8785 if (link && (flags & ~XDP_FLAGS_MODES)) {
8786 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
8789 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
8790 if (num_modes > 1) {
8791 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
8794 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
8795 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
8796 NL_SET_ERR_MSG(extack,
8797 "More than one program loaded, unset mode is ambiguous");
8800 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
8801 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
8802 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
8806 mode = dev_xdp_mode(dev, flags);
8807 /* can't replace attached link */
8808 if (dev_xdp_link(dev, mode)) {
8809 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
8813 /* don't allow if an upper device already has a program */
8814 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
8815 if (dev_xdp_prog_count(upper) > 0) {
8816 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
8821 cur_prog = dev_xdp_prog(dev, mode);
8822 /* can't replace attached prog with link */
8823 if (link && cur_prog) {
8824 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
8827 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
8828 NL_SET_ERR_MSG(extack, "Active program does not match expected");
8832 /* put effective new program into new_prog */
8834 new_prog = link->link.prog;
8837 bool offload = mode == XDP_MODE_HW;
8838 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
8839 ? XDP_MODE_DRV : XDP_MODE_SKB;
8841 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
8842 NL_SET_ERR_MSG(extack, "XDP program already attached");
8845 if (!offload && dev_xdp_prog(dev, other_mode)) {
8846 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
8849 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
8850 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
8853 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
8854 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
8857 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
8858 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
8863 /* don't call drivers if the effective program didn't change */
8864 if (new_prog != cur_prog) {
8865 bpf_op = dev_xdp_bpf_op(dev, mode);
8867 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
8871 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
8877 dev_xdp_set_link(dev, mode, link);
8879 dev_xdp_set_prog(dev, mode, new_prog);
8881 bpf_prog_put(cur_prog);
8886 static int dev_xdp_attach_link(struct net_device *dev,
8887 struct netlink_ext_ack *extack,
8888 struct bpf_xdp_link *link)
8890 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
8893 static int dev_xdp_detach_link(struct net_device *dev,
8894 struct netlink_ext_ack *extack,
8895 struct bpf_xdp_link *link)
8897 enum bpf_xdp_mode mode;
8902 mode = dev_xdp_mode(dev, link->flags);
8903 if (dev_xdp_link(dev, mode) != link)
8906 bpf_op = dev_xdp_bpf_op(dev, mode);
8907 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
8908 dev_xdp_set_link(dev, mode, NULL);
8912 static void bpf_xdp_link_release(struct bpf_link *link)
8914 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
8918 /* if racing with net_device's tear down, xdp_link->dev might be
8919 * already NULL, in which case link was already auto-detached
8921 if (xdp_link->dev) {
8922 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
8923 xdp_link->dev = NULL;
8929 static int bpf_xdp_link_detach(struct bpf_link *link)
8931 bpf_xdp_link_release(link);
8935 static void bpf_xdp_link_dealloc(struct bpf_link *link)
8937 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
8942 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
8943 struct seq_file *seq)
8945 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
8950 ifindex = xdp_link->dev->ifindex;
8953 seq_printf(seq, "ifindex:\t%u\n", ifindex);
8956 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
8957 struct bpf_link_info *info)
8959 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
8964 ifindex = xdp_link->dev->ifindex;
8967 info->xdp.ifindex = ifindex;
8971 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
8972 struct bpf_prog *old_prog)
8974 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
8975 enum bpf_xdp_mode mode;
8981 /* link might have been auto-released already, so fail */
8982 if (!xdp_link->dev) {
8987 if (old_prog && link->prog != old_prog) {
8991 old_prog = link->prog;
8992 if (old_prog == new_prog) {
8993 /* no-op, don't disturb drivers */
8994 bpf_prog_put(new_prog);
8998 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
8999 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9000 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9001 xdp_link->flags, new_prog);
9005 old_prog = xchg(&link->prog, new_prog);
9006 bpf_prog_put(old_prog);
9013 static const struct bpf_link_ops bpf_xdp_link_lops = {
9014 .release = bpf_xdp_link_release,
9015 .dealloc = bpf_xdp_link_dealloc,
9016 .detach = bpf_xdp_link_detach,
9017 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9018 .fill_link_info = bpf_xdp_link_fill_link_info,
9019 .update_prog = bpf_xdp_link_update,
9022 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9024 struct net *net = current->nsproxy->net_ns;
9025 struct bpf_link_primer link_primer;
9026 struct bpf_xdp_link *link;
9027 struct net_device *dev;
9031 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9037 link = kzalloc(sizeof(*link), GFP_USER);
9043 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9045 link->flags = attr->link_create.flags;
9047 err = bpf_link_prime(&link->link, &link_primer);
9053 err = dev_xdp_attach_link(dev, NULL, link);
9058 bpf_link_cleanup(&link_primer);
9062 fd = bpf_link_settle(&link_primer);
9063 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9076 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9078 * @extack: netlink extended ack
9079 * @fd: new program fd or negative value to clear
9080 * @expected_fd: old program fd that userspace expects to replace or clear
9081 * @flags: xdp-related flags
9083 * Set or clear a bpf program for a device
9085 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9086 int fd, int expected_fd, u32 flags)
9088 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9089 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9095 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9096 mode != XDP_MODE_SKB);
9097 if (IS_ERR(new_prog))
9098 return PTR_ERR(new_prog);
9101 if (expected_fd >= 0) {
9102 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9103 mode != XDP_MODE_SKB);
9104 if (IS_ERR(old_prog)) {
9105 err = PTR_ERR(old_prog);
9111 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9114 if (err && new_prog)
9115 bpf_prog_put(new_prog);
9117 bpf_prog_put(old_prog);
9122 * dev_new_index - allocate an ifindex
9123 * @net: the applicable net namespace
9125 * Returns a suitable unique value for a new device interface
9126 * number. The caller must hold the rtnl semaphore or the
9127 * dev_base_lock to be sure it remains unique.
9129 static int dev_new_index(struct net *net)
9131 int ifindex = net->ifindex;
9136 if (!__dev_get_by_index(net, ifindex))
9137 return net->ifindex = ifindex;
9141 /* Delayed registration/unregisteration */
9142 static LIST_HEAD(net_todo_list);
9143 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9145 static void net_set_todo(struct net_device *dev)
9147 list_add_tail(&dev->todo_list, &net_todo_list);
9148 dev_net(dev)->dev_unreg_count++;
9151 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9152 struct net_device *upper, netdev_features_t features)
9154 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9155 netdev_features_t feature;
9158 for_each_netdev_feature(upper_disables, feature_bit) {
9159 feature = __NETIF_F_BIT(feature_bit);
9160 if (!(upper->wanted_features & feature)
9161 && (features & feature)) {
9162 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9163 &feature, upper->name);
9164 features &= ~feature;
9171 static void netdev_sync_lower_features(struct net_device *upper,
9172 struct net_device *lower, netdev_features_t features)
9174 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9175 netdev_features_t feature;
9178 for_each_netdev_feature(upper_disables, feature_bit) {
9179 feature = __NETIF_F_BIT(feature_bit);
9180 if (!(features & feature) && (lower->features & feature)) {
9181 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9182 &feature, lower->name);
9183 lower->wanted_features &= ~feature;
9184 __netdev_update_features(lower);
9186 if (unlikely(lower->features & feature))
9187 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9188 &feature, lower->name);
9190 netdev_features_change(lower);
9195 static netdev_features_t netdev_fix_features(struct net_device *dev,
9196 netdev_features_t features)
9198 /* Fix illegal checksum combinations */
9199 if ((features & NETIF_F_HW_CSUM) &&
9200 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9201 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9202 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9205 /* TSO requires that SG is present as well. */
9206 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9207 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9208 features &= ~NETIF_F_ALL_TSO;
9211 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9212 !(features & NETIF_F_IP_CSUM)) {
9213 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9214 features &= ~NETIF_F_TSO;
9215 features &= ~NETIF_F_TSO_ECN;
9218 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9219 !(features & NETIF_F_IPV6_CSUM)) {
9220 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9221 features &= ~NETIF_F_TSO6;
9224 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9225 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9226 features &= ~NETIF_F_TSO_MANGLEID;
9228 /* TSO ECN requires that TSO is present as well. */
9229 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9230 features &= ~NETIF_F_TSO_ECN;
9232 /* Software GSO depends on SG. */
9233 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9234 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9235 features &= ~NETIF_F_GSO;
9238 /* GSO partial features require GSO partial be set */
9239 if ((features & dev->gso_partial_features) &&
9240 !(features & NETIF_F_GSO_PARTIAL)) {
9242 "Dropping partially supported GSO features since no GSO partial.\n");
9243 features &= ~dev->gso_partial_features;
9246 if (!(features & NETIF_F_RXCSUM)) {
9247 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9248 * successfully merged by hardware must also have the
9249 * checksum verified by hardware. If the user does not
9250 * want to enable RXCSUM, logically, we should disable GRO_HW.
9252 if (features & NETIF_F_GRO_HW) {
9253 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9254 features &= ~NETIF_F_GRO_HW;
9258 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9259 if (features & NETIF_F_RXFCS) {
9260 if (features & NETIF_F_LRO) {
9261 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9262 features &= ~NETIF_F_LRO;
9265 if (features & NETIF_F_GRO_HW) {
9266 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9267 features &= ~NETIF_F_GRO_HW;
9271 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9272 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9273 features &= ~NETIF_F_LRO;
9276 if (features & NETIF_F_HW_TLS_TX) {
9277 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9278 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9279 bool hw_csum = features & NETIF_F_HW_CSUM;
9281 if (!ip_csum && !hw_csum) {
9282 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9283 features &= ~NETIF_F_HW_TLS_TX;
9287 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9288 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9289 features &= ~NETIF_F_HW_TLS_RX;
9295 int __netdev_update_features(struct net_device *dev)
9297 struct net_device *upper, *lower;
9298 netdev_features_t features;
9299 struct list_head *iter;
9304 features = netdev_get_wanted_features(dev);
9306 if (dev->netdev_ops->ndo_fix_features)
9307 features = dev->netdev_ops->ndo_fix_features(dev, features);
9309 /* driver might be less strict about feature dependencies */
9310 features = netdev_fix_features(dev, features);
9312 /* some features can't be enabled if they're off on an upper device */
9313 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9314 features = netdev_sync_upper_features(dev, upper, features);
9316 if (dev->features == features)
9319 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9320 &dev->features, &features);
9322 if (dev->netdev_ops->ndo_set_features)
9323 err = dev->netdev_ops->ndo_set_features(dev, features);
9327 if (unlikely(err < 0)) {
9329 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9330 err, &features, &dev->features);
9331 /* return non-0 since some features might have changed and
9332 * it's better to fire a spurious notification than miss it
9338 /* some features must be disabled on lower devices when disabled
9339 * on an upper device (think: bonding master or bridge)
9341 netdev_for_each_lower_dev(dev, lower, iter)
9342 netdev_sync_lower_features(dev, lower, features);
9345 netdev_features_t diff = features ^ dev->features;
9347 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9348 /* udp_tunnel_{get,drop}_rx_info both need
9349 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9350 * device, or they won't do anything.
9351 * Thus we need to update dev->features
9352 * *before* calling udp_tunnel_get_rx_info,
9353 * but *after* calling udp_tunnel_drop_rx_info.
9355 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9356 dev->features = features;
9357 udp_tunnel_get_rx_info(dev);
9359 udp_tunnel_drop_rx_info(dev);
9363 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9364 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9365 dev->features = features;
9366 err |= vlan_get_rx_ctag_filter_info(dev);
9368 vlan_drop_rx_ctag_filter_info(dev);
9372 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9373 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9374 dev->features = features;
9375 err |= vlan_get_rx_stag_filter_info(dev);
9377 vlan_drop_rx_stag_filter_info(dev);
9381 dev->features = features;
9384 return err < 0 ? 0 : 1;
9388 * netdev_update_features - recalculate device features
9389 * @dev: the device to check
9391 * Recalculate dev->features set and send notifications if it
9392 * has changed. Should be called after driver or hardware dependent
9393 * conditions might have changed that influence the features.
9395 void netdev_update_features(struct net_device *dev)
9397 if (__netdev_update_features(dev))
9398 netdev_features_change(dev);
9400 EXPORT_SYMBOL(netdev_update_features);
9403 * netdev_change_features - recalculate device features
9404 * @dev: the device to check
9406 * Recalculate dev->features set and send notifications even
9407 * if they have not changed. Should be called instead of
9408 * netdev_update_features() if also dev->vlan_features might
9409 * have changed to allow the changes to be propagated to stacked
9412 void netdev_change_features(struct net_device *dev)
9414 __netdev_update_features(dev);
9415 netdev_features_change(dev);
9417 EXPORT_SYMBOL(netdev_change_features);
9420 * netif_stacked_transfer_operstate - transfer operstate
9421 * @rootdev: the root or lower level device to transfer state from
9422 * @dev: the device to transfer operstate to
9424 * Transfer operational state from root to device. This is normally
9425 * called when a stacking relationship exists between the root
9426 * device and the device(a leaf device).
9428 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9429 struct net_device *dev)
9431 if (rootdev->operstate == IF_OPER_DORMANT)
9432 netif_dormant_on(dev);
9434 netif_dormant_off(dev);
9436 if (rootdev->operstate == IF_OPER_TESTING)
9437 netif_testing_on(dev);
9439 netif_testing_off(dev);
9441 if (netif_carrier_ok(rootdev))
9442 netif_carrier_on(dev);
9444 netif_carrier_off(dev);
9446 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9448 static int netif_alloc_rx_queues(struct net_device *dev)
9450 unsigned int i, count = dev->num_rx_queues;
9451 struct netdev_rx_queue *rx;
9452 size_t sz = count * sizeof(*rx);
9457 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9463 for (i = 0; i < count; i++) {
9466 /* XDP RX-queue setup */
9467 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9474 /* Rollback successful reg's and free other resources */
9476 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9482 static void netif_free_rx_queues(struct net_device *dev)
9484 unsigned int i, count = dev->num_rx_queues;
9486 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9490 for (i = 0; i < count; i++)
9491 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9496 static void netdev_init_one_queue(struct net_device *dev,
9497 struct netdev_queue *queue, void *_unused)
9499 /* Initialize queue lock */
9500 spin_lock_init(&queue->_xmit_lock);
9501 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9502 queue->xmit_lock_owner = -1;
9503 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9506 dql_init(&queue->dql, HZ);
9510 static void netif_free_tx_queues(struct net_device *dev)
9515 static int netif_alloc_netdev_queues(struct net_device *dev)
9517 unsigned int count = dev->num_tx_queues;
9518 struct netdev_queue *tx;
9519 size_t sz = count * sizeof(*tx);
9521 if (count < 1 || count > 0xffff)
9524 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9530 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9531 spin_lock_init(&dev->tx_global_lock);
9536 void netif_tx_stop_all_queues(struct net_device *dev)
9540 for (i = 0; i < dev->num_tx_queues; i++) {
9541 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9543 netif_tx_stop_queue(txq);
9546 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9549 * register_netdevice - register a network device
9550 * @dev: device to register
9552 * Take a completed network device structure and add it to the kernel
9553 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9554 * chain. 0 is returned on success. A negative errno code is returned
9555 * on a failure to set up the device, or if the name is a duplicate.
9557 * Callers must hold the rtnl semaphore. You may want
9558 * register_netdev() instead of this.
9561 * The locking appears insufficient to guarantee two parallel registers
9562 * will not get the same name.
9565 int register_netdevice(struct net_device *dev)
9568 struct net *net = dev_net(dev);
9570 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9571 NETDEV_FEATURE_COUNT);
9572 BUG_ON(dev_boot_phase);
9577 /* When net_device's are persistent, this will be fatal. */
9578 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9581 ret = ethtool_check_ops(dev->ethtool_ops);
9585 spin_lock_init(&dev->addr_list_lock);
9586 netdev_set_addr_lockdep_class(dev);
9588 ret = dev_get_valid_name(net, dev, dev->name);
9593 dev->name_node = netdev_name_node_head_alloc(dev);
9594 if (!dev->name_node)
9597 /* Init, if this function is available */
9598 if (dev->netdev_ops->ndo_init) {
9599 ret = dev->netdev_ops->ndo_init(dev);
9607 if (((dev->hw_features | dev->features) &
9608 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9609 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9610 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9611 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
9618 dev->ifindex = dev_new_index(net);
9619 else if (__dev_get_by_index(net, dev->ifindex))
9622 /* Transfer changeable features to wanted_features and enable
9623 * software offloads (GSO and GRO).
9625 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
9626 dev->features |= NETIF_F_SOFT_FEATURES;
9628 if (dev->udp_tunnel_nic_info) {
9629 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9630 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9633 dev->wanted_features = dev->features & dev->hw_features;
9635 if (!(dev->flags & IFF_LOOPBACK))
9636 dev->hw_features |= NETIF_F_NOCACHE_COPY;
9638 /* If IPv4 TCP segmentation offload is supported we should also
9639 * allow the device to enable segmenting the frame with the option
9640 * of ignoring a static IP ID value. This doesn't enable the
9641 * feature itself but allows the user to enable it later.
9643 if (dev->hw_features & NETIF_F_TSO)
9644 dev->hw_features |= NETIF_F_TSO_MANGLEID;
9645 if (dev->vlan_features & NETIF_F_TSO)
9646 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
9647 if (dev->mpls_features & NETIF_F_TSO)
9648 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
9649 if (dev->hw_enc_features & NETIF_F_TSO)
9650 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9652 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
9654 dev->vlan_features |= NETIF_F_HIGHDMA;
9656 /* Make NETIF_F_SG inheritable to tunnel devices.
9658 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
9660 /* Make NETIF_F_SG inheritable to MPLS.
9662 dev->mpls_features |= NETIF_F_SG;
9664 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
9665 ret = notifier_to_errno(ret);
9669 ret = netdev_register_kobject(dev);
9671 dev->reg_state = NETREG_UNREGISTERED;
9674 dev->reg_state = NETREG_REGISTERED;
9676 __netdev_update_features(dev);
9679 * Default initial state at registry is that the
9680 * device is present.
9683 set_bit(__LINK_STATE_PRESENT, &dev->state);
9685 linkwatch_init_dev(dev);
9687 dev_init_scheduler(dev);
9689 list_netdevice(dev);
9690 add_device_randomness(dev->dev_addr, dev->addr_len);
9692 /* If the device has permanent device address, driver should
9693 * set dev_addr and also addr_assign_type should be set to
9694 * NET_ADDR_PERM (default value).
9696 if (dev->addr_assign_type == NET_ADDR_PERM)
9697 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
9699 /* Notify protocols, that a new device appeared. */
9700 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
9701 ret = notifier_to_errno(ret);
9703 /* Expect explicit free_netdev() on failure */
9704 dev->needs_free_netdev = false;
9705 unregister_netdevice_queue(dev, NULL);
9709 * Prevent userspace races by waiting until the network
9710 * device is fully setup before sending notifications.
9712 if (!dev->rtnl_link_ops ||
9713 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9714 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9720 if (dev->netdev_ops->ndo_uninit)
9721 dev->netdev_ops->ndo_uninit(dev);
9722 if (dev->priv_destructor)
9723 dev->priv_destructor(dev);
9725 netdev_name_node_free(dev->name_node);
9728 EXPORT_SYMBOL(register_netdevice);
9731 * init_dummy_netdev - init a dummy network device for NAPI
9732 * @dev: device to init
9734 * This takes a network device structure and initialize the minimum
9735 * amount of fields so it can be used to schedule NAPI polls without
9736 * registering a full blown interface. This is to be used by drivers
9737 * that need to tie several hardware interfaces to a single NAPI
9738 * poll scheduler due to HW limitations.
9740 int init_dummy_netdev(struct net_device *dev)
9742 /* Clear everything. Note we don't initialize spinlocks
9743 * are they aren't supposed to be taken by any of the
9744 * NAPI code and this dummy netdev is supposed to be
9745 * only ever used for NAPI polls
9747 memset(dev, 0, sizeof(struct net_device));
9749 /* make sure we BUG if trying to hit standard
9750 * register/unregister code path
9752 dev->reg_state = NETREG_DUMMY;
9754 /* NAPI wants this */
9755 INIT_LIST_HEAD(&dev->napi_list);
9757 /* a dummy interface is started by default */
9758 set_bit(__LINK_STATE_PRESENT, &dev->state);
9759 set_bit(__LINK_STATE_START, &dev->state);
9761 /* napi_busy_loop stats accounting wants this */
9762 dev_net_set(dev, &init_net);
9764 /* Note : We dont allocate pcpu_refcnt for dummy devices,
9765 * because users of this 'device' dont need to change
9771 EXPORT_SYMBOL_GPL(init_dummy_netdev);
9775 * register_netdev - register a network device
9776 * @dev: device to register
9778 * Take a completed network device structure and add it to the kernel
9779 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9780 * chain. 0 is returned on success. A negative errno code is returned
9781 * on a failure to set up the device, or if the name is a duplicate.
9783 * This is a wrapper around register_netdevice that takes the rtnl semaphore
9784 * and expands the device name if you passed a format string to
9787 int register_netdev(struct net_device *dev)
9791 if (rtnl_lock_killable())
9793 err = register_netdevice(dev);
9797 EXPORT_SYMBOL(register_netdev);
9799 int netdev_refcnt_read(const struct net_device *dev)
9801 #ifdef CONFIG_PCPU_DEV_REFCNT
9804 for_each_possible_cpu(i)
9805 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
9808 return refcount_read(&dev->dev_refcnt);
9811 EXPORT_SYMBOL(netdev_refcnt_read);
9813 int netdev_unregister_timeout_secs __read_mostly = 10;
9815 #define WAIT_REFS_MIN_MSECS 1
9816 #define WAIT_REFS_MAX_MSECS 250
9818 * netdev_wait_allrefs - wait until all references are gone.
9819 * @dev: target net_device
9821 * This is called when unregistering network devices.
9823 * Any protocol or device that holds a reference should register
9824 * for netdevice notification, and cleanup and put back the
9825 * reference if they receive an UNREGISTER event.
9826 * We can get stuck here if buggy protocols don't correctly
9829 static void netdev_wait_allrefs(struct net_device *dev)
9831 unsigned long rebroadcast_time, warning_time;
9832 int wait = 0, refcnt;
9834 linkwatch_forget_dev(dev);
9836 rebroadcast_time = warning_time = jiffies;
9837 refcnt = netdev_refcnt_read(dev);
9839 while (refcnt != 1) {
9840 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
9843 /* Rebroadcast unregister notification */
9844 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9850 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
9852 /* We must not have linkwatch events
9853 * pending on unregister. If this
9854 * happens, we simply run the queue
9855 * unscheduled, resulting in a noop
9858 linkwatch_run_queue();
9863 rebroadcast_time = jiffies;
9868 wait = WAIT_REFS_MIN_MSECS;
9871 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
9874 refcnt = netdev_refcnt_read(dev);
9877 time_after(jiffies, warning_time +
9878 netdev_unregister_timeout_secs * HZ)) {
9879 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
9881 warning_time = jiffies;
9890 * register_netdevice(x1);
9891 * register_netdevice(x2);
9893 * unregister_netdevice(y1);
9894 * unregister_netdevice(y2);
9900 * We are invoked by rtnl_unlock().
9901 * This allows us to deal with problems:
9902 * 1) We can delete sysfs objects which invoke hotplug
9903 * without deadlocking with linkwatch via keventd.
9904 * 2) Since we run with the RTNL semaphore not held, we can sleep
9905 * safely in order to wait for the netdev refcnt to drop to zero.
9907 * We must not return until all unregister events added during
9908 * the interval the lock was held have been completed.
9910 void netdev_run_todo(void)
9912 struct list_head list;
9913 #ifdef CONFIG_LOCKDEP
9914 struct list_head unlink_list;
9916 list_replace_init(&net_unlink_list, &unlink_list);
9918 while (!list_empty(&unlink_list)) {
9919 struct net_device *dev = list_first_entry(&unlink_list,
9922 list_del_init(&dev->unlink_list);
9923 dev->nested_level = dev->lower_level - 1;
9927 /* Snapshot list, allow later requests */
9928 list_replace_init(&net_todo_list, &list);
9933 /* Wait for rcu callbacks to finish before next phase */
9934 if (!list_empty(&list))
9937 while (!list_empty(&list)) {
9938 struct net_device *dev
9939 = list_first_entry(&list, struct net_device, todo_list);
9940 list_del(&dev->todo_list);
9942 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
9943 pr_err("network todo '%s' but state %d\n",
9944 dev->name, dev->reg_state);
9949 dev->reg_state = NETREG_UNREGISTERED;
9951 netdev_wait_allrefs(dev);
9954 BUG_ON(netdev_refcnt_read(dev) != 1);
9955 BUG_ON(!list_empty(&dev->ptype_all));
9956 BUG_ON(!list_empty(&dev->ptype_specific));
9957 WARN_ON(rcu_access_pointer(dev->ip_ptr));
9958 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
9959 #if IS_ENABLED(CONFIG_DECNET)
9960 WARN_ON(dev->dn_ptr);
9962 if (dev->priv_destructor)
9963 dev->priv_destructor(dev);
9964 if (dev->needs_free_netdev)
9967 /* Report a network device has been unregistered */
9969 dev_net(dev)->dev_unreg_count--;
9971 wake_up(&netdev_unregistering_wq);
9973 /* Free network device */
9974 kobject_put(&dev->dev.kobj);
9978 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
9979 * all the same fields in the same order as net_device_stats, with only
9980 * the type differing, but rtnl_link_stats64 may have additional fields
9981 * at the end for newer counters.
9983 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
9984 const struct net_device_stats *netdev_stats)
9986 #if BITS_PER_LONG == 64
9987 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
9988 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
9989 /* zero out counters that only exist in rtnl_link_stats64 */
9990 memset((char *)stats64 + sizeof(*netdev_stats), 0,
9991 sizeof(*stats64) - sizeof(*netdev_stats));
9993 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
9994 const unsigned long *src = (const unsigned long *)netdev_stats;
9995 u64 *dst = (u64 *)stats64;
9997 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
9998 for (i = 0; i < n; i++)
10000 /* zero out counters that only exist in rtnl_link_stats64 */
10001 memset((char *)stats64 + n * sizeof(u64), 0,
10002 sizeof(*stats64) - n * sizeof(u64));
10005 EXPORT_SYMBOL(netdev_stats_to_stats64);
10008 * dev_get_stats - get network device statistics
10009 * @dev: device to get statistics from
10010 * @storage: place to store stats
10012 * Get network statistics from device. Return @storage.
10013 * The device driver may provide its own method by setting
10014 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10015 * otherwise the internal statistics structure is used.
10017 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10018 struct rtnl_link_stats64 *storage)
10020 const struct net_device_ops *ops = dev->netdev_ops;
10022 if (ops->ndo_get_stats64) {
10023 memset(storage, 0, sizeof(*storage));
10024 ops->ndo_get_stats64(dev, storage);
10025 } else if (ops->ndo_get_stats) {
10026 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10028 netdev_stats_to_stats64(storage, &dev->stats);
10030 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
10031 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
10032 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
10035 EXPORT_SYMBOL(dev_get_stats);
10038 * dev_fetch_sw_netstats - get per-cpu network device statistics
10039 * @s: place to store stats
10040 * @netstats: per-cpu network stats to read from
10042 * Read per-cpu network statistics and populate the related fields in @s.
10044 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10045 const struct pcpu_sw_netstats __percpu *netstats)
10049 for_each_possible_cpu(cpu) {
10050 const struct pcpu_sw_netstats *stats;
10051 struct pcpu_sw_netstats tmp;
10052 unsigned int start;
10054 stats = per_cpu_ptr(netstats, cpu);
10056 start = u64_stats_fetch_begin_irq(&stats->syncp);
10057 tmp.rx_packets = stats->rx_packets;
10058 tmp.rx_bytes = stats->rx_bytes;
10059 tmp.tx_packets = stats->tx_packets;
10060 tmp.tx_bytes = stats->tx_bytes;
10061 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
10063 s->rx_packets += tmp.rx_packets;
10064 s->rx_bytes += tmp.rx_bytes;
10065 s->tx_packets += tmp.tx_packets;
10066 s->tx_bytes += tmp.tx_bytes;
10069 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10072 * dev_get_tstats64 - ndo_get_stats64 implementation
10073 * @dev: device to get statistics from
10074 * @s: place to store stats
10076 * Populate @s from dev->stats and dev->tstats. Can be used as
10077 * ndo_get_stats64() callback.
10079 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10081 netdev_stats_to_stats64(s, &dev->stats);
10082 dev_fetch_sw_netstats(s, dev->tstats);
10084 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10086 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10088 struct netdev_queue *queue = dev_ingress_queue(dev);
10090 #ifdef CONFIG_NET_CLS_ACT
10093 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10096 netdev_init_one_queue(dev, queue, NULL);
10097 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10098 queue->qdisc_sleeping = &noop_qdisc;
10099 rcu_assign_pointer(dev->ingress_queue, queue);
10104 static const struct ethtool_ops default_ethtool_ops;
10106 void netdev_set_default_ethtool_ops(struct net_device *dev,
10107 const struct ethtool_ops *ops)
10109 if (dev->ethtool_ops == &default_ethtool_ops)
10110 dev->ethtool_ops = ops;
10112 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10114 void netdev_freemem(struct net_device *dev)
10116 char *addr = (char *)dev - dev->padded;
10122 * alloc_netdev_mqs - allocate network device
10123 * @sizeof_priv: size of private data to allocate space for
10124 * @name: device name format string
10125 * @name_assign_type: origin of device name
10126 * @setup: callback to initialize device
10127 * @txqs: the number of TX subqueues to allocate
10128 * @rxqs: the number of RX subqueues to allocate
10130 * Allocates a struct net_device with private data area for driver use
10131 * and performs basic initialization. Also allocates subqueue structs
10132 * for each queue on the device.
10134 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10135 unsigned char name_assign_type,
10136 void (*setup)(struct net_device *),
10137 unsigned int txqs, unsigned int rxqs)
10139 struct net_device *dev;
10140 unsigned int alloc_size;
10141 struct net_device *p;
10143 BUG_ON(strlen(name) >= sizeof(dev->name));
10146 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10151 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10155 alloc_size = sizeof(struct net_device);
10157 /* ensure 32-byte alignment of private area */
10158 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10159 alloc_size += sizeof_priv;
10161 /* ensure 32-byte alignment of whole construct */
10162 alloc_size += NETDEV_ALIGN - 1;
10164 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10168 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10169 dev->padded = (char *)dev - (char *)p;
10171 #ifdef CONFIG_PCPU_DEV_REFCNT
10172 dev->pcpu_refcnt = alloc_percpu(int);
10173 if (!dev->pcpu_refcnt)
10177 refcount_set(&dev->dev_refcnt, 1);
10180 if (dev_addr_init(dev))
10186 dev_net_set(dev, &init_net);
10188 dev->gso_max_size = GSO_MAX_SIZE;
10189 dev->gso_max_segs = GSO_MAX_SEGS;
10190 dev->upper_level = 1;
10191 dev->lower_level = 1;
10192 #ifdef CONFIG_LOCKDEP
10193 dev->nested_level = 0;
10194 INIT_LIST_HEAD(&dev->unlink_list);
10197 INIT_LIST_HEAD(&dev->napi_list);
10198 INIT_LIST_HEAD(&dev->unreg_list);
10199 INIT_LIST_HEAD(&dev->close_list);
10200 INIT_LIST_HEAD(&dev->link_watch_list);
10201 INIT_LIST_HEAD(&dev->adj_list.upper);
10202 INIT_LIST_HEAD(&dev->adj_list.lower);
10203 INIT_LIST_HEAD(&dev->ptype_all);
10204 INIT_LIST_HEAD(&dev->ptype_specific);
10205 INIT_LIST_HEAD(&dev->net_notifier_list);
10206 #ifdef CONFIG_NET_SCHED
10207 hash_init(dev->qdisc_hash);
10209 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10212 if (!dev->tx_queue_len) {
10213 dev->priv_flags |= IFF_NO_QUEUE;
10214 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10217 dev->num_tx_queues = txqs;
10218 dev->real_num_tx_queues = txqs;
10219 if (netif_alloc_netdev_queues(dev))
10222 dev->num_rx_queues = rxqs;
10223 dev->real_num_rx_queues = rxqs;
10224 if (netif_alloc_rx_queues(dev))
10227 strcpy(dev->name, name);
10228 dev->name_assign_type = name_assign_type;
10229 dev->group = INIT_NETDEV_GROUP;
10230 if (!dev->ethtool_ops)
10231 dev->ethtool_ops = &default_ethtool_ops;
10233 nf_hook_netdev_init(dev);
10242 #ifdef CONFIG_PCPU_DEV_REFCNT
10243 free_percpu(dev->pcpu_refcnt);
10246 netdev_freemem(dev);
10249 EXPORT_SYMBOL(alloc_netdev_mqs);
10252 * free_netdev - free network device
10255 * This function does the last stage of destroying an allocated device
10256 * interface. The reference to the device object is released. If this
10257 * is the last reference then it will be freed.Must be called in process
10260 void free_netdev(struct net_device *dev)
10262 struct napi_struct *p, *n;
10266 /* When called immediately after register_netdevice() failed the unwind
10267 * handling may still be dismantling the device. Handle that case by
10268 * deferring the free.
10270 if (dev->reg_state == NETREG_UNREGISTERING) {
10272 dev->needs_free_netdev = true;
10276 netif_free_tx_queues(dev);
10277 netif_free_rx_queues(dev);
10279 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10281 /* Flush device addresses */
10282 dev_addr_flush(dev);
10284 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10287 #ifdef CONFIG_PCPU_DEV_REFCNT
10288 free_percpu(dev->pcpu_refcnt);
10289 dev->pcpu_refcnt = NULL;
10291 free_percpu(dev->xdp_bulkq);
10292 dev->xdp_bulkq = NULL;
10294 /* Compatibility with error handling in drivers */
10295 if (dev->reg_state == NETREG_UNINITIALIZED) {
10296 netdev_freemem(dev);
10300 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10301 dev->reg_state = NETREG_RELEASED;
10303 /* will free via device release */
10304 put_device(&dev->dev);
10306 EXPORT_SYMBOL(free_netdev);
10309 * synchronize_net - Synchronize with packet receive processing
10311 * Wait for packets currently being received to be done.
10312 * Does not block later packets from starting.
10314 void synchronize_net(void)
10317 if (rtnl_is_locked())
10318 synchronize_rcu_expedited();
10322 EXPORT_SYMBOL(synchronize_net);
10325 * unregister_netdevice_queue - remove device from the kernel
10329 * This function shuts down a device interface and removes it
10330 * from the kernel tables.
10331 * If head not NULL, device is queued to be unregistered later.
10333 * Callers must hold the rtnl semaphore. You may want
10334 * unregister_netdev() instead of this.
10337 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10342 list_move_tail(&dev->unreg_list, head);
10346 list_add(&dev->unreg_list, &single);
10347 unregister_netdevice_many(&single);
10350 EXPORT_SYMBOL(unregister_netdevice_queue);
10353 * unregister_netdevice_many - unregister many devices
10354 * @head: list of devices
10356 * Note: As most callers use a stack allocated list_head,
10357 * we force a list_del() to make sure stack wont be corrupted later.
10359 void unregister_netdevice_many(struct list_head *head)
10361 struct net_device *dev, *tmp;
10362 LIST_HEAD(close_head);
10364 BUG_ON(dev_boot_phase);
10367 if (list_empty(head))
10370 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10371 /* Some devices call without registering
10372 * for initialization unwind. Remove those
10373 * devices and proceed with the remaining.
10375 if (dev->reg_state == NETREG_UNINITIALIZED) {
10376 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10380 list_del(&dev->unreg_list);
10383 dev->dismantle = true;
10384 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10387 /* If device is running, close it first. */
10388 list_for_each_entry(dev, head, unreg_list)
10389 list_add_tail(&dev->close_list, &close_head);
10390 dev_close_many(&close_head, true);
10392 list_for_each_entry(dev, head, unreg_list) {
10393 /* And unlink it from device chain. */
10394 unlist_netdevice(dev);
10396 dev->reg_state = NETREG_UNREGISTERING;
10398 flush_all_backlogs();
10402 list_for_each_entry(dev, head, unreg_list) {
10403 struct sk_buff *skb = NULL;
10405 /* Shutdown queueing discipline. */
10408 dev_xdp_uninstall(dev);
10410 /* Notify protocols, that we are about to destroy
10411 * this device. They should clean all the things.
10413 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10415 if (!dev->rtnl_link_ops ||
10416 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10417 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10418 GFP_KERNEL, NULL, 0);
10421 * Flush the unicast and multicast chains
10426 netdev_name_node_alt_flush(dev);
10427 netdev_name_node_free(dev->name_node);
10429 if (dev->netdev_ops->ndo_uninit)
10430 dev->netdev_ops->ndo_uninit(dev);
10433 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
10435 /* Notifier chain MUST detach us all upper devices. */
10436 WARN_ON(netdev_has_any_upper_dev(dev));
10437 WARN_ON(netdev_has_any_lower_dev(dev));
10439 /* Remove entries from kobject tree */
10440 netdev_unregister_kobject(dev);
10442 /* Remove XPS queueing entries */
10443 netif_reset_xps_queues_gt(dev, 0);
10449 list_for_each_entry(dev, head, unreg_list) {
10456 EXPORT_SYMBOL(unregister_netdevice_many);
10459 * unregister_netdev - remove device from the kernel
10462 * This function shuts down a device interface and removes it
10463 * from the kernel tables.
10465 * This is just a wrapper for unregister_netdevice that takes
10466 * the rtnl semaphore. In general you want to use this and not
10467 * unregister_netdevice.
10469 void unregister_netdev(struct net_device *dev)
10472 unregister_netdevice(dev);
10475 EXPORT_SYMBOL(unregister_netdev);
10478 * __dev_change_net_namespace - move device to different nethost namespace
10480 * @net: network namespace
10481 * @pat: If not NULL name pattern to try if the current device name
10482 * is already taken in the destination network namespace.
10483 * @new_ifindex: If not zero, specifies device index in the target
10486 * This function shuts down a device interface and moves it
10487 * to a new network namespace. On success 0 is returned, on
10488 * a failure a netagive errno code is returned.
10490 * Callers must hold the rtnl semaphore.
10493 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
10494 const char *pat, int new_ifindex)
10496 struct net *net_old = dev_net(dev);
10501 /* Don't allow namespace local devices to be moved. */
10503 if (dev->features & NETIF_F_NETNS_LOCAL)
10506 /* Ensure the device has been registrered */
10507 if (dev->reg_state != NETREG_REGISTERED)
10510 /* Get out if there is nothing todo */
10512 if (net_eq(net_old, net))
10515 /* Pick the destination device name, and ensure
10516 * we can use it in the destination network namespace.
10519 if (netdev_name_in_use(net, dev->name)) {
10520 /* We get here if we can't use the current device name */
10523 err = dev_get_valid_name(net, dev, pat);
10528 /* Check that new_ifindex isn't used yet. */
10530 if (new_ifindex && __dev_get_by_index(net, new_ifindex))
10534 * And now a mini version of register_netdevice unregister_netdevice.
10537 /* If device is running close it first. */
10540 /* And unlink it from device chain */
10541 unlist_netdevice(dev);
10545 /* Shutdown queueing discipline. */
10548 /* Notify protocols, that we are about to destroy
10549 * this device. They should clean all the things.
10551 * Note that dev->reg_state stays at NETREG_REGISTERED.
10552 * This is wanted because this way 8021q and macvlan know
10553 * the device is just moving and can keep their slaves up.
10555 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10558 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10559 /* If there is an ifindex conflict assign a new one */
10560 if (!new_ifindex) {
10561 if (__dev_get_by_index(net, dev->ifindex))
10562 new_ifindex = dev_new_index(net);
10564 new_ifindex = dev->ifindex;
10567 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10571 * Flush the unicast and multicast chains
10576 /* Send a netdev-removed uevent to the old namespace */
10577 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10578 netdev_adjacent_del_links(dev);
10580 /* Move per-net netdevice notifiers that are following the netdevice */
10581 move_netdevice_notifiers_dev_net(dev, net);
10583 /* Actually switch the network namespace */
10584 dev_net_set(dev, net);
10585 dev->ifindex = new_ifindex;
10587 /* Send a netdev-add uevent to the new namespace */
10588 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10589 netdev_adjacent_add_links(dev);
10591 /* Fixup kobjects */
10592 err = device_rename(&dev->dev, dev->name);
10595 /* Adapt owner in case owning user namespace of target network
10596 * namespace is different from the original one.
10598 err = netdev_change_owner(dev, net_old, net);
10601 /* Add the device back in the hashes */
10602 list_netdevice(dev);
10604 /* Notify protocols, that a new device appeared. */
10605 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10608 * Prevent userspace races by waiting until the network
10609 * device is fully setup before sending notifications.
10611 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10618 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
10620 static int dev_cpu_dead(unsigned int oldcpu)
10622 struct sk_buff **list_skb;
10623 struct sk_buff *skb;
10625 struct softnet_data *sd, *oldsd, *remsd = NULL;
10627 local_irq_disable();
10628 cpu = smp_processor_id();
10629 sd = &per_cpu(softnet_data, cpu);
10630 oldsd = &per_cpu(softnet_data, oldcpu);
10632 /* Find end of our completion_queue. */
10633 list_skb = &sd->completion_queue;
10635 list_skb = &(*list_skb)->next;
10636 /* Append completion queue from offline CPU. */
10637 *list_skb = oldsd->completion_queue;
10638 oldsd->completion_queue = NULL;
10640 /* Append output queue from offline CPU. */
10641 if (oldsd->output_queue) {
10642 *sd->output_queue_tailp = oldsd->output_queue;
10643 sd->output_queue_tailp = oldsd->output_queue_tailp;
10644 oldsd->output_queue = NULL;
10645 oldsd->output_queue_tailp = &oldsd->output_queue;
10647 /* Append NAPI poll list from offline CPU, with one exception :
10648 * process_backlog() must be called by cpu owning percpu backlog.
10649 * We properly handle process_queue & input_pkt_queue later.
10651 while (!list_empty(&oldsd->poll_list)) {
10652 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10653 struct napi_struct,
10656 list_del_init(&napi->poll_list);
10657 if (napi->poll == process_backlog)
10660 ____napi_schedule(sd, napi);
10663 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10664 local_irq_enable();
10667 remsd = oldsd->rps_ipi_list;
10668 oldsd->rps_ipi_list = NULL;
10670 /* send out pending IPI's on offline CPU */
10671 net_rps_send_ipi(remsd);
10673 /* Process offline CPU's input_pkt_queue */
10674 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
10676 input_queue_head_incr(oldsd);
10678 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
10680 input_queue_head_incr(oldsd);
10687 * netdev_increment_features - increment feature set by one
10688 * @all: current feature set
10689 * @one: new feature set
10690 * @mask: mask feature set
10692 * Computes a new feature set after adding a device with feature set
10693 * @one to the master device with current feature set @all. Will not
10694 * enable anything that is off in @mask. Returns the new feature set.
10696 netdev_features_t netdev_increment_features(netdev_features_t all,
10697 netdev_features_t one, netdev_features_t mask)
10699 if (mask & NETIF_F_HW_CSUM)
10700 mask |= NETIF_F_CSUM_MASK;
10701 mask |= NETIF_F_VLAN_CHALLENGED;
10703 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
10704 all &= one | ~NETIF_F_ALL_FOR_ALL;
10706 /* If one device supports hw checksumming, set for all. */
10707 if (all & NETIF_F_HW_CSUM)
10708 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
10712 EXPORT_SYMBOL(netdev_increment_features);
10714 static struct hlist_head * __net_init netdev_create_hash(void)
10717 struct hlist_head *hash;
10719 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
10721 for (i = 0; i < NETDEV_HASHENTRIES; i++)
10722 INIT_HLIST_HEAD(&hash[i]);
10727 /* Initialize per network namespace state */
10728 static int __net_init netdev_init(struct net *net)
10730 BUILD_BUG_ON(GRO_HASH_BUCKETS >
10731 8 * sizeof_field(struct napi_struct, gro_bitmask));
10733 if (net != &init_net)
10734 INIT_LIST_HEAD(&net->dev_base_head);
10736 net->dev_name_head = netdev_create_hash();
10737 if (net->dev_name_head == NULL)
10740 net->dev_index_head = netdev_create_hash();
10741 if (net->dev_index_head == NULL)
10744 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
10749 kfree(net->dev_name_head);
10755 * netdev_drivername - network driver for the device
10756 * @dev: network device
10758 * Determine network driver for device.
10760 const char *netdev_drivername(const struct net_device *dev)
10762 const struct device_driver *driver;
10763 const struct device *parent;
10764 const char *empty = "";
10766 parent = dev->dev.parent;
10770 driver = parent->driver;
10771 if (driver && driver->name)
10772 return driver->name;
10776 static void __netdev_printk(const char *level, const struct net_device *dev,
10777 struct va_format *vaf)
10779 if (dev && dev->dev.parent) {
10780 dev_printk_emit(level[1] - '0',
10783 dev_driver_string(dev->dev.parent),
10784 dev_name(dev->dev.parent),
10785 netdev_name(dev), netdev_reg_state(dev),
10788 printk("%s%s%s: %pV",
10789 level, netdev_name(dev), netdev_reg_state(dev), vaf);
10791 printk("%s(NULL net_device): %pV", level, vaf);
10795 void netdev_printk(const char *level, const struct net_device *dev,
10796 const char *format, ...)
10798 struct va_format vaf;
10801 va_start(args, format);
10806 __netdev_printk(level, dev, &vaf);
10810 EXPORT_SYMBOL(netdev_printk);
10812 #define define_netdev_printk_level(func, level) \
10813 void func(const struct net_device *dev, const char *fmt, ...) \
10815 struct va_format vaf; \
10818 va_start(args, fmt); \
10823 __netdev_printk(level, dev, &vaf); \
10827 EXPORT_SYMBOL(func);
10829 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
10830 define_netdev_printk_level(netdev_alert, KERN_ALERT);
10831 define_netdev_printk_level(netdev_crit, KERN_CRIT);
10832 define_netdev_printk_level(netdev_err, KERN_ERR);
10833 define_netdev_printk_level(netdev_warn, KERN_WARNING);
10834 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
10835 define_netdev_printk_level(netdev_info, KERN_INFO);
10837 static void __net_exit netdev_exit(struct net *net)
10839 kfree(net->dev_name_head);
10840 kfree(net->dev_index_head);
10841 if (net != &init_net)
10842 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
10845 static struct pernet_operations __net_initdata netdev_net_ops = {
10846 .init = netdev_init,
10847 .exit = netdev_exit,
10850 static void __net_exit default_device_exit(struct net *net)
10852 struct net_device *dev, *aux;
10854 * Push all migratable network devices back to the
10855 * initial network namespace
10858 for_each_netdev_safe(net, dev, aux) {
10860 char fb_name[IFNAMSIZ];
10862 /* Ignore unmoveable devices (i.e. loopback) */
10863 if (dev->features & NETIF_F_NETNS_LOCAL)
10866 /* Leave virtual devices for the generic cleanup */
10867 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
10870 /* Push remaining network devices to init_net */
10871 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
10872 if (netdev_name_in_use(&init_net, fb_name))
10873 snprintf(fb_name, IFNAMSIZ, "dev%%d");
10874 err = dev_change_net_namespace(dev, &init_net, fb_name);
10876 pr_emerg("%s: failed to move %s to init_net: %d\n",
10877 __func__, dev->name, err);
10884 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
10886 /* Return with the rtnl_lock held when there are no network
10887 * devices unregistering in any network namespace in net_list.
10890 bool unregistering;
10891 DEFINE_WAIT_FUNC(wait, woken_wake_function);
10893 add_wait_queue(&netdev_unregistering_wq, &wait);
10895 unregistering = false;
10897 list_for_each_entry(net, net_list, exit_list) {
10898 if (net->dev_unreg_count > 0) {
10899 unregistering = true;
10903 if (!unregistering)
10907 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
10909 remove_wait_queue(&netdev_unregistering_wq, &wait);
10912 static void __net_exit default_device_exit_batch(struct list_head *net_list)
10914 /* At exit all network devices most be removed from a network
10915 * namespace. Do this in the reverse order of registration.
10916 * Do this across as many network namespaces as possible to
10917 * improve batching efficiency.
10919 struct net_device *dev;
10921 LIST_HEAD(dev_kill_list);
10923 /* To prevent network device cleanup code from dereferencing
10924 * loopback devices or network devices that have been freed
10925 * wait here for all pending unregistrations to complete,
10926 * before unregistring the loopback device and allowing the
10927 * network namespace be freed.
10929 * The netdev todo list containing all network devices
10930 * unregistrations that happen in default_device_exit_batch
10931 * will run in the rtnl_unlock() at the end of
10932 * default_device_exit_batch.
10934 rtnl_lock_unregistering(net_list);
10935 list_for_each_entry(net, net_list, exit_list) {
10936 for_each_netdev_reverse(net, dev) {
10937 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
10938 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
10940 unregister_netdevice_queue(dev, &dev_kill_list);
10943 unregister_netdevice_many(&dev_kill_list);
10947 static struct pernet_operations __net_initdata default_device_ops = {
10948 .exit = default_device_exit,
10949 .exit_batch = default_device_exit_batch,
10953 * Initialize the DEV module. At boot time this walks the device list and
10954 * unhooks any devices that fail to initialise (normally hardware not
10955 * present) and leaves us with a valid list of present and active devices.
10960 * This is called single threaded during boot, so no need
10961 * to take the rtnl semaphore.
10963 static int __init net_dev_init(void)
10965 int i, rc = -ENOMEM;
10967 BUG_ON(!dev_boot_phase);
10969 if (dev_proc_init())
10972 if (netdev_kobject_init())
10975 INIT_LIST_HEAD(&ptype_all);
10976 for (i = 0; i < PTYPE_HASH_SIZE; i++)
10977 INIT_LIST_HEAD(&ptype_base[i]);
10979 if (register_pernet_subsys(&netdev_net_ops))
10983 * Initialise the packet receive queues.
10986 for_each_possible_cpu(i) {
10987 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
10988 struct softnet_data *sd = &per_cpu(softnet_data, i);
10990 INIT_WORK(flush, flush_backlog);
10992 skb_queue_head_init(&sd->input_pkt_queue);
10993 skb_queue_head_init(&sd->process_queue);
10994 #ifdef CONFIG_XFRM_OFFLOAD
10995 skb_queue_head_init(&sd->xfrm_backlog);
10997 INIT_LIST_HEAD(&sd->poll_list);
10998 sd->output_queue_tailp = &sd->output_queue;
11000 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11004 init_gro_hash(&sd->backlog);
11005 sd->backlog.poll = process_backlog;
11006 sd->backlog.weight = weight_p;
11009 dev_boot_phase = 0;
11011 /* The loopback device is special if any other network devices
11012 * is present in a network namespace the loopback device must
11013 * be present. Since we now dynamically allocate and free the
11014 * loopback device ensure this invariant is maintained by
11015 * keeping the loopback device as the first device on the
11016 * list of network devices. Ensuring the loopback devices
11017 * is the first device that appears and the last network device
11020 if (register_pernet_device(&loopback_net_ops))
11023 if (register_pernet_device(&default_device_ops))
11026 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11027 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11029 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11030 NULL, dev_cpu_dead);
11037 subsys_initcall(net_dev_init);