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/string.h>
84 #include <linux/socket.h>
85 #include <linux/sockios.h>
86 #include <linux/errno.h>
87 #include <linux/interrupt.h>
88 #include <linux/if_ether.h>
89 #include <linux/netdevice.h>
90 #include <linux/etherdevice.h>
91 #include <linux/ethtool.h>
92 #include <linux/skbuff.h>
93 #include <linux/bpf.h>
94 #include <linux/bpf_trace.h>
95 #include <net/net_namespace.h>
97 #include <net/busy_poll.h>
98 #include <linux/rtnetlink.h>
99 #include <linux/stat.h>
101 #include <net/dst_metadata.h>
102 #include <net/pkt_sched.h>
103 #include <net/pkt_cls.h>
104 #include <net/checksum.h>
105 #include <net/xfrm.h>
106 #include <linux/highmem.h>
107 #include <linux/init.h>
108 #include <linux/module.h>
109 #include <linux/netpoll.h>
110 #include <linux/rcupdate.h>
111 #include <linux/delay.h>
112 #include <net/iw_handler.h>
113 #include <asm/current.h>
114 #include <linux/audit.h>
115 #include <linux/dmaengine.h>
116 #include <linux/err.h>
117 #include <linux/ctype.h>
118 #include <linux/if_arp.h>
119 #include <linux/if_vlan.h>
120 #include <linux/ip.h>
122 #include <net/mpls.h>
123 #include <linux/ipv6.h>
124 #include <linux/in.h>
125 #include <linux/jhash.h>
126 #include <linux/random.h>
127 #include <trace/events/napi.h>
128 #include <trace/events/net.h>
129 #include <trace/events/skb.h>
130 #include <linux/inetdevice.h>
131 #include <linux/cpu_rmap.h>
132 #include <linux/static_key.h>
133 #include <linux/hashtable.h>
134 #include <linux/vmalloc.h>
135 #include <linux/if_macvlan.h>
136 #include <linux/errqueue.h>
137 #include <linux/hrtimer.h>
138 #include <linux/netfilter_ingress.h>
139 #include <linux/crash_dump.h>
140 #include <linux/sctp.h>
141 #include <net/udp_tunnel.h>
142 #include <linux/net_namespace.h>
143 #include <linux/indirect_call_wrapper.h>
144 #include <net/devlink.h>
146 #include "net-sysfs.h"
148 #define MAX_GRO_SKBS 8
149 #define MAX_NEST_DEV 8
151 /* This should be increased if a protocol with a bigger head is added. */
152 #define GRO_MAX_HEAD (MAX_HEADER + 128)
154 static DEFINE_SPINLOCK(ptype_lock);
155 static DEFINE_SPINLOCK(offload_lock);
156 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
157 struct list_head ptype_all __read_mostly; /* Taps */
158 static struct list_head offload_base __read_mostly;
160 static int netif_rx_internal(struct sk_buff *skb);
161 static int call_netdevice_notifiers_info(unsigned long val,
162 struct netdev_notifier_info *info);
163 static int call_netdevice_notifiers_extack(unsigned long val,
164 struct net_device *dev,
165 struct netlink_ext_ack *extack);
166 static struct napi_struct *napi_by_id(unsigned int napi_id);
169 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
172 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
174 * Writers must hold the rtnl semaphore while they loop through the
175 * dev_base_head list, and hold dev_base_lock for writing when they do the
176 * actual updates. This allows pure readers to access the list even
177 * while a writer is preparing to update it.
179 * To put it another way, dev_base_lock is held for writing only to
180 * protect against pure readers; the rtnl semaphore provides the
181 * protection against other writers.
183 * See, for example usages, register_netdevice() and
184 * unregister_netdevice(), which must be called with the rtnl
187 DEFINE_RWLOCK(dev_base_lock);
188 EXPORT_SYMBOL(dev_base_lock);
190 static DEFINE_MUTEX(ifalias_mutex);
192 /* protects napi_hash addition/deletion and napi_gen_id */
193 static DEFINE_SPINLOCK(napi_hash_lock);
195 static unsigned int napi_gen_id = NR_CPUS;
196 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
198 static seqcount_t devnet_rename_seq;
200 static inline void dev_base_seq_inc(struct net *net)
202 while (++net->dev_base_seq == 0)
206 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
208 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
210 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
213 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
215 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
218 static inline void rps_lock(struct softnet_data *sd)
221 spin_lock(&sd->input_pkt_queue.lock);
225 static inline void rps_unlock(struct softnet_data *sd)
228 spin_unlock(&sd->input_pkt_queue.lock);
232 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
235 struct netdev_name_node *name_node;
237 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
240 INIT_HLIST_NODE(&name_node->hlist);
241 name_node->dev = dev;
242 name_node->name = name;
246 static struct netdev_name_node *
247 netdev_name_node_head_alloc(struct net_device *dev)
249 struct netdev_name_node *name_node;
251 name_node = netdev_name_node_alloc(dev, dev->name);
254 INIT_LIST_HEAD(&name_node->list);
258 static void netdev_name_node_free(struct netdev_name_node *name_node)
263 static void netdev_name_node_add(struct net *net,
264 struct netdev_name_node *name_node)
266 hlist_add_head_rcu(&name_node->hlist,
267 dev_name_hash(net, name_node->name));
270 static void netdev_name_node_del(struct netdev_name_node *name_node)
272 hlist_del_rcu(&name_node->hlist);
275 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
278 struct hlist_head *head = dev_name_hash(net, name);
279 struct netdev_name_node *name_node;
281 hlist_for_each_entry(name_node, head, hlist)
282 if (!strcmp(name_node->name, name))
287 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
290 struct hlist_head *head = dev_name_hash(net, name);
291 struct netdev_name_node *name_node;
293 hlist_for_each_entry_rcu(name_node, head, hlist)
294 if (!strcmp(name_node->name, name))
299 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
301 struct netdev_name_node *name_node;
302 struct net *net = dev_net(dev);
304 name_node = netdev_name_node_lookup(net, name);
307 name_node = netdev_name_node_alloc(dev, name);
310 netdev_name_node_add(net, name_node);
311 /* The node that holds dev->name acts as a head of per-device list. */
312 list_add_tail(&name_node->list, &dev->name_node->list);
316 EXPORT_SYMBOL(netdev_name_node_alt_create);
318 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
320 list_del(&name_node->list);
321 netdev_name_node_del(name_node);
322 kfree(name_node->name);
323 netdev_name_node_free(name_node);
326 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
328 struct netdev_name_node *name_node;
329 struct net *net = dev_net(dev);
331 name_node = netdev_name_node_lookup(net, name);
334 __netdev_name_node_alt_destroy(name_node);
338 EXPORT_SYMBOL(netdev_name_node_alt_destroy);
340 static void netdev_name_node_alt_flush(struct net_device *dev)
342 struct netdev_name_node *name_node, *tmp;
344 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
345 __netdev_name_node_alt_destroy(name_node);
348 /* Device list insertion */
349 static void list_netdevice(struct net_device *dev)
351 struct net *net = dev_net(dev);
355 write_lock_bh(&dev_base_lock);
356 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
357 netdev_name_node_add(net, dev->name_node);
358 hlist_add_head_rcu(&dev->index_hlist,
359 dev_index_hash(net, dev->ifindex));
360 write_unlock_bh(&dev_base_lock);
362 dev_base_seq_inc(net);
365 /* Device list removal
366 * caller must respect a RCU grace period before freeing/reusing dev
368 static void unlist_netdevice(struct net_device *dev)
372 /* Unlink dev from the device chain */
373 write_lock_bh(&dev_base_lock);
374 list_del_rcu(&dev->dev_list);
375 netdev_name_node_del(dev->name_node);
376 hlist_del_rcu(&dev->index_hlist);
377 write_unlock_bh(&dev_base_lock);
379 dev_base_seq_inc(dev_net(dev));
386 static RAW_NOTIFIER_HEAD(netdev_chain);
389 * Device drivers call our routines to queue packets here. We empty the
390 * queue in the local softnet handler.
393 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
394 EXPORT_PER_CPU_SYMBOL(softnet_data);
396 /*******************************************************************************
398 * Protocol management and registration routines
400 *******************************************************************************/
404 * Add a protocol ID to the list. Now that the input handler is
405 * smarter we can dispense with all the messy stuff that used to be
408 * BEWARE!!! Protocol handlers, mangling input packets,
409 * MUST BE last in hash buckets and checking protocol handlers
410 * MUST start from promiscuous ptype_all chain in net_bh.
411 * It is true now, do not change it.
412 * Explanation follows: if protocol handler, mangling packet, will
413 * be the first on list, it is not able to sense, that packet
414 * is cloned and should be copied-on-write, so that it will
415 * change it and subsequent readers will get broken packet.
419 static inline struct list_head *ptype_head(const struct packet_type *pt)
421 if (pt->type == htons(ETH_P_ALL))
422 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
424 return pt->dev ? &pt->dev->ptype_specific :
425 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
429 * dev_add_pack - add packet handler
430 * @pt: packet type declaration
432 * Add a protocol handler to the networking stack. The passed &packet_type
433 * is linked into kernel lists and may not be freed until it has been
434 * removed from the kernel lists.
436 * This call does not sleep therefore it can not
437 * guarantee all CPU's that are in middle of receiving packets
438 * will see the new packet type (until the next received packet).
441 void dev_add_pack(struct packet_type *pt)
443 struct list_head *head = ptype_head(pt);
445 spin_lock(&ptype_lock);
446 list_add_rcu(&pt->list, head);
447 spin_unlock(&ptype_lock);
449 EXPORT_SYMBOL(dev_add_pack);
452 * __dev_remove_pack - remove packet handler
453 * @pt: packet type declaration
455 * Remove a protocol handler that was previously added to the kernel
456 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
457 * from the kernel lists and can be freed or reused once this function
460 * The packet type might still be in use by receivers
461 * and must not be freed until after all the CPU's have gone
462 * through a quiescent state.
464 void __dev_remove_pack(struct packet_type *pt)
466 struct list_head *head = ptype_head(pt);
467 struct packet_type *pt1;
469 spin_lock(&ptype_lock);
471 list_for_each_entry(pt1, head, list) {
473 list_del_rcu(&pt->list);
478 pr_warn("dev_remove_pack: %p not found\n", pt);
480 spin_unlock(&ptype_lock);
482 EXPORT_SYMBOL(__dev_remove_pack);
485 * dev_remove_pack - remove packet handler
486 * @pt: packet type declaration
488 * Remove a protocol handler that was previously added to the kernel
489 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
490 * from the kernel lists and can be freed or reused once this function
493 * This call sleeps to guarantee that no CPU is looking at the packet
496 void dev_remove_pack(struct packet_type *pt)
498 __dev_remove_pack(pt);
502 EXPORT_SYMBOL(dev_remove_pack);
506 * dev_add_offload - register offload handlers
507 * @po: protocol offload declaration
509 * Add protocol offload handlers to the networking stack. The passed
510 * &proto_offload is linked into kernel lists and may not be freed until
511 * it has been removed from the kernel lists.
513 * This call does not sleep therefore it can not
514 * guarantee all CPU's that are in middle of receiving packets
515 * will see the new offload handlers (until the next received packet).
517 void dev_add_offload(struct packet_offload *po)
519 struct packet_offload *elem;
521 spin_lock(&offload_lock);
522 list_for_each_entry(elem, &offload_base, list) {
523 if (po->priority < elem->priority)
526 list_add_rcu(&po->list, elem->list.prev);
527 spin_unlock(&offload_lock);
529 EXPORT_SYMBOL(dev_add_offload);
532 * __dev_remove_offload - remove offload handler
533 * @po: packet offload declaration
535 * Remove a protocol offload handler that was previously added to the
536 * kernel offload handlers by dev_add_offload(). The passed &offload_type
537 * is removed from the kernel lists and can be freed or reused once this
540 * The packet type might still be in use by receivers
541 * and must not be freed until after all the CPU's have gone
542 * through a quiescent state.
544 static void __dev_remove_offload(struct packet_offload *po)
546 struct list_head *head = &offload_base;
547 struct packet_offload *po1;
549 spin_lock(&offload_lock);
551 list_for_each_entry(po1, head, list) {
553 list_del_rcu(&po->list);
558 pr_warn("dev_remove_offload: %p not found\n", po);
560 spin_unlock(&offload_lock);
564 * dev_remove_offload - remove packet offload handler
565 * @po: packet offload declaration
567 * Remove a packet offload handler that was previously added to the kernel
568 * offload handlers by dev_add_offload(). The passed &offload_type is
569 * removed from the kernel lists and can be freed or reused once this
572 * This call sleeps to guarantee that no CPU is looking at the packet
575 void dev_remove_offload(struct packet_offload *po)
577 __dev_remove_offload(po);
581 EXPORT_SYMBOL(dev_remove_offload);
583 /******************************************************************************
585 * Device Boot-time Settings Routines
587 ******************************************************************************/
589 /* Boot time configuration table */
590 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
593 * netdev_boot_setup_add - add new setup entry
594 * @name: name of the device
595 * @map: configured settings for the device
597 * Adds new setup entry to the dev_boot_setup list. The function
598 * returns 0 on error and 1 on success. This is a generic routine to
601 static int netdev_boot_setup_add(char *name, struct ifmap *map)
603 struct netdev_boot_setup *s;
607 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
608 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
609 memset(s[i].name, 0, sizeof(s[i].name));
610 strlcpy(s[i].name, name, IFNAMSIZ);
611 memcpy(&s[i].map, map, sizeof(s[i].map));
616 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
620 * netdev_boot_setup_check - check boot time settings
621 * @dev: the netdevice
623 * Check boot time settings for the device.
624 * The found settings are set for the device to be used
625 * later in the device probing.
626 * Returns 0 if no settings found, 1 if they are.
628 int netdev_boot_setup_check(struct net_device *dev)
630 struct netdev_boot_setup *s = dev_boot_setup;
633 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
634 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
635 !strcmp(dev->name, s[i].name)) {
636 dev->irq = s[i].map.irq;
637 dev->base_addr = s[i].map.base_addr;
638 dev->mem_start = s[i].map.mem_start;
639 dev->mem_end = s[i].map.mem_end;
645 EXPORT_SYMBOL(netdev_boot_setup_check);
649 * netdev_boot_base - get address from boot time settings
650 * @prefix: prefix for network device
651 * @unit: id for network device
653 * Check boot time settings for the base address of device.
654 * The found settings are set for the device to be used
655 * later in the device probing.
656 * Returns 0 if no settings found.
658 unsigned long netdev_boot_base(const char *prefix, int unit)
660 const struct netdev_boot_setup *s = dev_boot_setup;
664 sprintf(name, "%s%d", prefix, unit);
667 * If device already registered then return base of 1
668 * to indicate not to probe for this interface
670 if (__dev_get_by_name(&init_net, name))
673 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
674 if (!strcmp(name, s[i].name))
675 return s[i].map.base_addr;
680 * Saves at boot time configured settings for any netdevice.
682 int __init netdev_boot_setup(char *str)
687 str = get_options(str, ARRAY_SIZE(ints), ints);
692 memset(&map, 0, sizeof(map));
696 map.base_addr = ints[2];
698 map.mem_start = ints[3];
700 map.mem_end = ints[4];
702 /* Add new entry to the list */
703 return netdev_boot_setup_add(str, &map);
706 __setup("netdev=", netdev_boot_setup);
708 /*******************************************************************************
710 * Device Interface Subroutines
712 *******************************************************************************/
715 * dev_get_iflink - get 'iflink' value of a interface
716 * @dev: targeted interface
718 * Indicates the ifindex the interface is linked to.
719 * Physical interfaces have the same 'ifindex' and 'iflink' values.
722 int dev_get_iflink(const struct net_device *dev)
724 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
725 return dev->netdev_ops->ndo_get_iflink(dev);
729 EXPORT_SYMBOL(dev_get_iflink);
732 * dev_fill_metadata_dst - Retrieve tunnel egress information.
733 * @dev: targeted interface
736 * For better visibility of tunnel traffic OVS needs to retrieve
737 * egress tunnel information for a packet. Following API allows
738 * user to get this info.
740 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
742 struct ip_tunnel_info *info;
744 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
747 info = skb_tunnel_info_unclone(skb);
750 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
753 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
755 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
758 * __dev_get_by_name - find a device by its name
759 * @net: the applicable net namespace
760 * @name: name to find
762 * Find an interface by name. Must be called under RTNL semaphore
763 * or @dev_base_lock. If the name is found a pointer to the device
764 * is returned. If the name is not found then %NULL is returned. The
765 * reference counters are not incremented so the caller must be
766 * careful with locks.
769 struct net_device *__dev_get_by_name(struct net *net, const char *name)
771 struct netdev_name_node *node_name;
773 node_name = netdev_name_node_lookup(net, name);
774 return node_name ? node_name->dev : NULL;
776 EXPORT_SYMBOL(__dev_get_by_name);
779 * dev_get_by_name_rcu - find a device by its name
780 * @net: the applicable net namespace
781 * @name: name to find
783 * Find an interface by name.
784 * If the name is found a pointer to the device is returned.
785 * If the name is not found then %NULL is returned.
786 * The reference counters are not incremented so the caller must be
787 * careful with locks. The caller must hold RCU lock.
790 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
792 struct netdev_name_node *node_name;
794 node_name = netdev_name_node_lookup_rcu(net, name);
795 return node_name ? node_name->dev : NULL;
797 EXPORT_SYMBOL(dev_get_by_name_rcu);
800 * dev_get_by_name - find a device by its name
801 * @net: the applicable net namespace
802 * @name: name to find
804 * Find an interface by name. This can be called from any
805 * context and does its own locking. The returned handle has
806 * the usage count incremented and the caller must use dev_put() to
807 * release it when it is no longer needed. %NULL is returned if no
808 * matching device is found.
811 struct net_device *dev_get_by_name(struct net *net, const char *name)
813 struct net_device *dev;
816 dev = dev_get_by_name_rcu(net, name);
822 EXPORT_SYMBOL(dev_get_by_name);
825 * __dev_get_by_index - find a device by its ifindex
826 * @net: the applicable net namespace
827 * @ifindex: index of device
829 * Search for an interface by index. Returns %NULL if the device
830 * is not found or a pointer to the device. The device has not
831 * had its reference counter increased so the caller must be careful
832 * about locking. The caller must hold either the RTNL semaphore
836 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
838 struct net_device *dev;
839 struct hlist_head *head = dev_index_hash(net, ifindex);
841 hlist_for_each_entry(dev, head, index_hlist)
842 if (dev->ifindex == ifindex)
847 EXPORT_SYMBOL(__dev_get_by_index);
850 * dev_get_by_index_rcu - find a device by its ifindex
851 * @net: the applicable net namespace
852 * @ifindex: index of device
854 * Search for an interface by index. Returns %NULL if the device
855 * is not found or a pointer to the device. The device has not
856 * had its reference counter increased so the caller must be careful
857 * about locking. The caller must hold RCU lock.
860 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
862 struct net_device *dev;
863 struct hlist_head *head = dev_index_hash(net, ifindex);
865 hlist_for_each_entry_rcu(dev, head, index_hlist)
866 if (dev->ifindex == ifindex)
871 EXPORT_SYMBOL(dev_get_by_index_rcu);
875 * dev_get_by_index - find a device by its ifindex
876 * @net: the applicable net namespace
877 * @ifindex: index of device
879 * Search for an interface by index. Returns NULL if the device
880 * is not found or a pointer to the device. The device returned has
881 * had a reference added and the pointer is safe until the user calls
882 * dev_put to indicate they have finished with it.
885 struct net_device *dev_get_by_index(struct net *net, int ifindex)
887 struct net_device *dev;
890 dev = dev_get_by_index_rcu(net, ifindex);
896 EXPORT_SYMBOL(dev_get_by_index);
899 * dev_get_by_napi_id - find a device by napi_id
900 * @napi_id: ID of the NAPI struct
902 * Search for an interface by NAPI ID. Returns %NULL if the device
903 * is not found or a pointer to the device. The device has not had
904 * its reference counter increased so the caller must be careful
905 * about locking. The caller must hold RCU lock.
908 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
910 struct napi_struct *napi;
912 WARN_ON_ONCE(!rcu_read_lock_held());
914 if (napi_id < MIN_NAPI_ID)
917 napi = napi_by_id(napi_id);
919 return napi ? napi->dev : NULL;
921 EXPORT_SYMBOL(dev_get_by_napi_id);
924 * netdev_get_name - get a netdevice name, knowing its ifindex.
925 * @net: network namespace
926 * @name: a pointer to the buffer where the name will be stored.
927 * @ifindex: the ifindex of the interface to get the name from.
929 * The use of raw_seqcount_begin() and cond_resched() before
930 * retrying is required as we want to give the writers a chance
931 * to complete when CONFIG_PREEMPT is not set.
933 int netdev_get_name(struct net *net, char *name, int ifindex)
935 struct net_device *dev;
939 seq = raw_seqcount_begin(&devnet_rename_seq);
941 dev = dev_get_by_index_rcu(net, ifindex);
947 strcpy(name, dev->name);
949 if (read_seqcount_retry(&devnet_rename_seq, seq)) {
958 * dev_getbyhwaddr_rcu - find a device by its hardware address
959 * @net: the applicable net namespace
960 * @type: media type of device
961 * @ha: hardware address
963 * Search for an interface by MAC address. Returns NULL if the device
964 * is not found or a pointer to the device.
965 * The caller must hold RCU or RTNL.
966 * The returned device has not had its ref count increased
967 * and the caller must therefore be careful about locking
971 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
974 struct net_device *dev;
976 for_each_netdev_rcu(net, dev)
977 if (dev->type == type &&
978 !memcmp(dev->dev_addr, ha, dev->addr_len))
983 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
985 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
987 struct net_device *dev;
990 for_each_netdev(net, dev)
991 if (dev->type == type)
996 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
998 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1000 struct net_device *dev, *ret = NULL;
1003 for_each_netdev_rcu(net, dev)
1004 if (dev->type == type) {
1012 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1015 * __dev_get_by_flags - find any device with given flags
1016 * @net: the applicable net namespace
1017 * @if_flags: IFF_* values
1018 * @mask: bitmask of bits in if_flags to check
1020 * Search for any interface with the given flags. Returns NULL if a device
1021 * is not found or a pointer to the device. Must be called inside
1022 * rtnl_lock(), and result refcount is unchanged.
1025 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1026 unsigned short mask)
1028 struct net_device *dev, *ret;
1033 for_each_netdev(net, dev) {
1034 if (((dev->flags ^ if_flags) & mask) == 0) {
1041 EXPORT_SYMBOL(__dev_get_by_flags);
1044 * dev_valid_name - check if name is okay for network device
1045 * @name: name string
1047 * Network device names need to be valid file names to
1048 * to allow sysfs to work. We also disallow any kind of
1051 bool dev_valid_name(const char *name)
1055 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1057 if (!strcmp(name, ".") || !strcmp(name, ".."))
1061 if (*name == '/' || *name == ':' || isspace(*name))
1067 EXPORT_SYMBOL(dev_valid_name);
1070 * __dev_alloc_name - allocate a name for a device
1071 * @net: network namespace to allocate the device name in
1072 * @name: name format string
1073 * @buf: scratch buffer and result name string
1075 * Passed a format string - eg "lt%d" it will try and find a suitable
1076 * id. It scans list of devices to build up a free map, then chooses
1077 * the first empty slot. The caller must hold the dev_base or rtnl lock
1078 * while allocating the name and adding the device in order to avoid
1080 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1081 * Returns the number of the unit assigned or a negative errno code.
1084 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1088 const int max_netdevices = 8*PAGE_SIZE;
1089 unsigned long *inuse;
1090 struct net_device *d;
1092 if (!dev_valid_name(name))
1095 p = strchr(name, '%');
1098 * Verify the string as this thing may have come from
1099 * the user. There must be either one "%d" and no other "%"
1102 if (p[1] != 'd' || strchr(p + 2, '%'))
1105 /* Use one page as a bit array of possible slots */
1106 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1110 for_each_netdev(net, d) {
1111 if (!sscanf(d->name, name, &i))
1113 if (i < 0 || i >= max_netdevices)
1116 /* avoid cases where sscanf is not exact inverse of printf */
1117 snprintf(buf, IFNAMSIZ, name, i);
1118 if (!strncmp(buf, d->name, IFNAMSIZ))
1122 i = find_first_zero_bit(inuse, max_netdevices);
1123 free_page((unsigned long) inuse);
1126 snprintf(buf, IFNAMSIZ, name, i);
1127 if (!__dev_get_by_name(net, buf))
1130 /* It is possible to run out of possible slots
1131 * when the name is long and there isn't enough space left
1132 * for the digits, or if all bits are used.
1137 static int dev_alloc_name_ns(struct net *net,
1138 struct net_device *dev,
1145 ret = __dev_alloc_name(net, name, buf);
1147 strlcpy(dev->name, buf, IFNAMSIZ);
1152 * dev_alloc_name - allocate a name for a device
1154 * @name: name format string
1156 * Passed a format string - eg "lt%d" it will try and find a suitable
1157 * id. It scans list of devices to build up a free map, then chooses
1158 * the first empty slot. The caller must hold the dev_base or rtnl lock
1159 * while allocating the name and adding the device in order to avoid
1161 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1162 * Returns the number of the unit assigned or a negative errno code.
1165 int dev_alloc_name(struct net_device *dev, const char *name)
1167 return dev_alloc_name_ns(dev_net(dev), dev, name);
1169 EXPORT_SYMBOL(dev_alloc_name);
1171 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1176 if (!dev_valid_name(name))
1179 if (strchr(name, '%'))
1180 return dev_alloc_name_ns(net, dev, name);
1181 else if (__dev_get_by_name(net, name))
1183 else if (dev->name != name)
1184 strlcpy(dev->name, name, IFNAMSIZ);
1190 * dev_change_name - change name of a device
1192 * @newname: name (or format string) must be at least IFNAMSIZ
1194 * Change name of a device, can pass format strings "eth%d".
1197 int dev_change_name(struct net_device *dev, const char *newname)
1199 unsigned char old_assign_type;
1200 char oldname[IFNAMSIZ];
1206 BUG_ON(!dev_net(dev));
1210 /* Some auto-enslaved devices e.g. failover slaves are
1211 * special, as userspace might rename the device after
1212 * the interface had been brought up and running since
1213 * the point kernel initiated auto-enslavement. Allow
1214 * live name change even when these slave devices are
1217 * Typically, users of these auto-enslaving devices
1218 * don't actually care about slave name change, as
1219 * they are supposed to operate on master interface
1222 if (dev->flags & IFF_UP &&
1223 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1226 write_seqcount_begin(&devnet_rename_seq);
1228 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1229 write_seqcount_end(&devnet_rename_seq);
1233 memcpy(oldname, dev->name, IFNAMSIZ);
1235 err = dev_get_valid_name(net, dev, newname);
1237 write_seqcount_end(&devnet_rename_seq);
1241 if (oldname[0] && !strchr(oldname, '%'))
1242 netdev_info(dev, "renamed from %s\n", oldname);
1244 old_assign_type = dev->name_assign_type;
1245 dev->name_assign_type = NET_NAME_RENAMED;
1248 ret = device_rename(&dev->dev, dev->name);
1250 memcpy(dev->name, oldname, IFNAMSIZ);
1251 dev->name_assign_type = old_assign_type;
1252 write_seqcount_end(&devnet_rename_seq);
1256 write_seqcount_end(&devnet_rename_seq);
1258 netdev_adjacent_rename_links(dev, oldname);
1260 write_lock_bh(&dev_base_lock);
1261 netdev_name_node_del(dev->name_node);
1262 write_unlock_bh(&dev_base_lock);
1266 write_lock_bh(&dev_base_lock);
1267 netdev_name_node_add(net, dev->name_node);
1268 write_unlock_bh(&dev_base_lock);
1270 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1271 ret = notifier_to_errno(ret);
1274 /* err >= 0 after dev_alloc_name() or stores the first errno */
1277 write_seqcount_begin(&devnet_rename_seq);
1278 memcpy(dev->name, oldname, IFNAMSIZ);
1279 memcpy(oldname, newname, IFNAMSIZ);
1280 dev->name_assign_type = old_assign_type;
1281 old_assign_type = NET_NAME_RENAMED;
1284 pr_err("%s: name change rollback failed: %d\n",
1293 * dev_set_alias - change ifalias of a device
1295 * @alias: name up to IFALIASZ
1296 * @len: limit of bytes to copy from info
1298 * Set ifalias for a device,
1300 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1302 struct dev_ifalias *new_alias = NULL;
1304 if (len >= IFALIASZ)
1308 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1312 memcpy(new_alias->ifalias, alias, len);
1313 new_alias->ifalias[len] = 0;
1316 mutex_lock(&ifalias_mutex);
1317 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1318 mutex_is_locked(&ifalias_mutex));
1319 mutex_unlock(&ifalias_mutex);
1322 kfree_rcu(new_alias, rcuhead);
1326 EXPORT_SYMBOL(dev_set_alias);
1329 * dev_get_alias - get ifalias of a device
1331 * @name: buffer to store name of ifalias
1332 * @len: size of buffer
1334 * get ifalias for a device. Caller must make sure dev cannot go
1335 * away, e.g. rcu read lock or own a reference count to device.
1337 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1339 const struct dev_ifalias *alias;
1343 alias = rcu_dereference(dev->ifalias);
1345 ret = snprintf(name, len, "%s", alias->ifalias);
1352 * netdev_features_change - device changes features
1353 * @dev: device to cause notification
1355 * Called to indicate a device has changed features.
1357 void netdev_features_change(struct net_device *dev)
1359 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1361 EXPORT_SYMBOL(netdev_features_change);
1364 * netdev_state_change - device changes state
1365 * @dev: device to cause notification
1367 * Called to indicate a device has changed state. This function calls
1368 * the notifier chains for netdev_chain and sends a NEWLINK message
1369 * to the routing socket.
1371 void netdev_state_change(struct net_device *dev)
1373 if (dev->flags & IFF_UP) {
1374 struct netdev_notifier_change_info change_info = {
1378 call_netdevice_notifiers_info(NETDEV_CHANGE,
1380 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1383 EXPORT_SYMBOL(netdev_state_change);
1386 * netdev_notify_peers - notify network peers about existence of @dev
1387 * @dev: network device
1389 * Generate traffic such that interested network peers are aware of
1390 * @dev, such as by generating a gratuitous ARP. This may be used when
1391 * a device wants to inform the rest of the network about some sort of
1392 * reconfiguration such as a failover event or virtual machine
1395 void netdev_notify_peers(struct net_device *dev)
1398 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1399 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1402 EXPORT_SYMBOL(netdev_notify_peers);
1404 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1406 const struct net_device_ops *ops = dev->netdev_ops;
1411 if (!netif_device_present(dev))
1414 /* Block netpoll from trying to do any rx path servicing.
1415 * If we don't do this there is a chance ndo_poll_controller
1416 * or ndo_poll may be running while we open the device
1418 netpoll_poll_disable(dev);
1420 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1421 ret = notifier_to_errno(ret);
1425 set_bit(__LINK_STATE_START, &dev->state);
1427 if (ops->ndo_validate_addr)
1428 ret = ops->ndo_validate_addr(dev);
1430 if (!ret && ops->ndo_open)
1431 ret = ops->ndo_open(dev);
1433 netpoll_poll_enable(dev);
1436 clear_bit(__LINK_STATE_START, &dev->state);
1438 dev->flags |= IFF_UP;
1439 dev_set_rx_mode(dev);
1441 add_device_randomness(dev->dev_addr, dev->addr_len);
1448 * dev_open - prepare an interface for use.
1449 * @dev: device to open
1450 * @extack: netlink extended ack
1452 * Takes a device from down to up state. The device's private open
1453 * function is invoked and then the multicast lists are loaded. Finally
1454 * the device is moved into the up state and a %NETDEV_UP message is
1455 * sent to the netdev notifier chain.
1457 * Calling this function on an active interface is a nop. On a failure
1458 * a negative errno code is returned.
1460 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1464 if (dev->flags & IFF_UP)
1467 ret = __dev_open(dev, extack);
1471 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1472 call_netdevice_notifiers(NETDEV_UP, dev);
1476 EXPORT_SYMBOL(dev_open);
1478 static void __dev_close_many(struct list_head *head)
1480 struct net_device *dev;
1485 list_for_each_entry(dev, head, close_list) {
1486 /* Temporarily disable netpoll until the interface is down */
1487 netpoll_poll_disable(dev);
1489 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1491 clear_bit(__LINK_STATE_START, &dev->state);
1493 /* Synchronize to scheduled poll. We cannot touch poll list, it
1494 * can be even on different cpu. So just clear netif_running().
1496 * dev->stop() will invoke napi_disable() on all of it's
1497 * napi_struct instances on this device.
1499 smp_mb__after_atomic(); /* Commit netif_running(). */
1502 dev_deactivate_many(head);
1504 list_for_each_entry(dev, head, close_list) {
1505 const struct net_device_ops *ops = dev->netdev_ops;
1508 * Call the device specific close. This cannot fail.
1509 * Only if device is UP
1511 * We allow it to be called even after a DETACH hot-plug
1517 dev->flags &= ~IFF_UP;
1518 netpoll_poll_enable(dev);
1522 static void __dev_close(struct net_device *dev)
1526 list_add(&dev->close_list, &single);
1527 __dev_close_many(&single);
1531 void dev_close_many(struct list_head *head, bool unlink)
1533 struct net_device *dev, *tmp;
1535 /* Remove the devices that don't need to be closed */
1536 list_for_each_entry_safe(dev, tmp, head, close_list)
1537 if (!(dev->flags & IFF_UP))
1538 list_del_init(&dev->close_list);
1540 __dev_close_many(head);
1542 list_for_each_entry_safe(dev, tmp, head, close_list) {
1543 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1544 call_netdevice_notifiers(NETDEV_DOWN, dev);
1546 list_del_init(&dev->close_list);
1549 EXPORT_SYMBOL(dev_close_many);
1552 * dev_close - shutdown an interface.
1553 * @dev: device to shutdown
1555 * This function moves an active device into down state. A
1556 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1557 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1560 void dev_close(struct net_device *dev)
1562 if (dev->flags & IFF_UP) {
1565 list_add(&dev->close_list, &single);
1566 dev_close_many(&single, true);
1570 EXPORT_SYMBOL(dev_close);
1574 * dev_disable_lro - disable Large Receive Offload on a device
1577 * Disable Large Receive Offload (LRO) on a net device. Must be
1578 * called under RTNL. This is needed if received packets may be
1579 * forwarded to another interface.
1581 void dev_disable_lro(struct net_device *dev)
1583 struct net_device *lower_dev;
1584 struct list_head *iter;
1586 dev->wanted_features &= ~NETIF_F_LRO;
1587 netdev_update_features(dev);
1589 if (unlikely(dev->features & NETIF_F_LRO))
1590 netdev_WARN(dev, "failed to disable LRO!\n");
1592 netdev_for_each_lower_dev(dev, lower_dev, iter)
1593 dev_disable_lro(lower_dev);
1595 EXPORT_SYMBOL(dev_disable_lro);
1598 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1601 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1602 * called under RTNL. This is needed if Generic XDP is installed on
1605 static void dev_disable_gro_hw(struct net_device *dev)
1607 dev->wanted_features &= ~NETIF_F_GRO_HW;
1608 netdev_update_features(dev);
1610 if (unlikely(dev->features & NETIF_F_GRO_HW))
1611 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1614 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1617 case NETDEV_##val: \
1618 return "NETDEV_" __stringify(val);
1620 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1621 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1622 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1623 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1624 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1625 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1626 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1627 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1628 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1632 return "UNKNOWN_NETDEV_EVENT";
1634 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1636 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1637 struct net_device *dev)
1639 struct netdev_notifier_info info = {
1643 return nb->notifier_call(nb, val, &info);
1646 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1647 struct net_device *dev)
1651 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1652 err = notifier_to_errno(err);
1656 if (!(dev->flags & IFF_UP))
1659 call_netdevice_notifier(nb, NETDEV_UP, dev);
1663 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1664 struct net_device *dev)
1666 if (dev->flags & IFF_UP) {
1667 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1669 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1671 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1674 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1677 struct net_device *dev;
1680 for_each_netdev(net, dev) {
1681 err = call_netdevice_register_notifiers(nb, dev);
1688 for_each_netdev_continue_reverse(net, dev)
1689 call_netdevice_unregister_notifiers(nb, dev);
1693 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1696 struct net_device *dev;
1698 for_each_netdev(net, dev)
1699 call_netdevice_unregister_notifiers(nb, dev);
1702 static int dev_boot_phase = 1;
1705 * register_netdevice_notifier - register a network notifier block
1708 * Register a notifier to be called when network device events occur.
1709 * The notifier passed is linked into the kernel structures and must
1710 * not be reused until it has been unregistered. A negative errno code
1711 * is returned on a failure.
1713 * When registered all registration and up events are replayed
1714 * to the new notifier to allow device to have a race free
1715 * view of the network device list.
1718 int register_netdevice_notifier(struct notifier_block *nb)
1723 /* Close race with setup_net() and cleanup_net() */
1724 down_write(&pernet_ops_rwsem);
1726 err = raw_notifier_chain_register(&netdev_chain, nb);
1732 err = call_netdevice_register_net_notifiers(nb, net);
1739 up_write(&pernet_ops_rwsem);
1743 for_each_net_continue_reverse(net)
1744 call_netdevice_unregister_net_notifiers(nb, net);
1746 raw_notifier_chain_unregister(&netdev_chain, nb);
1749 EXPORT_SYMBOL(register_netdevice_notifier);
1752 * unregister_netdevice_notifier - unregister a network notifier block
1755 * Unregister a notifier previously registered by
1756 * register_netdevice_notifier(). The notifier is unlinked into the
1757 * kernel structures and may then be reused. A negative errno code
1758 * is returned on a failure.
1760 * After unregistering unregister and down device events are synthesized
1761 * for all devices on the device list to the removed notifier to remove
1762 * the need for special case cleanup code.
1765 int unregister_netdevice_notifier(struct notifier_block *nb)
1770 /* Close race with setup_net() and cleanup_net() */
1771 down_write(&pernet_ops_rwsem);
1773 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1778 call_netdevice_unregister_net_notifiers(nb, net);
1782 up_write(&pernet_ops_rwsem);
1785 EXPORT_SYMBOL(unregister_netdevice_notifier);
1787 static int __register_netdevice_notifier_net(struct net *net,
1788 struct notifier_block *nb,
1789 bool ignore_call_fail)
1793 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1799 err = call_netdevice_register_net_notifiers(nb, net);
1800 if (err && !ignore_call_fail)
1801 goto chain_unregister;
1806 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1810 static int __unregister_netdevice_notifier_net(struct net *net,
1811 struct notifier_block *nb)
1815 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1819 call_netdevice_unregister_net_notifiers(nb, net);
1824 * register_netdevice_notifier_net - register a per-netns network notifier block
1825 * @net: network namespace
1828 * Register a notifier to be called when network device events occur.
1829 * The notifier passed is linked into the kernel structures and must
1830 * not be reused until it has been unregistered. A negative errno code
1831 * is returned on a failure.
1833 * When registered all registration and up events are replayed
1834 * to the new notifier to allow device to have a race free
1835 * view of the network device list.
1838 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1843 err = __register_netdevice_notifier_net(net, nb, false);
1847 EXPORT_SYMBOL(register_netdevice_notifier_net);
1850 * unregister_netdevice_notifier_net - unregister a per-netns
1851 * network notifier block
1852 * @net: network namespace
1855 * Unregister a notifier previously registered by
1856 * register_netdevice_notifier(). The notifier is unlinked into the
1857 * kernel structures and may then be reused. A negative errno code
1858 * is returned on a failure.
1860 * After unregistering unregister and down device events are synthesized
1861 * for all devices on the device list to the removed notifier to remove
1862 * the need for special case cleanup code.
1865 int unregister_netdevice_notifier_net(struct net *net,
1866 struct notifier_block *nb)
1871 err = __unregister_netdevice_notifier_net(net, nb);
1875 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1878 * call_netdevice_notifiers_info - call all network notifier blocks
1879 * @val: value passed unmodified to notifier function
1880 * @info: notifier information data
1882 * Call all network notifier blocks. Parameters and return value
1883 * are as for raw_notifier_call_chain().
1886 static int call_netdevice_notifiers_info(unsigned long val,
1887 struct netdev_notifier_info *info)
1889 struct net *net = dev_net(info->dev);
1894 /* Run per-netns notifier block chain first, then run the global one.
1895 * Hopefully, one day, the global one is going to be removed after
1896 * all notifier block registrators get converted to be per-netns.
1898 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1899 if (ret & NOTIFY_STOP_MASK)
1901 return raw_notifier_call_chain(&netdev_chain, val, info);
1904 static int call_netdevice_notifiers_extack(unsigned long val,
1905 struct net_device *dev,
1906 struct netlink_ext_ack *extack)
1908 struct netdev_notifier_info info = {
1913 return call_netdevice_notifiers_info(val, &info);
1917 * call_netdevice_notifiers - call all network notifier blocks
1918 * @val: value passed unmodified to notifier function
1919 * @dev: net_device pointer passed unmodified to notifier function
1921 * Call all network notifier blocks. Parameters and return value
1922 * are as for raw_notifier_call_chain().
1925 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1927 return call_netdevice_notifiers_extack(val, dev, NULL);
1929 EXPORT_SYMBOL(call_netdevice_notifiers);
1932 * call_netdevice_notifiers_mtu - call all network notifier blocks
1933 * @val: value passed unmodified to notifier function
1934 * @dev: net_device pointer passed unmodified to notifier function
1935 * @arg: additional u32 argument passed to the notifier function
1937 * Call all network notifier blocks. Parameters and return value
1938 * are as for raw_notifier_call_chain().
1940 static int call_netdevice_notifiers_mtu(unsigned long val,
1941 struct net_device *dev, u32 arg)
1943 struct netdev_notifier_info_ext info = {
1948 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
1950 return call_netdevice_notifiers_info(val, &info.info);
1953 #ifdef CONFIG_NET_INGRESS
1954 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
1956 void net_inc_ingress_queue(void)
1958 static_branch_inc(&ingress_needed_key);
1960 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
1962 void net_dec_ingress_queue(void)
1964 static_branch_dec(&ingress_needed_key);
1966 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
1969 #ifdef CONFIG_NET_EGRESS
1970 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
1972 void net_inc_egress_queue(void)
1974 static_branch_inc(&egress_needed_key);
1976 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
1978 void net_dec_egress_queue(void)
1980 static_branch_dec(&egress_needed_key);
1982 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
1985 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
1986 #ifdef CONFIG_JUMP_LABEL
1987 static atomic_t netstamp_needed_deferred;
1988 static atomic_t netstamp_wanted;
1989 static void netstamp_clear(struct work_struct *work)
1991 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
1994 wanted = atomic_add_return(deferred, &netstamp_wanted);
1996 static_branch_enable(&netstamp_needed_key);
1998 static_branch_disable(&netstamp_needed_key);
2000 static DECLARE_WORK(netstamp_work, netstamp_clear);
2003 void net_enable_timestamp(void)
2005 #ifdef CONFIG_JUMP_LABEL
2009 wanted = atomic_read(&netstamp_wanted);
2012 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2015 atomic_inc(&netstamp_needed_deferred);
2016 schedule_work(&netstamp_work);
2018 static_branch_inc(&netstamp_needed_key);
2021 EXPORT_SYMBOL(net_enable_timestamp);
2023 void net_disable_timestamp(void)
2025 #ifdef CONFIG_JUMP_LABEL
2029 wanted = atomic_read(&netstamp_wanted);
2032 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2035 atomic_dec(&netstamp_needed_deferred);
2036 schedule_work(&netstamp_work);
2038 static_branch_dec(&netstamp_needed_key);
2041 EXPORT_SYMBOL(net_disable_timestamp);
2043 static inline void net_timestamp_set(struct sk_buff *skb)
2046 if (static_branch_unlikely(&netstamp_needed_key))
2047 __net_timestamp(skb);
2050 #define net_timestamp_check(COND, SKB) \
2051 if (static_branch_unlikely(&netstamp_needed_key)) { \
2052 if ((COND) && !(SKB)->tstamp) \
2053 __net_timestamp(SKB); \
2056 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2060 if (!(dev->flags & IFF_UP))
2063 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
2064 if (skb->len <= len)
2067 /* if TSO is enabled, we don't care about the length as the packet
2068 * could be forwarded without being segmented before
2070 if (skb_is_gso(skb))
2075 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2077 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2079 int ret = ____dev_forward_skb(dev, skb);
2082 skb->protocol = eth_type_trans(skb, dev);
2083 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2088 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2091 * dev_forward_skb - loopback an skb to another netif
2093 * @dev: destination network device
2094 * @skb: buffer to forward
2097 * NET_RX_SUCCESS (no congestion)
2098 * NET_RX_DROP (packet was dropped, but freed)
2100 * dev_forward_skb can be used for injecting an skb from the
2101 * start_xmit function of one device into the receive queue
2102 * of another device.
2104 * The receiving device may be in another namespace, so
2105 * we have to clear all information in the skb that could
2106 * impact namespace isolation.
2108 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2110 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2112 EXPORT_SYMBOL_GPL(dev_forward_skb);
2114 static inline int deliver_skb(struct sk_buff *skb,
2115 struct packet_type *pt_prev,
2116 struct net_device *orig_dev)
2118 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2120 refcount_inc(&skb->users);
2121 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2124 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2125 struct packet_type **pt,
2126 struct net_device *orig_dev,
2128 struct list_head *ptype_list)
2130 struct packet_type *ptype, *pt_prev = *pt;
2132 list_for_each_entry_rcu(ptype, ptype_list, list) {
2133 if (ptype->type != type)
2136 deliver_skb(skb, pt_prev, orig_dev);
2142 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2144 if (!ptype->af_packet_priv || !skb->sk)
2147 if (ptype->id_match)
2148 return ptype->id_match(ptype, skb->sk);
2149 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2156 * dev_nit_active - return true if any network interface taps are in use
2158 * @dev: network device to check for the presence of taps
2160 bool dev_nit_active(struct net_device *dev)
2162 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2164 EXPORT_SYMBOL_GPL(dev_nit_active);
2167 * Support routine. Sends outgoing frames to any network
2168 * taps currently in use.
2171 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2173 struct packet_type *ptype;
2174 struct sk_buff *skb2 = NULL;
2175 struct packet_type *pt_prev = NULL;
2176 struct list_head *ptype_list = &ptype_all;
2180 list_for_each_entry_rcu(ptype, ptype_list, list) {
2181 if (ptype->ignore_outgoing)
2184 /* Never send packets back to the socket
2185 * they originated from - MvS (miquels@drinkel.ow.org)
2187 if (skb_loop_sk(ptype, skb))
2191 deliver_skb(skb2, pt_prev, skb->dev);
2196 /* need to clone skb, done only once */
2197 skb2 = skb_clone(skb, GFP_ATOMIC);
2201 net_timestamp_set(skb2);
2203 /* skb->nh should be correctly
2204 * set by sender, so that the second statement is
2205 * just protection against buggy protocols.
2207 skb_reset_mac_header(skb2);
2209 if (skb_network_header(skb2) < skb2->data ||
2210 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2211 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2212 ntohs(skb2->protocol),
2214 skb_reset_network_header(skb2);
2217 skb2->transport_header = skb2->network_header;
2218 skb2->pkt_type = PACKET_OUTGOING;
2222 if (ptype_list == &ptype_all) {
2223 ptype_list = &dev->ptype_all;
2228 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2229 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2235 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2238 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2239 * @dev: Network device
2240 * @txq: number of queues available
2242 * If real_num_tx_queues is changed the tc mappings may no longer be
2243 * valid. To resolve this verify the tc mapping remains valid and if
2244 * not NULL the mapping. With no priorities mapping to this
2245 * offset/count pair it will no longer be used. In the worst case TC0
2246 * is invalid nothing can be done so disable priority mappings. If is
2247 * expected that drivers will fix this mapping if they can before
2248 * calling netif_set_real_num_tx_queues.
2250 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2253 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2255 /* If TC0 is invalidated disable TC mapping */
2256 if (tc->offset + tc->count > txq) {
2257 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2262 /* Invalidated prio to tc mappings set to TC0 */
2263 for (i = 1; i < TC_BITMASK + 1; i++) {
2264 int q = netdev_get_prio_tc_map(dev, i);
2266 tc = &dev->tc_to_txq[q];
2267 if (tc->offset + tc->count > txq) {
2268 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2270 netdev_set_prio_tc_map(dev, i, 0);
2275 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2278 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2281 /* walk through the TCs and see if it falls into any of them */
2282 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2283 if ((txq - tc->offset) < tc->count)
2287 /* didn't find it, just return -1 to indicate no match */
2293 EXPORT_SYMBOL(netdev_txq_to_tc);
2296 struct static_key xps_needed __read_mostly;
2297 EXPORT_SYMBOL(xps_needed);
2298 struct static_key xps_rxqs_needed __read_mostly;
2299 EXPORT_SYMBOL(xps_rxqs_needed);
2300 static DEFINE_MUTEX(xps_map_mutex);
2301 #define xmap_dereference(P) \
2302 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2304 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2307 struct xps_map *map = NULL;
2311 map = xmap_dereference(dev_maps->attr_map[tci]);
2315 for (pos = map->len; pos--;) {
2316 if (map->queues[pos] != index)
2320 map->queues[pos] = map->queues[--map->len];
2324 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2325 kfree_rcu(map, rcu);
2332 static bool remove_xps_queue_cpu(struct net_device *dev,
2333 struct xps_dev_maps *dev_maps,
2334 int cpu, u16 offset, u16 count)
2336 int num_tc = dev->num_tc ? : 1;
2337 bool active = false;
2340 for (tci = cpu * num_tc; num_tc--; tci++) {
2343 for (i = count, j = offset; i--; j++) {
2344 if (!remove_xps_queue(dev_maps, tci, j))
2354 static void reset_xps_maps(struct net_device *dev,
2355 struct xps_dev_maps *dev_maps,
2359 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2360 RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2362 RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2364 static_key_slow_dec_cpuslocked(&xps_needed);
2365 kfree_rcu(dev_maps, rcu);
2368 static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2369 struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2370 u16 offset, u16 count, bool is_rxqs_map)
2372 bool active = false;
2375 for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2377 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2380 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2383 for (i = offset + (count - 1); count--; i--) {
2384 netdev_queue_numa_node_write(
2385 netdev_get_tx_queue(dev, i),
2391 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2394 const unsigned long *possible_mask = NULL;
2395 struct xps_dev_maps *dev_maps;
2396 unsigned int nr_ids;
2398 if (!static_key_false(&xps_needed))
2402 mutex_lock(&xps_map_mutex);
2404 if (static_key_false(&xps_rxqs_needed)) {
2405 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2407 nr_ids = dev->num_rx_queues;
2408 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2409 offset, count, true);
2413 dev_maps = xmap_dereference(dev->xps_cpus_map);
2417 if (num_possible_cpus() > 1)
2418 possible_mask = cpumask_bits(cpu_possible_mask);
2419 nr_ids = nr_cpu_ids;
2420 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2424 mutex_unlock(&xps_map_mutex);
2428 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2430 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2433 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2434 u16 index, bool is_rxqs_map)
2436 struct xps_map *new_map;
2437 int alloc_len = XPS_MIN_MAP_ALLOC;
2440 for (pos = 0; map && pos < map->len; pos++) {
2441 if (map->queues[pos] != index)
2446 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2448 if (pos < map->alloc_len)
2451 alloc_len = map->alloc_len * 2;
2454 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2458 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2460 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2461 cpu_to_node(attr_index));
2465 for (i = 0; i < pos; i++)
2466 new_map->queues[i] = map->queues[i];
2467 new_map->alloc_len = alloc_len;
2473 /* Must be called under cpus_read_lock */
2474 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2475 u16 index, bool is_rxqs_map)
2477 const unsigned long *online_mask = NULL, *possible_mask = NULL;
2478 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2479 int i, j, tci, numa_node_id = -2;
2480 int maps_sz, num_tc = 1, tc = 0;
2481 struct xps_map *map, *new_map;
2482 bool active = false;
2483 unsigned int nr_ids;
2486 /* Do not allow XPS on subordinate device directly */
2487 num_tc = dev->num_tc;
2491 /* If queue belongs to subordinate dev use its map */
2492 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2494 tc = netdev_txq_to_tc(dev, index);
2499 mutex_lock(&xps_map_mutex);
2501 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2502 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2503 nr_ids = dev->num_rx_queues;
2505 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2506 if (num_possible_cpus() > 1) {
2507 online_mask = cpumask_bits(cpu_online_mask);
2508 possible_mask = cpumask_bits(cpu_possible_mask);
2510 dev_maps = xmap_dereference(dev->xps_cpus_map);
2511 nr_ids = nr_cpu_ids;
2514 if (maps_sz < L1_CACHE_BYTES)
2515 maps_sz = L1_CACHE_BYTES;
2517 /* allocate memory for queue storage */
2518 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2521 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2522 if (!new_dev_maps) {
2523 mutex_unlock(&xps_map_mutex);
2527 tci = j * num_tc + tc;
2528 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2531 map = expand_xps_map(map, j, index, is_rxqs_map);
2535 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2539 goto out_no_new_maps;
2542 /* Increment static keys at most once per type */
2543 static_key_slow_inc_cpuslocked(&xps_needed);
2545 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2548 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2550 /* copy maps belonging to foreign traffic classes */
2551 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2552 /* fill in the new device map from the old device map */
2553 map = xmap_dereference(dev_maps->attr_map[tci]);
2554 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2557 /* We need to explicitly update tci as prevous loop
2558 * could break out early if dev_maps is NULL.
2560 tci = j * num_tc + tc;
2562 if (netif_attr_test_mask(j, mask, nr_ids) &&
2563 netif_attr_test_online(j, online_mask, nr_ids)) {
2564 /* add tx-queue to CPU/rx-queue maps */
2567 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2568 while ((pos < map->len) && (map->queues[pos] != index))
2571 if (pos == map->len)
2572 map->queues[map->len++] = index;
2575 if (numa_node_id == -2)
2576 numa_node_id = cpu_to_node(j);
2577 else if (numa_node_id != cpu_to_node(j))
2581 } else if (dev_maps) {
2582 /* fill in the new device map from the old device map */
2583 map = xmap_dereference(dev_maps->attr_map[tci]);
2584 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2587 /* copy maps belonging to foreign traffic classes */
2588 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2589 /* fill in the new device map from the old device map */
2590 map = xmap_dereference(dev_maps->attr_map[tci]);
2591 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2596 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2598 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2600 /* Cleanup old maps */
2602 goto out_no_old_maps;
2604 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2606 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2607 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2608 map = xmap_dereference(dev_maps->attr_map[tci]);
2609 if (map && map != new_map)
2610 kfree_rcu(map, rcu);
2614 kfree_rcu(dev_maps, rcu);
2617 dev_maps = new_dev_maps;
2622 /* update Tx queue numa node */
2623 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2624 (numa_node_id >= 0) ?
2625 numa_node_id : NUMA_NO_NODE);
2631 /* removes tx-queue from unused CPUs/rx-queues */
2632 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2634 for (i = tc, tci = j * num_tc; i--; tci++)
2635 active |= remove_xps_queue(dev_maps, tci, index);
2636 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2637 !netif_attr_test_online(j, online_mask, nr_ids))
2638 active |= remove_xps_queue(dev_maps, tci, index);
2639 for (i = num_tc - tc, tci++; --i; tci++)
2640 active |= remove_xps_queue(dev_maps, tci, index);
2643 /* free map if not active */
2645 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2648 mutex_unlock(&xps_map_mutex);
2652 /* remove any maps that we added */
2653 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2655 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2656 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2658 xmap_dereference(dev_maps->attr_map[tci]) :
2660 if (new_map && new_map != map)
2665 mutex_unlock(&xps_map_mutex);
2667 kfree(new_dev_maps);
2670 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2672 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2678 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2683 EXPORT_SYMBOL(netif_set_xps_queue);
2686 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2688 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2690 /* Unbind any subordinate channels */
2691 while (txq-- != &dev->_tx[0]) {
2693 netdev_unbind_sb_channel(dev, txq->sb_dev);
2697 void netdev_reset_tc(struct net_device *dev)
2700 netif_reset_xps_queues_gt(dev, 0);
2702 netdev_unbind_all_sb_channels(dev);
2704 /* Reset TC configuration of device */
2706 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2707 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2709 EXPORT_SYMBOL(netdev_reset_tc);
2711 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2713 if (tc >= dev->num_tc)
2717 netif_reset_xps_queues(dev, offset, count);
2719 dev->tc_to_txq[tc].count = count;
2720 dev->tc_to_txq[tc].offset = offset;
2723 EXPORT_SYMBOL(netdev_set_tc_queue);
2725 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2727 if (num_tc > TC_MAX_QUEUE)
2731 netif_reset_xps_queues_gt(dev, 0);
2733 netdev_unbind_all_sb_channels(dev);
2735 dev->num_tc = num_tc;
2738 EXPORT_SYMBOL(netdev_set_num_tc);
2740 void netdev_unbind_sb_channel(struct net_device *dev,
2741 struct net_device *sb_dev)
2743 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2746 netif_reset_xps_queues_gt(sb_dev, 0);
2748 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2749 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2751 while (txq-- != &dev->_tx[0]) {
2752 if (txq->sb_dev == sb_dev)
2756 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2758 int netdev_bind_sb_channel_queue(struct net_device *dev,
2759 struct net_device *sb_dev,
2760 u8 tc, u16 count, u16 offset)
2762 /* Make certain the sb_dev and dev are already configured */
2763 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2766 /* We cannot hand out queues we don't have */
2767 if ((offset + count) > dev->real_num_tx_queues)
2770 /* Record the mapping */
2771 sb_dev->tc_to_txq[tc].count = count;
2772 sb_dev->tc_to_txq[tc].offset = offset;
2774 /* Provide a way for Tx queue to find the tc_to_txq map or
2775 * XPS map for itself.
2778 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2782 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2784 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2786 /* Do not use a multiqueue device to represent a subordinate channel */
2787 if (netif_is_multiqueue(dev))
2790 /* We allow channels 1 - 32767 to be used for subordinate channels.
2791 * Channel 0 is meant to be "native" mode and used only to represent
2792 * the main root device. We allow writing 0 to reset the device back
2793 * to normal mode after being used as a subordinate channel.
2795 if (channel > S16_MAX)
2798 dev->num_tc = -channel;
2802 EXPORT_SYMBOL(netdev_set_sb_channel);
2805 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2806 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2808 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2813 disabling = txq < dev->real_num_tx_queues;
2815 if (txq < 1 || txq > dev->num_tx_queues)
2818 if (dev->reg_state == NETREG_REGISTERED ||
2819 dev->reg_state == NETREG_UNREGISTERING) {
2822 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2828 netif_setup_tc(dev, txq);
2830 dev->real_num_tx_queues = txq;
2834 qdisc_reset_all_tx_gt(dev, txq);
2836 netif_reset_xps_queues_gt(dev, txq);
2840 dev->real_num_tx_queues = txq;
2845 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2849 * netif_set_real_num_rx_queues - set actual number of RX queues used
2850 * @dev: Network device
2851 * @rxq: Actual number of RX queues
2853 * This must be called either with the rtnl_lock held or before
2854 * registration of the net device. Returns 0 on success, or a
2855 * negative error code. If called before registration, it always
2858 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2862 if (rxq < 1 || rxq > dev->num_rx_queues)
2865 if (dev->reg_state == NETREG_REGISTERED) {
2868 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2874 dev->real_num_rx_queues = rxq;
2877 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2881 * netif_get_num_default_rss_queues - default number of RSS queues
2883 * This routine should set an upper limit on the number of RSS queues
2884 * used by default by multiqueue devices.
2886 int netif_get_num_default_rss_queues(void)
2888 return is_kdump_kernel() ?
2889 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2891 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2893 static void __netif_reschedule(struct Qdisc *q)
2895 struct softnet_data *sd;
2896 unsigned long flags;
2898 local_irq_save(flags);
2899 sd = this_cpu_ptr(&softnet_data);
2900 q->next_sched = NULL;
2901 *sd->output_queue_tailp = q;
2902 sd->output_queue_tailp = &q->next_sched;
2903 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2904 local_irq_restore(flags);
2907 void __netif_schedule(struct Qdisc *q)
2909 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2910 __netif_reschedule(q);
2912 EXPORT_SYMBOL(__netif_schedule);
2914 struct dev_kfree_skb_cb {
2915 enum skb_free_reason reason;
2918 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
2920 return (struct dev_kfree_skb_cb *)skb->cb;
2923 void netif_schedule_queue(struct netdev_queue *txq)
2926 if (!netif_xmit_stopped(txq)) {
2927 struct Qdisc *q = rcu_dereference(txq->qdisc);
2929 __netif_schedule(q);
2933 EXPORT_SYMBOL(netif_schedule_queue);
2935 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
2937 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
2941 q = rcu_dereference(dev_queue->qdisc);
2942 __netif_schedule(q);
2946 EXPORT_SYMBOL(netif_tx_wake_queue);
2948 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
2950 unsigned long flags;
2955 if (likely(refcount_read(&skb->users) == 1)) {
2957 refcount_set(&skb->users, 0);
2958 } else if (likely(!refcount_dec_and_test(&skb->users))) {
2961 get_kfree_skb_cb(skb)->reason = reason;
2962 local_irq_save(flags);
2963 skb->next = __this_cpu_read(softnet_data.completion_queue);
2964 __this_cpu_write(softnet_data.completion_queue, skb);
2965 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2966 local_irq_restore(flags);
2968 EXPORT_SYMBOL(__dev_kfree_skb_irq);
2970 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
2972 if (in_irq() || irqs_disabled())
2973 __dev_kfree_skb_irq(skb, reason);
2977 EXPORT_SYMBOL(__dev_kfree_skb_any);
2981 * netif_device_detach - mark device as removed
2982 * @dev: network device
2984 * Mark device as removed from system and therefore no longer available.
2986 void netif_device_detach(struct net_device *dev)
2988 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
2989 netif_running(dev)) {
2990 netif_tx_stop_all_queues(dev);
2993 EXPORT_SYMBOL(netif_device_detach);
2996 * netif_device_attach - mark device as attached
2997 * @dev: network device
2999 * Mark device as attached from system and restart if needed.
3001 void netif_device_attach(struct net_device *dev)
3003 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3004 netif_running(dev)) {
3005 netif_tx_wake_all_queues(dev);
3006 __netdev_watchdog_up(dev);
3009 EXPORT_SYMBOL(netif_device_attach);
3012 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3013 * to be used as a distribution range.
3015 static u16 skb_tx_hash(const struct net_device *dev,
3016 const struct net_device *sb_dev,
3017 struct sk_buff *skb)
3021 u16 qcount = dev->real_num_tx_queues;
3024 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3026 qoffset = sb_dev->tc_to_txq[tc].offset;
3027 qcount = sb_dev->tc_to_txq[tc].count;
3030 if (skb_rx_queue_recorded(skb)) {
3031 hash = skb_get_rx_queue(skb);
3032 while (unlikely(hash >= qcount))
3034 return hash + qoffset;
3037 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3040 static void skb_warn_bad_offload(const struct sk_buff *skb)
3042 static const netdev_features_t null_features;
3043 struct net_device *dev = skb->dev;
3044 const char *name = "";
3046 if (!net_ratelimit())
3050 if (dev->dev.parent)
3051 name = dev_driver_string(dev->dev.parent);
3053 name = netdev_name(dev);
3055 skb_dump(KERN_WARNING, skb, false);
3056 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3057 name, dev ? &dev->features : &null_features,
3058 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3062 * Invalidate hardware checksum when packet is to be mangled, and
3063 * complete checksum manually on outgoing path.
3065 int skb_checksum_help(struct sk_buff *skb)
3068 int ret = 0, offset;
3070 if (skb->ip_summed == CHECKSUM_COMPLETE)
3071 goto out_set_summed;
3073 if (unlikely(skb_shinfo(skb)->gso_size)) {
3074 skb_warn_bad_offload(skb);
3078 /* Before computing a checksum, we should make sure no frag could
3079 * be modified by an external entity : checksum could be wrong.
3081 if (skb_has_shared_frag(skb)) {
3082 ret = __skb_linearize(skb);
3087 offset = skb_checksum_start_offset(skb);
3088 BUG_ON(offset >= skb_headlen(skb));
3089 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3091 offset += skb->csum_offset;
3092 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3094 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3098 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3100 skb->ip_summed = CHECKSUM_NONE;
3104 EXPORT_SYMBOL(skb_checksum_help);
3106 int skb_crc32c_csum_help(struct sk_buff *skb)
3109 int ret = 0, offset, start;
3111 if (skb->ip_summed != CHECKSUM_PARTIAL)
3114 if (unlikely(skb_is_gso(skb)))
3117 /* Before computing a checksum, we should make sure no frag could
3118 * be modified by an external entity : checksum could be wrong.
3120 if (unlikely(skb_has_shared_frag(skb))) {
3121 ret = __skb_linearize(skb);
3125 start = skb_checksum_start_offset(skb);
3126 offset = start + offsetof(struct sctphdr, checksum);
3127 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3132 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3136 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3137 skb->len - start, ~(__u32)0,
3139 *(__le32 *)(skb->data + offset) = crc32c_csum;
3140 skb->ip_summed = CHECKSUM_NONE;
3141 skb->csum_not_inet = 0;
3146 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3148 __be16 type = skb->protocol;
3150 /* Tunnel gso handlers can set protocol to ethernet. */
3151 if (type == htons(ETH_P_TEB)) {
3154 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3157 eth = (struct ethhdr *)skb->data;
3158 type = eth->h_proto;
3161 return __vlan_get_protocol(skb, type, depth);
3165 * skb_mac_gso_segment - mac layer segmentation handler.
3166 * @skb: buffer to segment
3167 * @features: features for the output path (see dev->features)
3169 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3170 netdev_features_t features)
3172 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3173 struct packet_offload *ptype;
3174 int vlan_depth = skb->mac_len;
3175 __be16 type = skb_network_protocol(skb, &vlan_depth);
3177 if (unlikely(!type))
3178 return ERR_PTR(-EINVAL);
3180 __skb_pull(skb, vlan_depth);
3183 list_for_each_entry_rcu(ptype, &offload_base, list) {
3184 if (ptype->type == type && ptype->callbacks.gso_segment) {
3185 segs = ptype->callbacks.gso_segment(skb, features);
3191 __skb_push(skb, skb->data - skb_mac_header(skb));
3195 EXPORT_SYMBOL(skb_mac_gso_segment);
3198 /* openvswitch calls this on rx path, so we need a different check.
3200 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3203 return skb->ip_summed != CHECKSUM_PARTIAL &&
3204 skb->ip_summed != CHECKSUM_UNNECESSARY;
3206 return skb->ip_summed == CHECKSUM_NONE;
3210 * __skb_gso_segment - Perform segmentation on skb.
3211 * @skb: buffer to segment
3212 * @features: features for the output path (see dev->features)
3213 * @tx_path: whether it is called in TX path
3215 * This function segments the given skb and returns a list of segments.
3217 * It may return NULL if the skb requires no segmentation. This is
3218 * only possible when GSO is used for verifying header integrity.
3220 * Segmentation preserves SKB_SGO_CB_OFFSET bytes of previous skb cb.
3222 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3223 netdev_features_t features, bool tx_path)
3225 struct sk_buff *segs;
3227 if (unlikely(skb_needs_check(skb, tx_path))) {
3230 /* We're going to init ->check field in TCP or UDP header */
3231 err = skb_cow_head(skb, 0);
3233 return ERR_PTR(err);
3236 /* Only report GSO partial support if it will enable us to
3237 * support segmentation on this frame without needing additional
3240 if (features & NETIF_F_GSO_PARTIAL) {
3241 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3242 struct net_device *dev = skb->dev;
3244 partial_features |= dev->features & dev->gso_partial_features;
3245 if (!skb_gso_ok(skb, features | partial_features))
3246 features &= ~NETIF_F_GSO_PARTIAL;
3249 BUILD_BUG_ON(SKB_SGO_CB_OFFSET +
3250 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3252 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3253 SKB_GSO_CB(skb)->encap_level = 0;
3255 skb_reset_mac_header(skb);
3256 skb_reset_mac_len(skb);
3258 segs = skb_mac_gso_segment(skb, features);
3260 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3261 skb_warn_bad_offload(skb);
3265 EXPORT_SYMBOL(__skb_gso_segment);
3267 /* Take action when hardware reception checksum errors are detected. */
3269 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3271 if (net_ratelimit()) {
3272 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3273 skb_dump(KERN_ERR, skb, true);
3277 EXPORT_SYMBOL(netdev_rx_csum_fault);
3280 /* XXX: check that highmem exists at all on the given machine. */
3281 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3283 #ifdef CONFIG_HIGHMEM
3286 if (!(dev->features & NETIF_F_HIGHDMA)) {
3287 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3288 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3290 if (PageHighMem(skb_frag_page(frag)))
3298 /* If MPLS offload request, verify we are testing hardware MPLS features
3299 * instead of standard features for the netdev.
3301 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3302 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3303 netdev_features_t features,
3306 if (eth_p_mpls(type))
3307 features &= skb->dev->mpls_features;
3312 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3313 netdev_features_t features,
3320 static netdev_features_t harmonize_features(struct sk_buff *skb,
3321 netdev_features_t features)
3326 type = skb_network_protocol(skb, &tmp);
3327 features = net_mpls_features(skb, features, type);
3329 if (skb->ip_summed != CHECKSUM_NONE &&
3330 !can_checksum_protocol(features, type)) {
3331 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3333 if (illegal_highdma(skb->dev, skb))
3334 features &= ~NETIF_F_SG;
3339 netdev_features_t passthru_features_check(struct sk_buff *skb,
3340 struct net_device *dev,
3341 netdev_features_t features)
3345 EXPORT_SYMBOL(passthru_features_check);
3347 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3348 struct net_device *dev,
3349 netdev_features_t features)
3351 return vlan_features_check(skb, features);
3354 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3355 struct net_device *dev,
3356 netdev_features_t features)
3358 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3360 if (gso_segs > dev->gso_max_segs)
3361 return features & ~NETIF_F_GSO_MASK;
3363 /* Support for GSO partial features requires software
3364 * intervention before we can actually process the packets
3365 * so we need to strip support for any partial features now
3366 * and we can pull them back in after we have partially
3367 * segmented the frame.
3369 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3370 features &= ~dev->gso_partial_features;
3372 /* Make sure to clear the IPv4 ID mangling feature if the
3373 * IPv4 header has the potential to be fragmented.
3375 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3376 struct iphdr *iph = skb->encapsulation ?
3377 inner_ip_hdr(skb) : ip_hdr(skb);
3379 if (!(iph->frag_off & htons(IP_DF)))
3380 features &= ~NETIF_F_TSO_MANGLEID;
3386 netdev_features_t netif_skb_features(struct sk_buff *skb)
3388 struct net_device *dev = skb->dev;
3389 netdev_features_t features = dev->features;
3391 if (skb_is_gso(skb))
3392 features = gso_features_check(skb, dev, features);
3394 /* If encapsulation offload request, verify we are testing
3395 * hardware encapsulation features instead of standard
3396 * features for the netdev
3398 if (skb->encapsulation)
3399 features &= dev->hw_enc_features;
3401 if (skb_vlan_tagged(skb))
3402 features = netdev_intersect_features(features,
3403 dev->vlan_features |
3404 NETIF_F_HW_VLAN_CTAG_TX |
3405 NETIF_F_HW_VLAN_STAG_TX);
3407 if (dev->netdev_ops->ndo_features_check)
3408 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3411 features &= dflt_features_check(skb, dev, features);
3413 return harmonize_features(skb, features);
3415 EXPORT_SYMBOL(netif_skb_features);
3417 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3418 struct netdev_queue *txq, bool more)
3423 if (dev_nit_active(dev))
3424 dev_queue_xmit_nit(skb, dev);
3427 trace_net_dev_start_xmit(skb, dev);
3428 rc = netdev_start_xmit(skb, dev, txq, more);
3429 trace_net_dev_xmit(skb, rc, dev, len);
3434 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3435 struct netdev_queue *txq, int *ret)
3437 struct sk_buff *skb = first;
3438 int rc = NETDEV_TX_OK;
3441 struct sk_buff *next = skb->next;
3443 skb_mark_not_on_list(skb);
3444 rc = xmit_one(skb, dev, txq, next != NULL);
3445 if (unlikely(!dev_xmit_complete(rc))) {
3451 if (netif_tx_queue_stopped(txq) && skb) {
3452 rc = NETDEV_TX_BUSY;
3462 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3463 netdev_features_t features)
3465 if (skb_vlan_tag_present(skb) &&
3466 !vlan_hw_offload_capable(features, skb->vlan_proto))
3467 skb = __vlan_hwaccel_push_inside(skb);
3471 int skb_csum_hwoffload_help(struct sk_buff *skb,
3472 const netdev_features_t features)
3474 if (unlikely(skb->csum_not_inet))
3475 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3476 skb_crc32c_csum_help(skb);
3478 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3480 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3482 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3484 netdev_features_t features;
3486 features = netif_skb_features(skb);
3487 skb = validate_xmit_vlan(skb, features);
3491 skb = sk_validate_xmit_skb(skb, dev);
3495 if (netif_needs_gso(skb, features)) {
3496 struct sk_buff *segs;
3498 segs = skb_gso_segment(skb, features);
3506 if (skb_needs_linearize(skb, features) &&
3507 __skb_linearize(skb))
3510 /* If packet is not checksummed and device does not
3511 * support checksumming for this protocol, complete
3512 * checksumming here.
3514 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3515 if (skb->encapsulation)
3516 skb_set_inner_transport_header(skb,
3517 skb_checksum_start_offset(skb));
3519 skb_set_transport_header(skb,
3520 skb_checksum_start_offset(skb));
3521 if (skb_csum_hwoffload_help(skb, features))
3526 skb = validate_xmit_xfrm(skb, features, again);
3533 atomic_long_inc(&dev->tx_dropped);
3537 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3539 struct sk_buff *next, *head = NULL, *tail;
3541 for (; skb != NULL; skb = next) {
3543 skb_mark_not_on_list(skb);
3545 /* in case skb wont be segmented, point to itself */
3548 skb = validate_xmit_skb(skb, dev, again);
3556 /* If skb was segmented, skb->prev points to
3557 * the last segment. If not, it still contains skb.
3563 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3565 static void qdisc_pkt_len_init(struct sk_buff *skb)
3567 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3569 qdisc_skb_cb(skb)->pkt_len = skb->len;
3571 /* To get more precise estimation of bytes sent on wire,
3572 * we add to pkt_len the headers size of all segments
3574 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3575 unsigned int hdr_len;
3576 u16 gso_segs = shinfo->gso_segs;
3578 /* mac layer + network layer */
3579 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3581 /* + transport layer */
3582 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3583 const struct tcphdr *th;
3584 struct tcphdr _tcphdr;
3586 th = skb_header_pointer(skb, skb_transport_offset(skb),
3587 sizeof(_tcphdr), &_tcphdr);
3589 hdr_len += __tcp_hdrlen(th);
3591 struct udphdr _udphdr;
3593 if (skb_header_pointer(skb, skb_transport_offset(skb),
3594 sizeof(_udphdr), &_udphdr))
3595 hdr_len += sizeof(struct udphdr);
3598 if (shinfo->gso_type & SKB_GSO_DODGY)
3599 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3602 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3606 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3607 struct net_device *dev,
3608 struct netdev_queue *txq)
3610 spinlock_t *root_lock = qdisc_lock(q);
3611 struct sk_buff *to_free = NULL;
3615 qdisc_calculate_pkt_len(skb, q);
3617 if (q->flags & TCQ_F_NOLOCK) {
3618 if ((q->flags & TCQ_F_CAN_BYPASS) && READ_ONCE(q->empty) &&
3619 qdisc_run_begin(q)) {
3620 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
3622 __qdisc_drop(skb, &to_free);
3626 qdisc_bstats_cpu_update(q, skb);
3628 rc = NET_XMIT_SUCCESS;
3629 if (sch_direct_xmit(skb, q, dev, txq, NULL, true))
3635 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3639 if (unlikely(to_free))
3640 kfree_skb_list(to_free);
3645 * Heuristic to force contended enqueues to serialize on a
3646 * separate lock before trying to get qdisc main lock.
3647 * This permits qdisc->running owner to get the lock more
3648 * often and dequeue packets faster.
3650 contended = qdisc_is_running(q);
3651 if (unlikely(contended))
3652 spin_lock(&q->busylock);
3654 spin_lock(root_lock);
3655 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3656 __qdisc_drop(skb, &to_free);
3658 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3659 qdisc_run_begin(q)) {
3661 * This is a work-conserving queue; there are no old skbs
3662 * waiting to be sent out; and the qdisc is not running -
3663 * xmit the skb directly.
3666 qdisc_bstats_update(q, skb);
3668 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3669 if (unlikely(contended)) {
3670 spin_unlock(&q->busylock);
3677 rc = NET_XMIT_SUCCESS;
3679 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3680 if (qdisc_run_begin(q)) {
3681 if (unlikely(contended)) {
3682 spin_unlock(&q->busylock);
3689 spin_unlock(root_lock);
3690 if (unlikely(to_free))
3691 kfree_skb_list(to_free);
3692 if (unlikely(contended))
3693 spin_unlock(&q->busylock);
3697 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3698 static void skb_update_prio(struct sk_buff *skb)
3700 const struct netprio_map *map;
3701 const struct sock *sk;
3702 unsigned int prioidx;
3706 map = rcu_dereference_bh(skb->dev->priomap);
3709 sk = skb_to_full_sk(skb);
3713 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3715 if (prioidx < map->priomap_len)
3716 skb->priority = map->priomap[prioidx];
3719 #define skb_update_prio(skb)
3723 * dev_loopback_xmit - loop back @skb
3724 * @net: network namespace this loopback is happening in
3725 * @sk: sk needed to be a netfilter okfn
3726 * @skb: buffer to transmit
3728 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3730 skb_reset_mac_header(skb);
3731 __skb_pull(skb, skb_network_offset(skb));
3732 skb->pkt_type = PACKET_LOOPBACK;
3733 skb->ip_summed = CHECKSUM_UNNECESSARY;
3734 WARN_ON(!skb_dst(skb));
3739 EXPORT_SYMBOL(dev_loopback_xmit);
3741 #ifdef CONFIG_NET_EGRESS
3742 static struct sk_buff *
3743 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3745 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3746 struct tcf_result cl_res;
3751 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3752 mini_qdisc_bstats_cpu_update(miniq, skb);
3754 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3756 case TC_ACT_RECLASSIFY:
3757 skb->tc_index = TC_H_MIN(cl_res.classid);
3760 mini_qdisc_qstats_cpu_drop(miniq);
3761 *ret = NET_XMIT_DROP;
3767 *ret = NET_XMIT_SUCCESS;
3770 case TC_ACT_REDIRECT:
3771 /* No need to push/pop skb's mac_header here on egress! */
3772 skb_do_redirect(skb);
3773 *ret = NET_XMIT_SUCCESS;
3781 #endif /* CONFIG_NET_EGRESS */
3784 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3785 struct xps_dev_maps *dev_maps, unsigned int tci)
3787 struct xps_map *map;
3788 int queue_index = -1;
3792 tci += netdev_get_prio_tc_map(dev, skb->priority);
3795 map = rcu_dereference(dev_maps->attr_map[tci]);
3798 queue_index = map->queues[0];
3800 queue_index = map->queues[reciprocal_scale(
3801 skb_get_hash(skb), map->len)];
3802 if (unlikely(queue_index >= dev->real_num_tx_queues))
3809 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3810 struct sk_buff *skb)
3813 struct xps_dev_maps *dev_maps;
3814 struct sock *sk = skb->sk;
3815 int queue_index = -1;
3817 if (!static_key_false(&xps_needed))
3821 if (!static_key_false(&xps_rxqs_needed))
3824 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3826 int tci = sk_rx_queue_get(sk);
3828 if (tci >= 0 && tci < dev->num_rx_queues)
3829 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3834 if (queue_index < 0) {
3835 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3837 unsigned int tci = skb->sender_cpu - 1;
3839 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3851 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3852 struct net_device *sb_dev)
3856 EXPORT_SYMBOL(dev_pick_tx_zero);
3858 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3859 struct net_device *sb_dev)
3861 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
3863 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
3865 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
3866 struct net_device *sb_dev)
3868 struct sock *sk = skb->sk;
3869 int queue_index = sk_tx_queue_get(sk);
3871 sb_dev = sb_dev ? : dev;
3873 if (queue_index < 0 || skb->ooo_okay ||
3874 queue_index >= dev->real_num_tx_queues) {
3875 int new_index = get_xps_queue(dev, sb_dev, skb);
3878 new_index = skb_tx_hash(dev, sb_dev, skb);
3880 if (queue_index != new_index && sk &&
3882 rcu_access_pointer(sk->sk_dst_cache))
3883 sk_tx_queue_set(sk, new_index);
3885 queue_index = new_index;
3890 EXPORT_SYMBOL(netdev_pick_tx);
3892 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
3893 struct sk_buff *skb,
3894 struct net_device *sb_dev)
3896 int queue_index = 0;
3899 u32 sender_cpu = skb->sender_cpu - 1;
3901 if (sender_cpu >= (u32)NR_CPUS)
3902 skb->sender_cpu = raw_smp_processor_id() + 1;
3905 if (dev->real_num_tx_queues != 1) {
3906 const struct net_device_ops *ops = dev->netdev_ops;
3908 if (ops->ndo_select_queue)
3909 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
3911 queue_index = netdev_pick_tx(dev, skb, sb_dev);
3913 queue_index = netdev_cap_txqueue(dev, queue_index);
3916 skb_set_queue_mapping(skb, queue_index);
3917 return netdev_get_tx_queue(dev, queue_index);
3921 * __dev_queue_xmit - transmit a buffer
3922 * @skb: buffer to transmit
3923 * @sb_dev: suboordinate device used for L2 forwarding offload
3925 * Queue a buffer for transmission to a network device. The caller must
3926 * have set the device and priority and built the buffer before calling
3927 * this function. The function can be called from an interrupt.
3929 * A negative errno code is returned on a failure. A success does not
3930 * guarantee the frame will be transmitted as it may be dropped due
3931 * to congestion or traffic shaping.
3933 * -----------------------------------------------------------------------------------
3934 * I notice this method can also return errors from the queue disciplines,
3935 * including NET_XMIT_DROP, which is a positive value. So, errors can also
3938 * Regardless of the return value, the skb is consumed, so it is currently
3939 * difficult to retry a send to this method. (You can bump the ref count
3940 * before sending to hold a reference for retry if you are careful.)
3942 * When calling this method, interrupts MUST be enabled. This is because
3943 * the BH enable code must have IRQs enabled so that it will not deadlock.
3946 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
3948 struct net_device *dev = skb->dev;
3949 struct netdev_queue *txq;
3954 skb_reset_mac_header(skb);
3956 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
3957 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
3959 /* Disable soft irqs for various locks below. Also
3960 * stops preemption for RCU.
3964 skb_update_prio(skb);
3966 qdisc_pkt_len_init(skb);
3967 #ifdef CONFIG_NET_CLS_ACT
3968 skb->tc_at_ingress = 0;
3969 # ifdef CONFIG_NET_EGRESS
3970 if (static_branch_unlikely(&egress_needed_key)) {
3971 skb = sch_handle_egress(skb, &rc, dev);
3977 /* If device/qdisc don't need skb->dst, release it right now while
3978 * its hot in this cpu cache.
3980 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
3985 txq = netdev_core_pick_tx(dev, skb, sb_dev);
3986 q = rcu_dereference_bh(txq->qdisc);
3988 trace_net_dev_queue(skb);
3990 rc = __dev_xmit_skb(skb, q, dev, txq);
3994 /* The device has no queue. Common case for software devices:
3995 * loopback, all the sorts of tunnels...
3997 * Really, it is unlikely that netif_tx_lock protection is necessary
3998 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4000 * However, it is possible, that they rely on protection
4003 * Check this and shot the lock. It is not prone from deadlocks.
4004 *Either shot noqueue qdisc, it is even simpler 8)
4006 if (dev->flags & IFF_UP) {
4007 int cpu = smp_processor_id(); /* ok because BHs are off */
4009 if (txq->xmit_lock_owner != cpu) {
4010 if (dev_xmit_recursion())
4011 goto recursion_alert;
4013 skb = validate_xmit_skb(skb, dev, &again);
4017 HARD_TX_LOCK(dev, txq, cpu);
4019 if (!netif_xmit_stopped(txq)) {
4020 dev_xmit_recursion_inc();
4021 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4022 dev_xmit_recursion_dec();
4023 if (dev_xmit_complete(rc)) {
4024 HARD_TX_UNLOCK(dev, txq);
4028 HARD_TX_UNLOCK(dev, txq);
4029 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4032 /* Recursion is detected! It is possible,
4036 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4042 rcu_read_unlock_bh();
4044 atomic_long_inc(&dev->tx_dropped);
4045 kfree_skb_list(skb);
4048 rcu_read_unlock_bh();
4052 int dev_queue_xmit(struct sk_buff *skb)
4054 return __dev_queue_xmit(skb, NULL);
4056 EXPORT_SYMBOL(dev_queue_xmit);
4058 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4060 return __dev_queue_xmit(skb, sb_dev);
4062 EXPORT_SYMBOL(dev_queue_xmit_accel);
4064 int dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4066 struct net_device *dev = skb->dev;
4067 struct sk_buff *orig_skb = skb;
4068 struct netdev_queue *txq;
4069 int ret = NETDEV_TX_BUSY;
4072 if (unlikely(!netif_running(dev) ||
4073 !netif_carrier_ok(dev)))
4076 skb = validate_xmit_skb_list(skb, dev, &again);
4077 if (skb != orig_skb)
4080 skb_set_queue_mapping(skb, queue_id);
4081 txq = skb_get_tx_queue(dev, skb);
4085 HARD_TX_LOCK(dev, txq, smp_processor_id());
4086 if (!netif_xmit_frozen_or_drv_stopped(txq))
4087 ret = netdev_start_xmit(skb, dev, txq, false);
4088 HARD_TX_UNLOCK(dev, txq);
4092 if (!dev_xmit_complete(ret))
4097 atomic_long_inc(&dev->tx_dropped);
4098 kfree_skb_list(skb);
4099 return NET_XMIT_DROP;
4101 EXPORT_SYMBOL(dev_direct_xmit);
4103 /*************************************************************************
4105 *************************************************************************/
4107 int netdev_max_backlog __read_mostly = 1000;
4108 EXPORT_SYMBOL(netdev_max_backlog);
4110 int netdev_tstamp_prequeue __read_mostly = 1;
4111 int netdev_budget __read_mostly = 300;
4112 unsigned int __read_mostly netdev_budget_usecs = 2000;
4113 int weight_p __read_mostly = 64; /* old backlog weight */
4114 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4115 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4116 int dev_rx_weight __read_mostly = 64;
4117 int dev_tx_weight __read_mostly = 64;
4118 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4119 int gro_normal_batch __read_mostly = 8;
4121 /* Called with irq disabled */
4122 static inline void ____napi_schedule(struct softnet_data *sd,
4123 struct napi_struct *napi)
4125 list_add_tail(&napi->poll_list, &sd->poll_list);
4126 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4131 /* One global table that all flow-based protocols share. */
4132 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4133 EXPORT_SYMBOL(rps_sock_flow_table);
4134 u32 rps_cpu_mask __read_mostly;
4135 EXPORT_SYMBOL(rps_cpu_mask);
4137 struct static_key_false rps_needed __read_mostly;
4138 EXPORT_SYMBOL(rps_needed);
4139 struct static_key_false rfs_needed __read_mostly;
4140 EXPORT_SYMBOL(rfs_needed);
4142 static struct rps_dev_flow *
4143 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4144 struct rps_dev_flow *rflow, u16 next_cpu)
4146 if (next_cpu < nr_cpu_ids) {
4147 #ifdef CONFIG_RFS_ACCEL
4148 struct netdev_rx_queue *rxqueue;
4149 struct rps_dev_flow_table *flow_table;
4150 struct rps_dev_flow *old_rflow;
4155 /* Should we steer this flow to a different hardware queue? */
4156 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4157 !(dev->features & NETIF_F_NTUPLE))
4159 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4160 if (rxq_index == skb_get_rx_queue(skb))
4163 rxqueue = dev->_rx + rxq_index;
4164 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4167 flow_id = skb_get_hash(skb) & flow_table->mask;
4168 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4169 rxq_index, flow_id);
4173 rflow = &flow_table->flows[flow_id];
4175 if (old_rflow->filter == rflow->filter)
4176 old_rflow->filter = RPS_NO_FILTER;
4180 per_cpu(softnet_data, next_cpu).input_queue_head;
4183 rflow->cpu = next_cpu;
4188 * get_rps_cpu is called from netif_receive_skb and returns the target
4189 * CPU from the RPS map of the receiving queue for a given skb.
4190 * rcu_read_lock must be held on entry.
4192 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4193 struct rps_dev_flow **rflowp)
4195 const struct rps_sock_flow_table *sock_flow_table;
4196 struct netdev_rx_queue *rxqueue = dev->_rx;
4197 struct rps_dev_flow_table *flow_table;
4198 struct rps_map *map;
4203 if (skb_rx_queue_recorded(skb)) {
4204 u16 index = skb_get_rx_queue(skb);
4206 if (unlikely(index >= dev->real_num_rx_queues)) {
4207 WARN_ONCE(dev->real_num_rx_queues > 1,
4208 "%s received packet on queue %u, but number "
4209 "of RX queues is %u\n",
4210 dev->name, index, dev->real_num_rx_queues);
4216 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4218 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4219 map = rcu_dereference(rxqueue->rps_map);
4220 if (!flow_table && !map)
4223 skb_reset_network_header(skb);
4224 hash = skb_get_hash(skb);
4228 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4229 if (flow_table && sock_flow_table) {
4230 struct rps_dev_flow *rflow;
4234 /* First check into global flow table if there is a match */
4235 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4236 if ((ident ^ hash) & ~rps_cpu_mask)
4239 next_cpu = ident & rps_cpu_mask;
4241 /* OK, now we know there is a match,
4242 * we can look at the local (per receive queue) flow table
4244 rflow = &flow_table->flows[hash & flow_table->mask];
4248 * If the desired CPU (where last recvmsg was done) is
4249 * different from current CPU (one in the rx-queue flow
4250 * table entry), switch if one of the following holds:
4251 * - Current CPU is unset (>= nr_cpu_ids).
4252 * - Current CPU is offline.
4253 * - The current CPU's queue tail has advanced beyond the
4254 * last packet that was enqueued using this table entry.
4255 * This guarantees that all previous packets for the flow
4256 * have been dequeued, thus preserving in order delivery.
4258 if (unlikely(tcpu != next_cpu) &&
4259 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4260 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4261 rflow->last_qtail)) >= 0)) {
4263 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4266 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4276 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4277 if (cpu_online(tcpu)) {
4287 #ifdef CONFIG_RFS_ACCEL
4290 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4291 * @dev: Device on which the filter was set
4292 * @rxq_index: RX queue index
4293 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4294 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4296 * Drivers that implement ndo_rx_flow_steer() should periodically call
4297 * this function for each installed filter and remove the filters for
4298 * which it returns %true.
4300 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4301 u32 flow_id, u16 filter_id)
4303 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4304 struct rps_dev_flow_table *flow_table;
4305 struct rps_dev_flow *rflow;
4310 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4311 if (flow_table && flow_id <= flow_table->mask) {
4312 rflow = &flow_table->flows[flow_id];
4313 cpu = READ_ONCE(rflow->cpu);
4314 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4315 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4316 rflow->last_qtail) <
4317 (int)(10 * flow_table->mask)))
4323 EXPORT_SYMBOL(rps_may_expire_flow);
4325 #endif /* CONFIG_RFS_ACCEL */
4327 /* Called from hardirq (IPI) context */
4328 static void rps_trigger_softirq(void *data)
4330 struct softnet_data *sd = data;
4332 ____napi_schedule(sd, &sd->backlog);
4336 #endif /* CONFIG_RPS */
4339 * Check if this softnet_data structure is another cpu one
4340 * If yes, queue it to our IPI list and return 1
4343 static int rps_ipi_queued(struct softnet_data *sd)
4346 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4349 sd->rps_ipi_next = mysd->rps_ipi_list;
4350 mysd->rps_ipi_list = sd;
4352 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4355 #endif /* CONFIG_RPS */
4359 #ifdef CONFIG_NET_FLOW_LIMIT
4360 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4363 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4365 #ifdef CONFIG_NET_FLOW_LIMIT
4366 struct sd_flow_limit *fl;
4367 struct softnet_data *sd;
4368 unsigned int old_flow, new_flow;
4370 if (qlen < (netdev_max_backlog >> 1))
4373 sd = this_cpu_ptr(&softnet_data);
4376 fl = rcu_dereference(sd->flow_limit);
4378 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4379 old_flow = fl->history[fl->history_head];
4380 fl->history[fl->history_head] = new_flow;
4383 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4385 if (likely(fl->buckets[old_flow]))
4386 fl->buckets[old_flow]--;
4388 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4400 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4401 * queue (may be a remote CPU queue).
4403 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4404 unsigned int *qtail)
4406 struct softnet_data *sd;
4407 unsigned long flags;
4410 sd = &per_cpu(softnet_data, cpu);
4412 local_irq_save(flags);
4415 if (!netif_running(skb->dev))
4417 qlen = skb_queue_len(&sd->input_pkt_queue);
4418 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4421 __skb_queue_tail(&sd->input_pkt_queue, skb);
4422 input_queue_tail_incr_save(sd, qtail);
4424 local_irq_restore(flags);
4425 return NET_RX_SUCCESS;
4428 /* Schedule NAPI for backlog device
4429 * We can use non atomic operation since we own the queue lock
4431 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4432 if (!rps_ipi_queued(sd))
4433 ____napi_schedule(sd, &sd->backlog);
4442 local_irq_restore(flags);
4444 atomic_long_inc(&skb->dev->rx_dropped);
4449 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4451 struct net_device *dev = skb->dev;
4452 struct netdev_rx_queue *rxqueue;
4456 if (skb_rx_queue_recorded(skb)) {
4457 u16 index = skb_get_rx_queue(skb);
4459 if (unlikely(index >= dev->real_num_rx_queues)) {
4460 WARN_ONCE(dev->real_num_rx_queues > 1,
4461 "%s received packet on queue %u, but number "
4462 "of RX queues is %u\n",
4463 dev->name, index, dev->real_num_rx_queues);
4465 return rxqueue; /* Return first rxqueue */
4472 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4473 struct xdp_buff *xdp,
4474 struct bpf_prog *xdp_prog)
4476 struct netdev_rx_queue *rxqueue;
4477 void *orig_data, *orig_data_end;
4478 u32 metalen, act = XDP_DROP;
4479 __be16 orig_eth_type;
4485 /* Reinjected packets coming from act_mirred or similar should
4486 * not get XDP generic processing.
4488 if (skb_cloned(skb) || skb_is_tc_redirected(skb))
4491 /* XDP packets must be linear and must have sufficient headroom
4492 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4493 * native XDP provides, thus we need to do it here as well.
4495 if (skb_is_nonlinear(skb) ||
4496 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4497 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4498 int troom = skb->tail + skb->data_len - skb->end;
4500 /* In case we have to go down the path and also linearize,
4501 * then lets do the pskb_expand_head() work just once here.
4503 if (pskb_expand_head(skb,
4504 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4505 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4507 if (skb_linearize(skb))
4511 /* The XDP program wants to see the packet starting at the MAC
4514 mac_len = skb->data - skb_mac_header(skb);
4515 hlen = skb_headlen(skb) + mac_len;
4516 xdp->data = skb->data - mac_len;
4517 xdp->data_meta = xdp->data;
4518 xdp->data_end = xdp->data + hlen;
4519 xdp->data_hard_start = skb->data - skb_headroom(skb);
4520 orig_data_end = xdp->data_end;
4521 orig_data = xdp->data;
4522 eth = (struct ethhdr *)xdp->data;
4523 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4524 orig_eth_type = eth->h_proto;
4526 rxqueue = netif_get_rxqueue(skb);
4527 xdp->rxq = &rxqueue->xdp_rxq;
4529 act = bpf_prog_run_xdp(xdp_prog, xdp);
4531 /* check if bpf_xdp_adjust_head was used */
4532 off = xdp->data - orig_data;
4535 __skb_pull(skb, off);
4537 __skb_push(skb, -off);
4539 skb->mac_header += off;
4540 skb_reset_network_header(skb);
4543 /* check if bpf_xdp_adjust_tail was used. it can only "shrink"
4546 off = orig_data_end - xdp->data_end;
4548 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4553 /* check if XDP changed eth hdr such SKB needs update */
4554 eth = (struct ethhdr *)xdp->data;
4555 if ((orig_eth_type != eth->h_proto) ||
4556 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4557 __skb_push(skb, ETH_HLEN);
4558 skb->protocol = eth_type_trans(skb, skb->dev);
4564 __skb_push(skb, mac_len);
4567 metalen = xdp->data - xdp->data_meta;
4569 skb_metadata_set(skb, metalen);
4572 bpf_warn_invalid_xdp_action(act);
4575 trace_xdp_exception(skb->dev, xdp_prog, act);
4586 /* When doing generic XDP we have to bypass the qdisc layer and the
4587 * network taps in order to match in-driver-XDP behavior.
4589 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4591 struct net_device *dev = skb->dev;
4592 struct netdev_queue *txq;
4593 bool free_skb = true;
4596 txq = netdev_core_pick_tx(dev, skb, NULL);
4597 cpu = smp_processor_id();
4598 HARD_TX_LOCK(dev, txq, cpu);
4599 if (!netif_xmit_stopped(txq)) {
4600 rc = netdev_start_xmit(skb, dev, txq, 0);
4601 if (dev_xmit_complete(rc))
4604 HARD_TX_UNLOCK(dev, txq);
4606 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4610 EXPORT_SYMBOL_GPL(generic_xdp_tx);
4612 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4614 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4617 struct xdp_buff xdp;
4621 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4622 if (act != XDP_PASS) {
4625 err = xdp_do_generic_redirect(skb->dev, skb,
4631 generic_xdp_tx(skb, xdp_prog);
4642 EXPORT_SYMBOL_GPL(do_xdp_generic);
4644 static int netif_rx_internal(struct sk_buff *skb)
4648 net_timestamp_check(netdev_tstamp_prequeue, skb);
4650 trace_netif_rx(skb);
4653 if (static_branch_unlikely(&rps_needed)) {
4654 struct rps_dev_flow voidflow, *rflow = &voidflow;
4660 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4662 cpu = smp_processor_id();
4664 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4673 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4680 * netif_rx - post buffer to the network code
4681 * @skb: buffer to post
4683 * This function receives a packet from a device driver and queues it for
4684 * the upper (protocol) levels to process. It always succeeds. The buffer
4685 * may be dropped during processing for congestion control or by the
4689 * NET_RX_SUCCESS (no congestion)
4690 * NET_RX_DROP (packet was dropped)
4694 int netif_rx(struct sk_buff *skb)
4698 trace_netif_rx_entry(skb);
4700 ret = netif_rx_internal(skb);
4701 trace_netif_rx_exit(ret);
4705 EXPORT_SYMBOL(netif_rx);
4707 int netif_rx_ni(struct sk_buff *skb)
4711 trace_netif_rx_ni_entry(skb);
4714 err = netif_rx_internal(skb);
4715 if (local_softirq_pending())
4718 trace_netif_rx_ni_exit(err);
4722 EXPORT_SYMBOL(netif_rx_ni);
4724 static __latent_entropy void net_tx_action(struct softirq_action *h)
4726 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4728 if (sd->completion_queue) {
4729 struct sk_buff *clist;
4731 local_irq_disable();
4732 clist = sd->completion_queue;
4733 sd->completion_queue = NULL;
4737 struct sk_buff *skb = clist;
4739 clist = clist->next;
4741 WARN_ON(refcount_read(&skb->users));
4742 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4743 trace_consume_skb(skb);
4745 trace_kfree_skb(skb, net_tx_action);
4747 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4750 __kfree_skb_defer(skb);
4753 __kfree_skb_flush();
4756 if (sd->output_queue) {
4759 local_irq_disable();
4760 head = sd->output_queue;
4761 sd->output_queue = NULL;
4762 sd->output_queue_tailp = &sd->output_queue;
4766 struct Qdisc *q = head;
4767 spinlock_t *root_lock = NULL;
4769 head = head->next_sched;
4771 if (!(q->flags & TCQ_F_NOLOCK)) {
4772 root_lock = qdisc_lock(q);
4773 spin_lock(root_lock);
4775 /* We need to make sure head->next_sched is read
4776 * before clearing __QDISC_STATE_SCHED
4778 smp_mb__before_atomic();
4779 clear_bit(__QDISC_STATE_SCHED, &q->state);
4782 spin_unlock(root_lock);
4786 xfrm_dev_backlog(sd);
4789 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4790 /* This hook is defined here for ATM LANE */
4791 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4792 unsigned char *addr) __read_mostly;
4793 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4796 static inline struct sk_buff *
4797 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4798 struct net_device *orig_dev)
4800 #ifdef CONFIG_NET_CLS_ACT
4801 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4802 struct tcf_result cl_res;
4804 /* If there's at least one ingress present somewhere (so
4805 * we get here via enabled static key), remaining devices
4806 * that are not configured with an ingress qdisc will bail
4813 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4817 qdisc_skb_cb(skb)->pkt_len = skb->len;
4818 skb->tc_at_ingress = 1;
4819 mini_qdisc_bstats_cpu_update(miniq, skb);
4821 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
4823 case TC_ACT_RECLASSIFY:
4824 skb->tc_index = TC_H_MIN(cl_res.classid);
4827 mini_qdisc_qstats_cpu_drop(miniq);
4835 case TC_ACT_REDIRECT:
4836 /* skb_mac_header check was done by cls/act_bpf, so
4837 * we can safely push the L2 header back before
4838 * redirecting to another netdev
4840 __skb_push(skb, skb->mac_len);
4841 skb_do_redirect(skb);
4843 case TC_ACT_CONSUMED:
4848 #endif /* CONFIG_NET_CLS_ACT */
4853 * netdev_is_rx_handler_busy - check if receive handler is registered
4854 * @dev: device to check
4856 * Check if a receive handler is already registered for a given device.
4857 * Return true if there one.
4859 * The caller must hold the rtnl_mutex.
4861 bool netdev_is_rx_handler_busy(struct net_device *dev)
4864 return dev && rtnl_dereference(dev->rx_handler);
4866 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
4869 * netdev_rx_handler_register - register receive handler
4870 * @dev: device to register a handler for
4871 * @rx_handler: receive handler to register
4872 * @rx_handler_data: data pointer that is used by rx handler
4874 * Register a receive handler for a device. This handler will then be
4875 * called from __netif_receive_skb. A negative errno code is returned
4878 * The caller must hold the rtnl_mutex.
4880 * For a general description of rx_handler, see enum rx_handler_result.
4882 int netdev_rx_handler_register(struct net_device *dev,
4883 rx_handler_func_t *rx_handler,
4884 void *rx_handler_data)
4886 if (netdev_is_rx_handler_busy(dev))
4889 if (dev->priv_flags & IFF_NO_RX_HANDLER)
4892 /* Note: rx_handler_data must be set before rx_handler */
4893 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
4894 rcu_assign_pointer(dev->rx_handler, rx_handler);
4898 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
4901 * netdev_rx_handler_unregister - unregister receive handler
4902 * @dev: device to unregister a handler from
4904 * Unregister a receive handler from a device.
4906 * The caller must hold the rtnl_mutex.
4908 void netdev_rx_handler_unregister(struct net_device *dev)
4912 RCU_INIT_POINTER(dev->rx_handler, NULL);
4913 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
4914 * section has a guarantee to see a non NULL rx_handler_data
4918 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
4920 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
4923 * Limit the use of PFMEMALLOC reserves to those protocols that implement
4924 * the special handling of PFMEMALLOC skbs.
4926 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
4928 switch (skb->protocol) {
4929 case htons(ETH_P_ARP):
4930 case htons(ETH_P_IP):
4931 case htons(ETH_P_IPV6):
4932 case htons(ETH_P_8021Q):
4933 case htons(ETH_P_8021AD):
4940 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
4941 int *ret, struct net_device *orig_dev)
4943 if (nf_hook_ingress_active(skb)) {
4947 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4952 ingress_retval = nf_hook_ingress(skb);
4954 return ingress_retval;
4959 static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc,
4960 struct packet_type **ppt_prev)
4962 struct packet_type *ptype, *pt_prev;
4963 rx_handler_func_t *rx_handler;
4964 struct net_device *orig_dev;
4965 bool deliver_exact = false;
4966 int ret = NET_RX_DROP;
4969 net_timestamp_check(!netdev_tstamp_prequeue, skb);
4971 trace_netif_receive_skb(skb);
4973 orig_dev = skb->dev;
4975 skb_reset_network_header(skb);
4976 if (!skb_transport_header_was_set(skb))
4977 skb_reset_transport_header(skb);
4978 skb_reset_mac_len(skb);
4983 skb->skb_iif = skb->dev->ifindex;
4985 __this_cpu_inc(softnet_data.processed);
4987 if (static_branch_unlikely(&generic_xdp_needed_key)) {
4991 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
4994 if (ret2 != XDP_PASS)
4996 skb_reset_mac_len(skb);
4999 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5000 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5001 skb = skb_vlan_untag(skb);
5006 if (skb_skip_tc_classify(skb))
5012 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5014 ret = deliver_skb(skb, pt_prev, orig_dev);
5018 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5020 ret = deliver_skb(skb, pt_prev, orig_dev);
5025 #ifdef CONFIG_NET_INGRESS
5026 if (static_branch_unlikely(&ingress_needed_key)) {
5027 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
5031 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5037 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5040 if (skb_vlan_tag_present(skb)) {
5042 ret = deliver_skb(skb, pt_prev, orig_dev);
5045 if (vlan_do_receive(&skb))
5047 else if (unlikely(!skb))
5051 rx_handler = rcu_dereference(skb->dev->rx_handler);
5054 ret = deliver_skb(skb, pt_prev, orig_dev);
5057 switch (rx_handler(&skb)) {
5058 case RX_HANDLER_CONSUMED:
5059 ret = NET_RX_SUCCESS;
5061 case RX_HANDLER_ANOTHER:
5063 case RX_HANDLER_EXACT:
5064 deliver_exact = true;
5065 case RX_HANDLER_PASS:
5072 if (unlikely(skb_vlan_tag_present(skb))) {
5074 if (skb_vlan_tag_get_id(skb)) {
5075 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5078 skb->pkt_type = PACKET_OTHERHOST;
5079 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5080 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5081 /* Outer header is 802.1P with vlan 0, inner header is
5082 * 802.1Q or 802.1AD and vlan_do_receive() above could
5083 * not find vlan dev for vlan id 0.
5085 __vlan_hwaccel_clear_tag(skb);
5086 skb = skb_vlan_untag(skb);
5089 if (vlan_do_receive(&skb))
5090 /* After stripping off 802.1P header with vlan 0
5091 * vlan dev is found for inner header.
5094 else if (unlikely(!skb))
5097 /* We have stripped outer 802.1P vlan 0 header.
5098 * But could not find vlan dev.
5099 * check again for vlan id to set OTHERHOST.
5103 /* Note: we might in the future use prio bits
5104 * and set skb->priority like in vlan_do_receive()
5105 * For the time being, just ignore Priority Code Point
5107 __vlan_hwaccel_clear_tag(skb);
5110 type = skb->protocol;
5112 /* deliver only exact match when indicated */
5113 if (likely(!deliver_exact)) {
5114 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5115 &ptype_base[ntohs(type) &
5119 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5120 &orig_dev->ptype_specific);
5122 if (unlikely(skb->dev != orig_dev)) {
5123 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5124 &skb->dev->ptype_specific);
5128 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5130 *ppt_prev = pt_prev;
5134 atomic_long_inc(&skb->dev->rx_dropped);
5136 atomic_long_inc(&skb->dev->rx_nohandler);
5138 /* Jamal, now you will not able to escape explaining
5139 * me how you were going to use this. :-)
5148 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5150 struct net_device *orig_dev = skb->dev;
5151 struct packet_type *pt_prev = NULL;
5154 ret = __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
5156 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5157 skb->dev, pt_prev, orig_dev);
5162 * netif_receive_skb_core - special purpose version of netif_receive_skb
5163 * @skb: buffer to process
5165 * More direct receive version of netif_receive_skb(). It should
5166 * only be used by callers that have a need to skip RPS and Generic XDP.
5167 * Caller must also take care of handling if (page_is_)pfmemalloc.
5169 * This function may only be called from softirq context and interrupts
5170 * should be enabled.
5172 * Return values (usually ignored):
5173 * NET_RX_SUCCESS: no congestion
5174 * NET_RX_DROP: packet was dropped
5176 int netif_receive_skb_core(struct sk_buff *skb)
5181 ret = __netif_receive_skb_one_core(skb, false);
5186 EXPORT_SYMBOL(netif_receive_skb_core);
5188 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5189 struct packet_type *pt_prev,
5190 struct net_device *orig_dev)
5192 struct sk_buff *skb, *next;
5196 if (list_empty(head))
5198 if (pt_prev->list_func != NULL)
5199 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5200 ip_list_rcv, head, pt_prev, orig_dev);
5202 list_for_each_entry_safe(skb, next, head, list) {
5203 skb_list_del_init(skb);
5204 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5208 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5210 /* Fast-path assumptions:
5211 * - There is no RX handler.
5212 * - Only one packet_type matches.
5213 * If either of these fails, we will end up doing some per-packet
5214 * processing in-line, then handling the 'last ptype' for the whole
5215 * sublist. This can't cause out-of-order delivery to any single ptype,
5216 * because the 'last ptype' must be constant across the sublist, and all
5217 * other ptypes are handled per-packet.
5219 /* Current (common) ptype of sublist */
5220 struct packet_type *pt_curr = NULL;
5221 /* Current (common) orig_dev of sublist */
5222 struct net_device *od_curr = NULL;
5223 struct list_head sublist;
5224 struct sk_buff *skb, *next;
5226 INIT_LIST_HEAD(&sublist);
5227 list_for_each_entry_safe(skb, next, head, list) {
5228 struct net_device *orig_dev = skb->dev;
5229 struct packet_type *pt_prev = NULL;
5231 skb_list_del_init(skb);
5232 __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
5235 if (pt_curr != pt_prev || od_curr != orig_dev) {
5236 /* dispatch old sublist */
5237 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5238 /* start new sublist */
5239 INIT_LIST_HEAD(&sublist);
5243 list_add_tail(&skb->list, &sublist);
5246 /* dispatch final sublist */
5247 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5250 static int __netif_receive_skb(struct sk_buff *skb)
5254 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5255 unsigned int noreclaim_flag;
5258 * PFMEMALLOC skbs are special, they should
5259 * - be delivered to SOCK_MEMALLOC sockets only
5260 * - stay away from userspace
5261 * - have bounded memory usage
5263 * Use PF_MEMALLOC as this saves us from propagating the allocation
5264 * context down to all allocation sites.
5266 noreclaim_flag = memalloc_noreclaim_save();
5267 ret = __netif_receive_skb_one_core(skb, true);
5268 memalloc_noreclaim_restore(noreclaim_flag);
5270 ret = __netif_receive_skb_one_core(skb, false);
5275 static void __netif_receive_skb_list(struct list_head *head)
5277 unsigned long noreclaim_flag = 0;
5278 struct sk_buff *skb, *next;
5279 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5281 list_for_each_entry_safe(skb, next, head, list) {
5282 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5283 struct list_head sublist;
5285 /* Handle the previous sublist */
5286 list_cut_before(&sublist, head, &skb->list);
5287 if (!list_empty(&sublist))
5288 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5289 pfmemalloc = !pfmemalloc;
5290 /* See comments in __netif_receive_skb */
5292 noreclaim_flag = memalloc_noreclaim_save();
5294 memalloc_noreclaim_restore(noreclaim_flag);
5297 /* Handle the remaining sublist */
5298 if (!list_empty(head))
5299 __netif_receive_skb_list_core(head, pfmemalloc);
5300 /* Restore pflags */
5302 memalloc_noreclaim_restore(noreclaim_flag);
5305 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5307 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5308 struct bpf_prog *new = xdp->prog;
5311 switch (xdp->command) {
5312 case XDP_SETUP_PROG:
5313 rcu_assign_pointer(dev->xdp_prog, new);
5318 static_branch_dec(&generic_xdp_needed_key);
5319 } else if (new && !old) {
5320 static_branch_inc(&generic_xdp_needed_key);
5321 dev_disable_lro(dev);
5322 dev_disable_gro_hw(dev);
5326 case XDP_QUERY_PROG:
5327 xdp->prog_id = old ? old->aux->id : 0;
5338 static int netif_receive_skb_internal(struct sk_buff *skb)
5342 net_timestamp_check(netdev_tstamp_prequeue, skb);
5344 if (skb_defer_rx_timestamp(skb))
5345 return NET_RX_SUCCESS;
5349 if (static_branch_unlikely(&rps_needed)) {
5350 struct rps_dev_flow voidflow, *rflow = &voidflow;
5351 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5354 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5360 ret = __netif_receive_skb(skb);
5365 static void netif_receive_skb_list_internal(struct list_head *head)
5367 struct sk_buff *skb, *next;
5368 struct list_head sublist;
5370 INIT_LIST_HEAD(&sublist);
5371 list_for_each_entry_safe(skb, next, head, list) {
5372 net_timestamp_check(netdev_tstamp_prequeue, skb);
5373 skb_list_del_init(skb);
5374 if (!skb_defer_rx_timestamp(skb))
5375 list_add_tail(&skb->list, &sublist);
5377 list_splice_init(&sublist, head);
5381 if (static_branch_unlikely(&rps_needed)) {
5382 list_for_each_entry_safe(skb, next, head, list) {
5383 struct rps_dev_flow voidflow, *rflow = &voidflow;
5384 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5387 /* Will be handled, remove from list */
5388 skb_list_del_init(skb);
5389 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5394 __netif_receive_skb_list(head);
5399 * netif_receive_skb - process receive buffer from network
5400 * @skb: buffer to process
5402 * netif_receive_skb() is the main receive data processing function.
5403 * It always succeeds. The buffer may be dropped during processing
5404 * for congestion control or by the protocol layers.
5406 * This function may only be called from softirq context and interrupts
5407 * should be enabled.
5409 * Return values (usually ignored):
5410 * NET_RX_SUCCESS: no congestion
5411 * NET_RX_DROP: packet was dropped
5413 int netif_receive_skb(struct sk_buff *skb)
5417 trace_netif_receive_skb_entry(skb);
5419 ret = netif_receive_skb_internal(skb);
5420 trace_netif_receive_skb_exit(ret);
5424 EXPORT_SYMBOL(netif_receive_skb);
5427 * netif_receive_skb_list - process many receive buffers from network
5428 * @head: list of skbs to process.
5430 * Since return value of netif_receive_skb() is normally ignored, and
5431 * wouldn't be meaningful for a list, this function returns void.
5433 * This function may only be called from softirq context and interrupts
5434 * should be enabled.
5436 void netif_receive_skb_list(struct list_head *head)
5438 struct sk_buff *skb;
5440 if (list_empty(head))
5442 if (trace_netif_receive_skb_list_entry_enabled()) {
5443 list_for_each_entry(skb, head, list)
5444 trace_netif_receive_skb_list_entry(skb);
5446 netif_receive_skb_list_internal(head);
5447 trace_netif_receive_skb_list_exit(0);
5449 EXPORT_SYMBOL(netif_receive_skb_list);
5451 DEFINE_PER_CPU(struct work_struct, flush_works);
5453 /* Network device is going away, flush any packets still pending */
5454 static void flush_backlog(struct work_struct *work)
5456 struct sk_buff *skb, *tmp;
5457 struct softnet_data *sd;
5460 sd = this_cpu_ptr(&softnet_data);
5462 local_irq_disable();
5464 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5465 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5466 __skb_unlink(skb, &sd->input_pkt_queue);
5468 input_queue_head_incr(sd);
5474 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5475 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5476 __skb_unlink(skb, &sd->process_queue);
5478 input_queue_head_incr(sd);
5484 static void flush_all_backlogs(void)
5490 for_each_online_cpu(cpu)
5491 queue_work_on(cpu, system_highpri_wq,
5492 per_cpu_ptr(&flush_works, cpu));
5494 for_each_online_cpu(cpu)
5495 flush_work(per_cpu_ptr(&flush_works, cpu));
5500 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
5501 static void gro_normal_list(struct napi_struct *napi)
5503 if (!napi->rx_count)
5505 netif_receive_skb_list_internal(&napi->rx_list);
5506 INIT_LIST_HEAD(&napi->rx_list);
5510 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5511 * pass the whole batch up to the stack.
5513 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb)
5515 list_add_tail(&skb->list, &napi->rx_list);
5516 if (++napi->rx_count >= gro_normal_batch)
5517 gro_normal_list(napi);
5520 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5521 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5522 static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
5524 struct packet_offload *ptype;
5525 __be16 type = skb->protocol;
5526 struct list_head *head = &offload_base;
5529 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5531 if (NAPI_GRO_CB(skb)->count == 1) {
5532 skb_shinfo(skb)->gso_size = 0;
5537 list_for_each_entry_rcu(ptype, head, list) {
5538 if (ptype->type != type || !ptype->callbacks.gro_complete)
5541 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5542 ipv6_gro_complete, inet_gro_complete,
5549 WARN_ON(&ptype->list == head);
5551 return NET_RX_SUCCESS;
5555 gro_normal_one(napi, skb);
5556 return NET_RX_SUCCESS;
5559 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5562 struct list_head *head = &napi->gro_hash[index].list;
5563 struct sk_buff *skb, *p;
5565 list_for_each_entry_safe_reverse(skb, p, head, list) {
5566 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5568 skb_list_del_init(skb);
5569 napi_gro_complete(napi, skb);
5570 napi->gro_hash[index].count--;
5573 if (!napi->gro_hash[index].count)
5574 __clear_bit(index, &napi->gro_bitmask);
5577 /* napi->gro_hash[].list contains packets ordered by age.
5578 * youngest packets at the head of it.
5579 * Complete skbs in reverse order to reduce latencies.
5581 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5583 unsigned long bitmask = napi->gro_bitmask;
5584 unsigned int i, base = ~0U;
5586 while ((i = ffs(bitmask)) != 0) {
5589 __napi_gro_flush_chain(napi, base, flush_old);
5592 EXPORT_SYMBOL(napi_gro_flush);
5594 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5595 struct sk_buff *skb)
5597 unsigned int maclen = skb->dev->hard_header_len;
5598 u32 hash = skb_get_hash_raw(skb);
5599 struct list_head *head;
5602 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5603 list_for_each_entry(p, head, list) {
5604 unsigned long diffs;
5606 NAPI_GRO_CB(p)->flush = 0;
5608 if (hash != skb_get_hash_raw(p)) {
5609 NAPI_GRO_CB(p)->same_flow = 0;
5613 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5614 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5615 if (skb_vlan_tag_present(p))
5616 diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
5617 diffs |= skb_metadata_dst_cmp(p, skb);
5618 diffs |= skb_metadata_differs(p, skb);
5619 if (maclen == ETH_HLEN)
5620 diffs |= compare_ether_header(skb_mac_header(p),
5621 skb_mac_header(skb));
5623 diffs = memcmp(skb_mac_header(p),
5624 skb_mac_header(skb),
5626 NAPI_GRO_CB(p)->same_flow = !diffs;
5632 static void skb_gro_reset_offset(struct sk_buff *skb)
5634 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5635 const skb_frag_t *frag0 = &pinfo->frags[0];
5637 NAPI_GRO_CB(skb)->data_offset = 0;
5638 NAPI_GRO_CB(skb)->frag0 = NULL;
5639 NAPI_GRO_CB(skb)->frag0_len = 0;
5641 if (!skb_headlen(skb) && pinfo->nr_frags &&
5642 !PageHighMem(skb_frag_page(frag0))) {
5643 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5644 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5645 skb_frag_size(frag0),
5646 skb->end - skb->tail);
5650 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5652 struct skb_shared_info *pinfo = skb_shinfo(skb);
5654 BUG_ON(skb->end - skb->tail < grow);
5656 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5658 skb->data_len -= grow;
5661 skb_frag_off_add(&pinfo->frags[0], grow);
5662 skb_frag_size_sub(&pinfo->frags[0], grow);
5664 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5665 skb_frag_unref(skb, 0);
5666 memmove(pinfo->frags, pinfo->frags + 1,
5667 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5671 static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
5673 struct sk_buff *oldest;
5675 oldest = list_last_entry(head, struct sk_buff, list);
5677 /* We are called with head length >= MAX_GRO_SKBS, so this is
5680 if (WARN_ON_ONCE(!oldest))
5683 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5686 skb_list_del_init(oldest);
5687 napi_gro_complete(napi, oldest);
5690 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5692 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5694 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5696 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5697 struct list_head *head = &offload_base;
5698 struct packet_offload *ptype;
5699 __be16 type = skb->protocol;
5700 struct list_head *gro_head;
5701 struct sk_buff *pp = NULL;
5702 enum gro_result ret;
5706 if (netif_elide_gro(skb->dev))
5709 gro_head = gro_list_prepare(napi, skb);
5712 list_for_each_entry_rcu(ptype, head, list) {
5713 if (ptype->type != type || !ptype->callbacks.gro_receive)
5716 skb_set_network_header(skb, skb_gro_offset(skb));
5717 skb_reset_mac_len(skb);
5718 NAPI_GRO_CB(skb)->same_flow = 0;
5719 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5720 NAPI_GRO_CB(skb)->free = 0;
5721 NAPI_GRO_CB(skb)->encap_mark = 0;
5722 NAPI_GRO_CB(skb)->recursion_counter = 0;
5723 NAPI_GRO_CB(skb)->is_fou = 0;
5724 NAPI_GRO_CB(skb)->is_atomic = 1;
5725 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5727 /* Setup for GRO checksum validation */
5728 switch (skb->ip_summed) {
5729 case CHECKSUM_COMPLETE:
5730 NAPI_GRO_CB(skb)->csum = skb->csum;
5731 NAPI_GRO_CB(skb)->csum_valid = 1;
5732 NAPI_GRO_CB(skb)->csum_cnt = 0;
5734 case CHECKSUM_UNNECESSARY:
5735 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
5736 NAPI_GRO_CB(skb)->csum_valid = 0;
5739 NAPI_GRO_CB(skb)->csum_cnt = 0;
5740 NAPI_GRO_CB(skb)->csum_valid = 0;
5743 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
5744 ipv6_gro_receive, inet_gro_receive,
5750 if (&ptype->list == head)
5753 if (IS_ERR(pp) && PTR_ERR(pp) == -EINPROGRESS) {
5758 same_flow = NAPI_GRO_CB(skb)->same_flow;
5759 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
5762 skb_list_del_init(pp);
5763 napi_gro_complete(napi, pp);
5764 napi->gro_hash[hash].count--;
5770 if (NAPI_GRO_CB(skb)->flush)
5773 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
5774 gro_flush_oldest(napi, gro_head);
5776 napi->gro_hash[hash].count++;
5778 NAPI_GRO_CB(skb)->count = 1;
5779 NAPI_GRO_CB(skb)->age = jiffies;
5780 NAPI_GRO_CB(skb)->last = skb;
5781 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
5782 list_add(&skb->list, gro_head);
5786 grow = skb_gro_offset(skb) - skb_headlen(skb);
5788 gro_pull_from_frag0(skb, grow);
5790 if (napi->gro_hash[hash].count) {
5791 if (!test_bit(hash, &napi->gro_bitmask))
5792 __set_bit(hash, &napi->gro_bitmask);
5793 } else if (test_bit(hash, &napi->gro_bitmask)) {
5794 __clear_bit(hash, &napi->gro_bitmask);
5804 struct packet_offload *gro_find_receive_by_type(__be16 type)
5806 struct list_head *offload_head = &offload_base;
5807 struct packet_offload *ptype;
5809 list_for_each_entry_rcu(ptype, offload_head, list) {
5810 if (ptype->type != type || !ptype->callbacks.gro_receive)
5816 EXPORT_SYMBOL(gro_find_receive_by_type);
5818 struct packet_offload *gro_find_complete_by_type(__be16 type)
5820 struct list_head *offload_head = &offload_base;
5821 struct packet_offload *ptype;
5823 list_for_each_entry_rcu(ptype, offload_head, list) {
5824 if (ptype->type != type || !ptype->callbacks.gro_complete)
5830 EXPORT_SYMBOL(gro_find_complete_by_type);
5832 static void napi_skb_free_stolen_head(struct sk_buff *skb)
5836 kmem_cache_free(skbuff_head_cache, skb);
5839 static gro_result_t napi_skb_finish(struct napi_struct *napi,
5840 struct sk_buff *skb,
5845 gro_normal_one(napi, skb);
5852 case GRO_MERGED_FREE:
5853 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5854 napi_skb_free_stolen_head(skb);
5868 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5872 skb_mark_napi_id(skb, napi);
5873 trace_napi_gro_receive_entry(skb);
5875 skb_gro_reset_offset(skb);
5877 ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
5878 trace_napi_gro_receive_exit(ret);
5882 EXPORT_SYMBOL(napi_gro_receive);
5884 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
5886 if (unlikely(skb->pfmemalloc)) {
5890 __skb_pull(skb, skb_headlen(skb));
5891 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
5892 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
5893 __vlan_hwaccel_clear_tag(skb);
5894 skb->dev = napi->dev;
5897 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
5898 skb->pkt_type = PACKET_HOST;
5900 skb->encapsulation = 0;
5901 skb_shinfo(skb)->gso_type = 0;
5902 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
5908 struct sk_buff *napi_get_frags(struct napi_struct *napi)
5910 struct sk_buff *skb = napi->skb;
5913 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
5916 skb_mark_napi_id(skb, napi);
5921 EXPORT_SYMBOL(napi_get_frags);
5923 static gro_result_t napi_frags_finish(struct napi_struct *napi,
5924 struct sk_buff *skb,
5930 __skb_push(skb, ETH_HLEN);
5931 skb->protocol = eth_type_trans(skb, skb->dev);
5932 if (ret == GRO_NORMAL)
5933 gro_normal_one(napi, skb);
5937 napi_reuse_skb(napi, skb);
5940 case GRO_MERGED_FREE:
5941 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5942 napi_skb_free_stolen_head(skb);
5944 napi_reuse_skb(napi, skb);
5955 /* Upper GRO stack assumes network header starts at gro_offset=0
5956 * Drivers could call both napi_gro_frags() and napi_gro_receive()
5957 * We copy ethernet header into skb->data to have a common layout.
5959 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
5961 struct sk_buff *skb = napi->skb;
5962 const struct ethhdr *eth;
5963 unsigned int hlen = sizeof(*eth);
5967 skb_reset_mac_header(skb);
5968 skb_gro_reset_offset(skb);
5970 if (unlikely(skb_gro_header_hard(skb, hlen))) {
5971 eth = skb_gro_header_slow(skb, hlen, 0);
5972 if (unlikely(!eth)) {
5973 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
5974 __func__, napi->dev->name);
5975 napi_reuse_skb(napi, skb);
5979 eth = (const struct ethhdr *)skb->data;
5980 gro_pull_from_frag0(skb, hlen);
5981 NAPI_GRO_CB(skb)->frag0 += hlen;
5982 NAPI_GRO_CB(skb)->frag0_len -= hlen;
5984 __skb_pull(skb, hlen);
5987 * This works because the only protocols we care about don't require
5989 * We'll fix it up properly in napi_frags_finish()
5991 skb->protocol = eth->h_proto;
5996 gro_result_t napi_gro_frags(struct napi_struct *napi)
5999 struct sk_buff *skb = napi_frags_skb(napi);
6004 trace_napi_gro_frags_entry(skb);
6006 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6007 trace_napi_gro_frags_exit(ret);
6011 EXPORT_SYMBOL(napi_gro_frags);
6013 /* Compute the checksum from gro_offset and return the folded value
6014 * after adding in any pseudo checksum.
6016 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6021 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6023 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6024 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6025 /* See comments in __skb_checksum_complete(). */
6027 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6028 !skb->csum_complete_sw)
6029 netdev_rx_csum_fault(skb->dev, skb);
6032 NAPI_GRO_CB(skb)->csum = wsum;
6033 NAPI_GRO_CB(skb)->csum_valid = 1;
6037 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6039 static void net_rps_send_ipi(struct softnet_data *remsd)
6043 struct softnet_data *next = remsd->rps_ipi_next;
6045 if (cpu_online(remsd->cpu))
6046 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6053 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6054 * Note: called with local irq disabled, but exits with local irq enabled.
6056 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6059 struct softnet_data *remsd = sd->rps_ipi_list;
6062 sd->rps_ipi_list = NULL;
6066 /* Send pending IPI's to kick RPS processing on remote cpus. */
6067 net_rps_send_ipi(remsd);
6073 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6076 return sd->rps_ipi_list != NULL;
6082 static int process_backlog(struct napi_struct *napi, int quota)
6084 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6088 /* Check if we have pending ipi, its better to send them now,
6089 * not waiting net_rx_action() end.
6091 if (sd_has_rps_ipi_waiting(sd)) {
6092 local_irq_disable();
6093 net_rps_action_and_irq_enable(sd);
6096 napi->weight = dev_rx_weight;
6098 struct sk_buff *skb;
6100 while ((skb = __skb_dequeue(&sd->process_queue))) {
6102 __netif_receive_skb(skb);
6104 input_queue_head_incr(sd);
6105 if (++work >= quota)
6110 local_irq_disable();
6112 if (skb_queue_empty(&sd->input_pkt_queue)) {
6114 * Inline a custom version of __napi_complete().
6115 * only current cpu owns and manipulates this napi,
6116 * and NAPI_STATE_SCHED is the only possible flag set
6118 * We can use a plain write instead of clear_bit(),
6119 * and we dont need an smp_mb() memory barrier.
6124 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6125 &sd->process_queue);
6135 * __napi_schedule - schedule for receive
6136 * @n: entry to schedule
6138 * The entry's receive function will be scheduled to run.
6139 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6141 void __napi_schedule(struct napi_struct *n)
6143 unsigned long flags;
6145 local_irq_save(flags);
6146 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6147 local_irq_restore(flags);
6149 EXPORT_SYMBOL(__napi_schedule);
6152 * napi_schedule_prep - check if napi can be scheduled
6155 * Test if NAPI routine is already running, and if not mark
6156 * it as running. This is used as a condition variable
6157 * insure only one NAPI poll instance runs. We also make
6158 * sure there is no pending NAPI disable.
6160 bool napi_schedule_prep(struct napi_struct *n)
6162 unsigned long val, new;
6165 val = READ_ONCE(n->state);
6166 if (unlikely(val & NAPIF_STATE_DISABLE))
6168 new = val | NAPIF_STATE_SCHED;
6170 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6171 * This was suggested by Alexander Duyck, as compiler
6172 * emits better code than :
6173 * if (val & NAPIF_STATE_SCHED)
6174 * new |= NAPIF_STATE_MISSED;
6176 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6178 } while (cmpxchg(&n->state, val, new) != val);
6180 return !(val & NAPIF_STATE_SCHED);
6182 EXPORT_SYMBOL(napi_schedule_prep);
6185 * __napi_schedule_irqoff - schedule for receive
6186 * @n: entry to schedule
6188 * Variant of __napi_schedule() assuming hard irqs are masked
6190 void __napi_schedule_irqoff(struct napi_struct *n)
6192 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6194 EXPORT_SYMBOL(__napi_schedule_irqoff);
6196 bool napi_complete_done(struct napi_struct *n, int work_done)
6198 unsigned long flags, val, new;
6201 * 1) Don't let napi dequeue from the cpu poll list
6202 * just in case its running on a different cpu.
6203 * 2) If we are busy polling, do nothing here, we have
6204 * the guarantee we will be called later.
6206 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6207 NAPIF_STATE_IN_BUSY_POLL)))
6210 if (n->gro_bitmask) {
6211 unsigned long timeout = 0;
6214 timeout = n->dev->gro_flush_timeout;
6216 /* When the NAPI instance uses a timeout and keeps postponing
6217 * it, we need to bound somehow the time packets are kept in
6220 napi_gro_flush(n, !!timeout);
6222 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6223 HRTIMER_MODE_REL_PINNED);
6228 if (unlikely(!list_empty(&n->poll_list))) {
6229 /* If n->poll_list is not empty, we need to mask irqs */
6230 local_irq_save(flags);
6231 list_del_init(&n->poll_list);
6232 local_irq_restore(flags);
6236 val = READ_ONCE(n->state);
6238 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6240 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6242 /* If STATE_MISSED was set, leave STATE_SCHED set,
6243 * because we will call napi->poll() one more time.
6244 * This C code was suggested by Alexander Duyck to help gcc.
6246 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6248 } while (cmpxchg(&n->state, val, new) != val);
6250 if (unlikely(val & NAPIF_STATE_MISSED)) {
6257 EXPORT_SYMBOL(napi_complete_done);
6259 /* must be called under rcu_read_lock(), as we dont take a reference */
6260 static struct napi_struct *napi_by_id(unsigned int napi_id)
6262 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6263 struct napi_struct *napi;
6265 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6266 if (napi->napi_id == napi_id)
6272 #if defined(CONFIG_NET_RX_BUSY_POLL)
6274 #define BUSY_POLL_BUDGET 8
6276 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6280 /* Busy polling means there is a high chance device driver hard irq
6281 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6282 * set in napi_schedule_prep().
6283 * Since we are about to call napi->poll() once more, we can safely
6284 * clear NAPI_STATE_MISSED.
6286 * Note: x86 could use a single "lock and ..." instruction
6287 * to perform these two clear_bit()
6289 clear_bit(NAPI_STATE_MISSED, &napi->state);
6290 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6294 /* All we really want here is to re-enable device interrupts.
6295 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6297 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6298 /* We can't gro_normal_list() here, because napi->poll() might have
6299 * rearmed the napi (napi_complete_done()) in which case it could
6300 * already be running on another CPU.
6302 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6303 netpoll_poll_unlock(have_poll_lock);
6304 if (rc == BUSY_POLL_BUDGET) {
6305 /* As the whole budget was spent, we still own the napi so can
6306 * safely handle the rx_list.
6308 gro_normal_list(napi);
6309 __napi_schedule(napi);
6314 void napi_busy_loop(unsigned int napi_id,
6315 bool (*loop_end)(void *, unsigned long),
6318 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6319 int (*napi_poll)(struct napi_struct *napi, int budget);
6320 void *have_poll_lock = NULL;
6321 struct napi_struct *napi;
6328 napi = napi_by_id(napi_id);
6338 unsigned long val = READ_ONCE(napi->state);
6340 /* If multiple threads are competing for this napi,
6341 * we avoid dirtying napi->state as much as we can.
6343 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6344 NAPIF_STATE_IN_BUSY_POLL))
6346 if (cmpxchg(&napi->state, val,
6347 val | NAPIF_STATE_IN_BUSY_POLL |
6348 NAPIF_STATE_SCHED) != val)
6350 have_poll_lock = netpoll_poll_lock(napi);
6351 napi_poll = napi->poll;
6353 work = napi_poll(napi, BUSY_POLL_BUDGET);
6354 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6355 gro_normal_list(napi);
6358 __NET_ADD_STATS(dev_net(napi->dev),
6359 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6362 if (!loop_end || loop_end(loop_end_arg, start_time))
6365 if (unlikely(need_resched())) {
6367 busy_poll_stop(napi, have_poll_lock);
6371 if (loop_end(loop_end_arg, start_time))
6378 busy_poll_stop(napi, have_poll_lock);
6383 EXPORT_SYMBOL(napi_busy_loop);
6385 #endif /* CONFIG_NET_RX_BUSY_POLL */
6387 static void napi_hash_add(struct napi_struct *napi)
6389 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
6390 test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
6393 spin_lock(&napi_hash_lock);
6395 /* 0..NR_CPUS range is reserved for sender_cpu use */
6397 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6398 napi_gen_id = MIN_NAPI_ID;
6399 } while (napi_by_id(napi_gen_id));
6400 napi->napi_id = napi_gen_id;
6402 hlist_add_head_rcu(&napi->napi_hash_node,
6403 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6405 spin_unlock(&napi_hash_lock);
6408 /* Warning : caller is responsible to make sure rcu grace period
6409 * is respected before freeing memory containing @napi
6411 bool napi_hash_del(struct napi_struct *napi)
6413 bool rcu_sync_needed = false;
6415 spin_lock(&napi_hash_lock);
6417 if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
6418 rcu_sync_needed = true;
6419 hlist_del_rcu(&napi->napi_hash_node);
6421 spin_unlock(&napi_hash_lock);
6422 return rcu_sync_needed;
6424 EXPORT_SYMBOL_GPL(napi_hash_del);
6426 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6428 struct napi_struct *napi;
6430 napi = container_of(timer, struct napi_struct, timer);
6432 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6433 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6435 if (napi->gro_bitmask && !napi_disable_pending(napi) &&
6436 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6437 __napi_schedule_irqoff(napi);
6439 return HRTIMER_NORESTART;
6442 static void init_gro_hash(struct napi_struct *napi)
6446 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6447 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6448 napi->gro_hash[i].count = 0;
6450 napi->gro_bitmask = 0;
6453 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6454 int (*poll)(struct napi_struct *, int), int weight)
6456 INIT_LIST_HEAD(&napi->poll_list);
6457 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6458 napi->timer.function = napi_watchdog;
6459 init_gro_hash(napi);
6461 INIT_LIST_HEAD(&napi->rx_list);
6464 if (weight > NAPI_POLL_WEIGHT)
6465 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6467 napi->weight = weight;
6468 list_add(&napi->dev_list, &dev->napi_list);
6470 #ifdef CONFIG_NETPOLL
6471 napi->poll_owner = -1;
6473 set_bit(NAPI_STATE_SCHED, &napi->state);
6474 napi_hash_add(napi);
6476 EXPORT_SYMBOL(netif_napi_add);
6478 void napi_disable(struct napi_struct *n)
6481 set_bit(NAPI_STATE_DISABLE, &n->state);
6483 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6485 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6488 hrtimer_cancel(&n->timer);
6490 clear_bit(NAPI_STATE_DISABLE, &n->state);
6492 EXPORT_SYMBOL(napi_disable);
6494 static void flush_gro_hash(struct napi_struct *napi)
6498 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6499 struct sk_buff *skb, *n;
6501 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6503 napi->gro_hash[i].count = 0;
6507 /* Must be called in process context */
6508 void netif_napi_del(struct napi_struct *napi)
6511 if (napi_hash_del(napi))
6513 list_del_init(&napi->dev_list);
6514 napi_free_frags(napi);
6516 flush_gro_hash(napi);
6517 napi->gro_bitmask = 0;
6519 EXPORT_SYMBOL(netif_napi_del);
6521 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6526 list_del_init(&n->poll_list);
6528 have = netpoll_poll_lock(n);
6532 /* This NAPI_STATE_SCHED test is for avoiding a race
6533 * with netpoll's poll_napi(). Only the entity which
6534 * obtains the lock and sees NAPI_STATE_SCHED set will
6535 * actually make the ->poll() call. Therefore we avoid
6536 * accidentally calling ->poll() when NAPI is not scheduled.
6539 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6540 work = n->poll(n, weight);
6541 trace_napi_poll(n, work, weight);
6544 WARN_ON_ONCE(work > weight);
6546 if (likely(work < weight))
6549 /* Drivers must not modify the NAPI state if they
6550 * consume the entire weight. In such cases this code
6551 * still "owns" the NAPI instance and therefore can
6552 * move the instance around on the list at-will.
6554 if (unlikely(napi_disable_pending(n))) {
6559 if (n->gro_bitmask) {
6560 /* flush too old packets
6561 * If HZ < 1000, flush all packets.
6563 napi_gro_flush(n, HZ >= 1000);
6568 /* Some drivers may have called napi_schedule
6569 * prior to exhausting their budget.
6571 if (unlikely(!list_empty(&n->poll_list))) {
6572 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6573 n->dev ? n->dev->name : "backlog");
6577 list_add_tail(&n->poll_list, repoll);
6580 netpoll_poll_unlock(have);
6585 static __latent_entropy void net_rx_action(struct softirq_action *h)
6587 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6588 unsigned long time_limit = jiffies +
6589 usecs_to_jiffies(netdev_budget_usecs);
6590 int budget = netdev_budget;
6594 local_irq_disable();
6595 list_splice_init(&sd->poll_list, &list);
6599 struct napi_struct *n;
6601 if (list_empty(&list)) {
6602 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6607 n = list_first_entry(&list, struct napi_struct, poll_list);
6608 budget -= napi_poll(n, &repoll);
6610 /* If softirq window is exhausted then punt.
6611 * Allow this to run for 2 jiffies since which will allow
6612 * an average latency of 1.5/HZ.
6614 if (unlikely(budget <= 0 ||
6615 time_after_eq(jiffies, time_limit))) {
6621 local_irq_disable();
6623 list_splice_tail_init(&sd->poll_list, &list);
6624 list_splice_tail(&repoll, &list);
6625 list_splice(&list, &sd->poll_list);
6626 if (!list_empty(&sd->poll_list))
6627 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6629 net_rps_action_and_irq_enable(sd);
6631 __kfree_skb_flush();
6634 struct netdev_adjacent {
6635 struct net_device *dev;
6637 /* upper master flag, there can only be one master device per list */
6640 /* lookup ignore flag */
6643 /* counter for the number of times this device was added to us */
6646 /* private field for the users */
6649 struct list_head list;
6650 struct rcu_head rcu;
6653 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6654 struct list_head *adj_list)
6656 struct netdev_adjacent *adj;
6658 list_for_each_entry(adj, adj_list, list) {
6659 if (adj->dev == adj_dev)
6665 static int ____netdev_has_upper_dev(struct net_device *upper_dev, void *data)
6667 struct net_device *dev = data;
6669 return upper_dev == dev;
6673 * netdev_has_upper_dev - Check if device is linked to an upper device
6675 * @upper_dev: upper device to check
6677 * Find out if a device is linked to specified upper device and return true
6678 * in case it is. Note that this checks only immediate upper device,
6679 * not through a complete stack of devices. The caller must hold the RTNL lock.
6681 bool netdev_has_upper_dev(struct net_device *dev,
6682 struct net_device *upper_dev)
6686 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6689 EXPORT_SYMBOL(netdev_has_upper_dev);
6692 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6694 * @upper_dev: upper device to check
6696 * Find out if a device is linked to specified upper device and return true
6697 * in case it is. Note that this checks the entire upper device chain.
6698 * The caller must hold rcu lock.
6701 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6702 struct net_device *upper_dev)
6704 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6707 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6710 * netdev_has_any_upper_dev - Check if device is linked to some device
6713 * Find out if a device is linked to an upper device and return true in case
6714 * it is. The caller must hold the RTNL lock.
6716 bool netdev_has_any_upper_dev(struct net_device *dev)
6720 return !list_empty(&dev->adj_list.upper);
6722 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6725 * netdev_master_upper_dev_get - Get master upper device
6728 * Find a master upper device and return pointer to it or NULL in case
6729 * it's not there. The caller must hold the RTNL lock.
6731 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6733 struct netdev_adjacent *upper;
6737 if (list_empty(&dev->adj_list.upper))
6740 upper = list_first_entry(&dev->adj_list.upper,
6741 struct netdev_adjacent, list);
6742 if (likely(upper->master))
6746 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6748 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6750 struct netdev_adjacent *upper;
6754 if (list_empty(&dev->adj_list.upper))
6757 upper = list_first_entry(&dev->adj_list.upper,
6758 struct netdev_adjacent, list);
6759 if (likely(upper->master) && !upper->ignore)
6765 * netdev_has_any_lower_dev - Check if device is linked to some device
6768 * Find out if a device is linked to a lower device and return true in case
6769 * it is. The caller must hold the RTNL lock.
6771 static bool netdev_has_any_lower_dev(struct net_device *dev)
6775 return !list_empty(&dev->adj_list.lower);
6778 void *netdev_adjacent_get_private(struct list_head *adj_list)
6780 struct netdev_adjacent *adj;
6782 adj = list_entry(adj_list, struct netdev_adjacent, list);
6784 return adj->private;
6786 EXPORT_SYMBOL(netdev_adjacent_get_private);
6789 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6791 * @iter: list_head ** of the current position
6793 * Gets the next device from the dev's upper list, starting from iter
6794 * position. The caller must hold RCU read lock.
6796 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6797 struct list_head **iter)
6799 struct netdev_adjacent *upper;
6801 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6803 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6805 if (&upper->list == &dev->adj_list.upper)
6808 *iter = &upper->list;
6812 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6814 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6815 struct list_head **iter,
6818 struct netdev_adjacent *upper;
6820 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6822 if (&upper->list == &dev->adj_list.upper)
6825 *iter = &upper->list;
6826 *ignore = upper->ignore;
6831 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6832 struct list_head **iter)
6834 struct netdev_adjacent *upper;
6836 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6838 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6840 if (&upper->list == &dev->adj_list.upper)
6843 *iter = &upper->list;
6848 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6849 int (*fn)(struct net_device *dev,
6853 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6854 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6859 iter = &dev->adj_list.upper;
6863 ret = fn(now, data);
6870 udev = __netdev_next_upper_dev(now, &iter, &ignore);
6877 niter = &udev->adj_list.upper;
6878 dev_stack[cur] = now;
6879 iter_stack[cur++] = iter;
6886 next = dev_stack[--cur];
6887 niter = iter_stack[cur];
6897 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6898 int (*fn)(struct net_device *dev,
6902 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6903 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6907 iter = &dev->adj_list.upper;
6911 ret = fn(now, data);
6918 udev = netdev_next_upper_dev_rcu(now, &iter);
6923 niter = &udev->adj_list.upper;
6924 dev_stack[cur] = now;
6925 iter_stack[cur++] = iter;
6932 next = dev_stack[--cur];
6933 niter = iter_stack[cur];
6942 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6944 static bool __netdev_has_upper_dev(struct net_device *dev,
6945 struct net_device *upper_dev)
6949 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
6954 * netdev_lower_get_next_private - Get the next ->private from the
6955 * lower neighbour list
6957 * @iter: list_head ** of the current position
6959 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6960 * list, starting from iter position. The caller must hold either hold the
6961 * RTNL lock or its own locking that guarantees that the neighbour lower
6962 * list will remain unchanged.
6964 void *netdev_lower_get_next_private(struct net_device *dev,
6965 struct list_head **iter)
6967 struct netdev_adjacent *lower;
6969 lower = list_entry(*iter, struct netdev_adjacent, list);
6971 if (&lower->list == &dev->adj_list.lower)
6974 *iter = lower->list.next;
6976 return lower->private;
6978 EXPORT_SYMBOL(netdev_lower_get_next_private);
6981 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6982 * lower neighbour list, RCU
6985 * @iter: list_head ** of the current position
6987 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6988 * list, starting from iter position. The caller must hold RCU read lock.
6990 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6991 struct list_head **iter)
6993 struct netdev_adjacent *lower;
6995 WARN_ON_ONCE(!rcu_read_lock_held());
6997 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6999 if (&lower->list == &dev->adj_list.lower)
7002 *iter = &lower->list;
7004 return lower->private;
7006 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7009 * netdev_lower_get_next - Get the next device from the lower neighbour
7012 * @iter: list_head ** of the current position
7014 * Gets the next netdev_adjacent from the dev's lower neighbour
7015 * list, starting from iter position. The caller must hold RTNL lock or
7016 * its own locking that guarantees that the neighbour lower
7017 * list will remain unchanged.
7019 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7021 struct netdev_adjacent *lower;
7023 lower = list_entry(*iter, struct netdev_adjacent, list);
7025 if (&lower->list == &dev->adj_list.lower)
7028 *iter = lower->list.next;
7032 EXPORT_SYMBOL(netdev_lower_get_next);
7034 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7035 struct list_head **iter)
7037 struct netdev_adjacent *lower;
7039 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7041 if (&lower->list == &dev->adj_list.lower)
7044 *iter = &lower->list;
7049 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7050 struct list_head **iter,
7053 struct netdev_adjacent *lower;
7055 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7057 if (&lower->list == &dev->adj_list.lower)
7060 *iter = &lower->list;
7061 *ignore = lower->ignore;
7066 int netdev_walk_all_lower_dev(struct net_device *dev,
7067 int (*fn)(struct net_device *dev,
7071 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7072 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7076 iter = &dev->adj_list.lower;
7080 ret = fn(now, data);
7087 ldev = netdev_next_lower_dev(now, &iter);
7092 niter = &ldev->adj_list.lower;
7093 dev_stack[cur] = now;
7094 iter_stack[cur++] = iter;
7101 next = dev_stack[--cur];
7102 niter = iter_stack[cur];
7111 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7113 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7114 int (*fn)(struct net_device *dev,
7118 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7119 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7124 iter = &dev->adj_list.lower;
7128 ret = fn(now, data);
7135 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7142 niter = &ldev->adj_list.lower;
7143 dev_stack[cur] = now;
7144 iter_stack[cur++] = iter;
7151 next = dev_stack[--cur];
7152 niter = iter_stack[cur];
7162 static struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7163 struct list_head **iter)
7165 struct netdev_adjacent *lower;
7167 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7168 if (&lower->list == &dev->adj_list.lower)
7171 *iter = &lower->list;
7176 static u8 __netdev_upper_depth(struct net_device *dev)
7178 struct net_device *udev;
7179 struct list_head *iter;
7183 for (iter = &dev->adj_list.upper,
7184 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7186 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7189 if (max_depth < udev->upper_level)
7190 max_depth = udev->upper_level;
7196 static u8 __netdev_lower_depth(struct net_device *dev)
7198 struct net_device *ldev;
7199 struct list_head *iter;
7203 for (iter = &dev->adj_list.lower,
7204 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7206 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7209 if (max_depth < ldev->lower_level)
7210 max_depth = ldev->lower_level;
7216 static int __netdev_update_upper_level(struct net_device *dev, void *data)
7218 dev->upper_level = __netdev_upper_depth(dev) + 1;
7222 static int __netdev_update_lower_level(struct net_device *dev, void *data)
7224 dev->lower_level = __netdev_lower_depth(dev) + 1;
7228 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7229 int (*fn)(struct net_device *dev,
7233 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7234 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7238 iter = &dev->adj_list.lower;
7242 ret = fn(now, data);
7249 ldev = netdev_next_lower_dev_rcu(now, &iter);
7254 niter = &ldev->adj_list.lower;
7255 dev_stack[cur] = now;
7256 iter_stack[cur++] = iter;
7263 next = dev_stack[--cur];
7264 niter = iter_stack[cur];
7273 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7276 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7277 * lower neighbour list, RCU
7281 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7282 * list. The caller must hold RCU read lock.
7284 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7286 struct netdev_adjacent *lower;
7288 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7289 struct netdev_adjacent, list);
7291 return lower->private;
7294 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7297 * netdev_master_upper_dev_get_rcu - Get master upper device
7300 * Find a master upper device and return pointer to it or NULL in case
7301 * it's not there. The caller must hold the RCU read lock.
7303 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7305 struct netdev_adjacent *upper;
7307 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7308 struct netdev_adjacent, list);
7309 if (upper && likely(upper->master))
7313 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7315 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7316 struct net_device *adj_dev,
7317 struct list_head *dev_list)
7319 char linkname[IFNAMSIZ+7];
7321 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7322 "upper_%s" : "lower_%s", adj_dev->name);
7323 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7326 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7328 struct list_head *dev_list)
7330 char linkname[IFNAMSIZ+7];
7332 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7333 "upper_%s" : "lower_%s", name);
7334 sysfs_remove_link(&(dev->dev.kobj), linkname);
7337 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7338 struct net_device *adj_dev,
7339 struct list_head *dev_list)
7341 return (dev_list == &dev->adj_list.upper ||
7342 dev_list == &dev->adj_list.lower) &&
7343 net_eq(dev_net(dev), dev_net(adj_dev));
7346 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7347 struct net_device *adj_dev,
7348 struct list_head *dev_list,
7349 void *private, bool master)
7351 struct netdev_adjacent *adj;
7354 adj = __netdev_find_adj(adj_dev, dev_list);
7358 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7359 dev->name, adj_dev->name, adj->ref_nr);
7364 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7369 adj->master = master;
7371 adj->private = private;
7372 adj->ignore = false;
7375 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7376 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7378 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7379 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7384 /* Ensure that master link is always the first item in list. */
7386 ret = sysfs_create_link(&(dev->dev.kobj),
7387 &(adj_dev->dev.kobj), "master");
7389 goto remove_symlinks;
7391 list_add_rcu(&adj->list, dev_list);
7393 list_add_tail_rcu(&adj->list, dev_list);
7399 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7400 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7408 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7409 struct net_device *adj_dev,
7411 struct list_head *dev_list)
7413 struct netdev_adjacent *adj;
7415 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7416 dev->name, adj_dev->name, ref_nr);
7418 adj = __netdev_find_adj(adj_dev, dev_list);
7421 pr_err("Adjacency does not exist for device %s from %s\n",
7422 dev->name, adj_dev->name);
7427 if (adj->ref_nr > ref_nr) {
7428 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7429 dev->name, adj_dev->name, ref_nr,
7430 adj->ref_nr - ref_nr);
7431 adj->ref_nr -= ref_nr;
7436 sysfs_remove_link(&(dev->dev.kobj), "master");
7438 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7439 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7441 list_del_rcu(&adj->list);
7442 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7443 adj_dev->name, dev->name, adj_dev->name);
7445 kfree_rcu(adj, rcu);
7448 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7449 struct net_device *upper_dev,
7450 struct list_head *up_list,
7451 struct list_head *down_list,
7452 void *private, bool master)
7456 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7461 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7464 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7471 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7472 struct net_device *upper_dev,
7474 struct list_head *up_list,
7475 struct list_head *down_list)
7477 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7478 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7481 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7482 struct net_device *upper_dev,
7483 void *private, bool master)
7485 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7486 &dev->adj_list.upper,
7487 &upper_dev->adj_list.lower,
7491 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7492 struct net_device *upper_dev)
7494 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7495 &dev->adj_list.upper,
7496 &upper_dev->adj_list.lower);
7499 static int __netdev_upper_dev_link(struct net_device *dev,
7500 struct net_device *upper_dev, bool master,
7501 void *upper_priv, void *upper_info,
7502 struct netlink_ext_ack *extack)
7504 struct netdev_notifier_changeupper_info changeupper_info = {
7509 .upper_dev = upper_dev,
7512 .upper_info = upper_info,
7514 struct net_device *master_dev;
7519 if (dev == upper_dev)
7522 /* To prevent loops, check if dev is not upper device to upper_dev. */
7523 if (__netdev_has_upper_dev(upper_dev, dev))
7526 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7530 if (__netdev_has_upper_dev(dev, upper_dev))
7533 master_dev = __netdev_master_upper_dev_get(dev);
7535 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7538 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7539 &changeupper_info.info);
7540 ret = notifier_to_errno(ret);
7544 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7549 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7550 &changeupper_info.info);
7551 ret = notifier_to_errno(ret);
7555 __netdev_update_upper_level(dev, NULL);
7556 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7558 __netdev_update_lower_level(upper_dev, NULL);
7559 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7565 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7571 * netdev_upper_dev_link - Add a link to the upper device
7573 * @upper_dev: new upper device
7574 * @extack: netlink extended ack
7576 * Adds a link to device which is upper to this one. The caller must hold
7577 * the RTNL lock. On a failure a negative errno code is returned.
7578 * On success the reference counts are adjusted and the function
7581 int netdev_upper_dev_link(struct net_device *dev,
7582 struct net_device *upper_dev,
7583 struct netlink_ext_ack *extack)
7585 return __netdev_upper_dev_link(dev, upper_dev, false,
7586 NULL, NULL, extack);
7588 EXPORT_SYMBOL(netdev_upper_dev_link);
7591 * netdev_master_upper_dev_link - Add a master link to the upper device
7593 * @upper_dev: new upper device
7594 * @upper_priv: upper device private
7595 * @upper_info: upper info to be passed down via notifier
7596 * @extack: netlink extended ack
7598 * Adds a link to device which is upper to this one. In this case, only
7599 * one master upper device can be linked, although other non-master devices
7600 * might be linked as well. The caller must hold the RTNL lock.
7601 * On a failure a negative errno code is returned. On success the reference
7602 * counts are adjusted and the function returns zero.
7604 int netdev_master_upper_dev_link(struct net_device *dev,
7605 struct net_device *upper_dev,
7606 void *upper_priv, void *upper_info,
7607 struct netlink_ext_ack *extack)
7609 return __netdev_upper_dev_link(dev, upper_dev, true,
7610 upper_priv, upper_info, extack);
7612 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7615 * netdev_upper_dev_unlink - Removes a link to upper device
7617 * @upper_dev: new upper device
7619 * Removes a link to device which is upper to this one. The caller must hold
7622 void netdev_upper_dev_unlink(struct net_device *dev,
7623 struct net_device *upper_dev)
7625 struct netdev_notifier_changeupper_info changeupper_info = {
7629 .upper_dev = upper_dev,
7635 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7637 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7638 &changeupper_info.info);
7640 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7642 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7643 &changeupper_info.info);
7645 __netdev_update_upper_level(dev, NULL);
7646 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7648 __netdev_update_lower_level(upper_dev, NULL);
7649 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7652 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7654 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7655 struct net_device *lower_dev,
7658 struct netdev_adjacent *adj;
7660 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7664 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7669 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7670 struct net_device *lower_dev)
7672 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7675 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7676 struct net_device *lower_dev)
7678 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7681 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7682 struct net_device *new_dev,
7683 struct net_device *dev,
7684 struct netlink_ext_ack *extack)
7691 if (old_dev && new_dev != old_dev)
7692 netdev_adjacent_dev_disable(dev, old_dev);
7694 err = netdev_upper_dev_link(new_dev, dev, extack);
7696 if (old_dev && new_dev != old_dev)
7697 netdev_adjacent_dev_enable(dev, old_dev);
7703 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7705 void netdev_adjacent_change_commit(struct net_device *old_dev,
7706 struct net_device *new_dev,
7707 struct net_device *dev)
7709 if (!new_dev || !old_dev)
7712 if (new_dev == old_dev)
7715 netdev_adjacent_dev_enable(dev, old_dev);
7716 netdev_upper_dev_unlink(old_dev, dev);
7718 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7720 void netdev_adjacent_change_abort(struct net_device *old_dev,
7721 struct net_device *new_dev,
7722 struct net_device *dev)
7727 if (old_dev && new_dev != old_dev)
7728 netdev_adjacent_dev_enable(dev, old_dev);
7730 netdev_upper_dev_unlink(new_dev, dev);
7732 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7735 * netdev_bonding_info_change - Dispatch event about slave change
7737 * @bonding_info: info to dispatch
7739 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7740 * The caller must hold the RTNL lock.
7742 void netdev_bonding_info_change(struct net_device *dev,
7743 struct netdev_bonding_info *bonding_info)
7745 struct netdev_notifier_bonding_info info = {
7749 memcpy(&info.bonding_info, bonding_info,
7750 sizeof(struct netdev_bonding_info));
7751 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7754 EXPORT_SYMBOL(netdev_bonding_info_change);
7756 static void netdev_adjacent_add_links(struct net_device *dev)
7758 struct netdev_adjacent *iter;
7760 struct net *net = dev_net(dev);
7762 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7763 if (!net_eq(net, dev_net(iter->dev)))
7765 netdev_adjacent_sysfs_add(iter->dev, dev,
7766 &iter->dev->adj_list.lower);
7767 netdev_adjacent_sysfs_add(dev, iter->dev,
7768 &dev->adj_list.upper);
7771 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7772 if (!net_eq(net, dev_net(iter->dev)))
7774 netdev_adjacent_sysfs_add(iter->dev, dev,
7775 &iter->dev->adj_list.upper);
7776 netdev_adjacent_sysfs_add(dev, iter->dev,
7777 &dev->adj_list.lower);
7781 static void netdev_adjacent_del_links(struct net_device *dev)
7783 struct netdev_adjacent *iter;
7785 struct net *net = dev_net(dev);
7787 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7788 if (!net_eq(net, dev_net(iter->dev)))
7790 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7791 &iter->dev->adj_list.lower);
7792 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7793 &dev->adj_list.upper);
7796 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7797 if (!net_eq(net, dev_net(iter->dev)))
7799 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7800 &iter->dev->adj_list.upper);
7801 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7802 &dev->adj_list.lower);
7806 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
7808 struct netdev_adjacent *iter;
7810 struct net *net = dev_net(dev);
7812 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7813 if (!net_eq(net, dev_net(iter->dev)))
7815 netdev_adjacent_sysfs_del(iter->dev, oldname,
7816 &iter->dev->adj_list.lower);
7817 netdev_adjacent_sysfs_add(iter->dev, dev,
7818 &iter->dev->adj_list.lower);
7821 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7822 if (!net_eq(net, dev_net(iter->dev)))
7824 netdev_adjacent_sysfs_del(iter->dev, oldname,
7825 &iter->dev->adj_list.upper);
7826 netdev_adjacent_sysfs_add(iter->dev, dev,
7827 &iter->dev->adj_list.upper);
7831 void *netdev_lower_dev_get_private(struct net_device *dev,
7832 struct net_device *lower_dev)
7834 struct netdev_adjacent *lower;
7838 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
7842 return lower->private;
7844 EXPORT_SYMBOL(netdev_lower_dev_get_private);
7848 * netdev_lower_change - Dispatch event about lower device state change
7849 * @lower_dev: device
7850 * @lower_state_info: state to dispatch
7852 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
7853 * The caller must hold the RTNL lock.
7855 void netdev_lower_state_changed(struct net_device *lower_dev,
7856 void *lower_state_info)
7858 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
7859 .info.dev = lower_dev,
7863 changelowerstate_info.lower_state_info = lower_state_info;
7864 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
7865 &changelowerstate_info.info);
7867 EXPORT_SYMBOL(netdev_lower_state_changed);
7869 static void dev_change_rx_flags(struct net_device *dev, int flags)
7871 const struct net_device_ops *ops = dev->netdev_ops;
7873 if (ops->ndo_change_rx_flags)
7874 ops->ndo_change_rx_flags(dev, flags);
7877 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
7879 unsigned int old_flags = dev->flags;
7885 dev->flags |= IFF_PROMISC;
7886 dev->promiscuity += inc;
7887 if (dev->promiscuity == 0) {
7890 * If inc causes overflow, untouch promisc and return error.
7893 dev->flags &= ~IFF_PROMISC;
7895 dev->promiscuity -= inc;
7896 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
7901 if (dev->flags != old_flags) {
7902 pr_info("device %s %s promiscuous mode\n",
7904 dev->flags & IFF_PROMISC ? "entered" : "left");
7905 if (audit_enabled) {
7906 current_uid_gid(&uid, &gid);
7907 audit_log(audit_context(), GFP_ATOMIC,
7908 AUDIT_ANOM_PROMISCUOUS,
7909 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
7910 dev->name, (dev->flags & IFF_PROMISC),
7911 (old_flags & IFF_PROMISC),
7912 from_kuid(&init_user_ns, audit_get_loginuid(current)),
7913 from_kuid(&init_user_ns, uid),
7914 from_kgid(&init_user_ns, gid),
7915 audit_get_sessionid(current));
7918 dev_change_rx_flags(dev, IFF_PROMISC);
7921 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
7926 * dev_set_promiscuity - update promiscuity count on a device
7930 * Add or remove promiscuity from a device. While the count in the device
7931 * remains above zero the interface remains promiscuous. Once it hits zero
7932 * the device reverts back to normal filtering operation. A negative inc
7933 * value is used to drop promiscuity on the device.
7934 * Return 0 if successful or a negative errno code on error.
7936 int dev_set_promiscuity(struct net_device *dev, int inc)
7938 unsigned int old_flags = dev->flags;
7941 err = __dev_set_promiscuity(dev, inc, true);
7944 if (dev->flags != old_flags)
7945 dev_set_rx_mode(dev);
7948 EXPORT_SYMBOL(dev_set_promiscuity);
7950 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
7952 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
7956 dev->flags |= IFF_ALLMULTI;
7957 dev->allmulti += inc;
7958 if (dev->allmulti == 0) {
7961 * If inc causes overflow, untouch allmulti and return error.
7964 dev->flags &= ~IFF_ALLMULTI;
7966 dev->allmulti -= inc;
7967 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
7972 if (dev->flags ^ old_flags) {
7973 dev_change_rx_flags(dev, IFF_ALLMULTI);
7974 dev_set_rx_mode(dev);
7976 __dev_notify_flags(dev, old_flags,
7977 dev->gflags ^ old_gflags);
7983 * dev_set_allmulti - update allmulti count on a device
7987 * Add or remove reception of all multicast frames to a device. While the
7988 * count in the device remains above zero the interface remains listening
7989 * to all interfaces. Once it hits zero the device reverts back to normal
7990 * filtering operation. A negative @inc value is used to drop the counter
7991 * when releasing a resource needing all multicasts.
7992 * Return 0 if successful or a negative errno code on error.
7995 int dev_set_allmulti(struct net_device *dev, int inc)
7997 return __dev_set_allmulti(dev, inc, true);
7999 EXPORT_SYMBOL(dev_set_allmulti);
8002 * Upload unicast and multicast address lists to device and
8003 * configure RX filtering. When the device doesn't support unicast
8004 * filtering it is put in promiscuous mode while unicast addresses
8007 void __dev_set_rx_mode(struct net_device *dev)
8009 const struct net_device_ops *ops = dev->netdev_ops;
8011 /* dev_open will call this function so the list will stay sane. */
8012 if (!(dev->flags&IFF_UP))
8015 if (!netif_device_present(dev))
8018 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8019 /* Unicast addresses changes may only happen under the rtnl,
8020 * therefore calling __dev_set_promiscuity here is safe.
8022 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8023 __dev_set_promiscuity(dev, 1, false);
8024 dev->uc_promisc = true;
8025 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8026 __dev_set_promiscuity(dev, -1, false);
8027 dev->uc_promisc = false;
8031 if (ops->ndo_set_rx_mode)
8032 ops->ndo_set_rx_mode(dev);
8035 void dev_set_rx_mode(struct net_device *dev)
8037 netif_addr_lock_bh(dev);
8038 __dev_set_rx_mode(dev);
8039 netif_addr_unlock_bh(dev);
8043 * dev_get_flags - get flags reported to userspace
8046 * Get the combination of flag bits exported through APIs to userspace.
8048 unsigned int dev_get_flags(const struct net_device *dev)
8052 flags = (dev->flags & ~(IFF_PROMISC |
8057 (dev->gflags & (IFF_PROMISC |
8060 if (netif_running(dev)) {
8061 if (netif_oper_up(dev))
8062 flags |= IFF_RUNNING;
8063 if (netif_carrier_ok(dev))
8064 flags |= IFF_LOWER_UP;
8065 if (netif_dormant(dev))
8066 flags |= IFF_DORMANT;
8071 EXPORT_SYMBOL(dev_get_flags);
8073 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8074 struct netlink_ext_ack *extack)
8076 unsigned int old_flags = dev->flags;
8082 * Set the flags on our device.
8085 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8086 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8088 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8092 * Load in the correct multicast list now the flags have changed.
8095 if ((old_flags ^ flags) & IFF_MULTICAST)
8096 dev_change_rx_flags(dev, IFF_MULTICAST);
8098 dev_set_rx_mode(dev);
8101 * Have we downed the interface. We handle IFF_UP ourselves
8102 * according to user attempts to set it, rather than blindly
8107 if ((old_flags ^ flags) & IFF_UP) {
8108 if (old_flags & IFF_UP)
8111 ret = __dev_open(dev, extack);
8114 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8115 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8116 unsigned int old_flags = dev->flags;
8118 dev->gflags ^= IFF_PROMISC;
8120 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8121 if (dev->flags != old_flags)
8122 dev_set_rx_mode(dev);
8125 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8126 * is important. Some (broken) drivers set IFF_PROMISC, when
8127 * IFF_ALLMULTI is requested not asking us and not reporting.
8129 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8130 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8132 dev->gflags ^= IFF_ALLMULTI;
8133 __dev_set_allmulti(dev, inc, false);
8139 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8140 unsigned int gchanges)
8142 unsigned int changes = dev->flags ^ old_flags;
8145 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8147 if (changes & IFF_UP) {
8148 if (dev->flags & IFF_UP)
8149 call_netdevice_notifiers(NETDEV_UP, dev);
8151 call_netdevice_notifiers(NETDEV_DOWN, dev);
8154 if (dev->flags & IFF_UP &&
8155 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8156 struct netdev_notifier_change_info change_info = {
8160 .flags_changed = changes,
8163 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8168 * dev_change_flags - change device settings
8170 * @flags: device state flags
8171 * @extack: netlink extended ack
8173 * Change settings on device based state flags. The flags are
8174 * in the userspace exported format.
8176 int dev_change_flags(struct net_device *dev, unsigned int flags,
8177 struct netlink_ext_ack *extack)
8180 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8182 ret = __dev_change_flags(dev, flags, extack);
8186 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8187 __dev_notify_flags(dev, old_flags, changes);
8190 EXPORT_SYMBOL(dev_change_flags);
8192 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8194 const struct net_device_ops *ops = dev->netdev_ops;
8196 if (ops->ndo_change_mtu)
8197 return ops->ndo_change_mtu(dev, new_mtu);
8199 /* Pairs with all the lockless reads of dev->mtu in the stack */
8200 WRITE_ONCE(dev->mtu, new_mtu);
8203 EXPORT_SYMBOL(__dev_set_mtu);
8205 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8206 struct netlink_ext_ack *extack)
8208 /* MTU must be positive, and in range */
8209 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8210 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8214 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8215 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8222 * dev_set_mtu_ext - Change maximum transfer unit
8224 * @new_mtu: new transfer unit
8225 * @extack: netlink extended ack
8227 * Change the maximum transfer size of the network device.
8229 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8230 struct netlink_ext_ack *extack)
8234 if (new_mtu == dev->mtu)
8237 err = dev_validate_mtu(dev, new_mtu, extack);
8241 if (!netif_device_present(dev))
8244 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8245 err = notifier_to_errno(err);
8249 orig_mtu = dev->mtu;
8250 err = __dev_set_mtu(dev, new_mtu);
8253 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8255 err = notifier_to_errno(err);
8257 /* setting mtu back and notifying everyone again,
8258 * so that they have a chance to revert changes.
8260 __dev_set_mtu(dev, orig_mtu);
8261 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8268 int dev_set_mtu(struct net_device *dev, int new_mtu)
8270 struct netlink_ext_ack extack;
8273 memset(&extack, 0, sizeof(extack));
8274 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8275 if (err && extack._msg)
8276 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8279 EXPORT_SYMBOL(dev_set_mtu);
8282 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8284 * @new_len: new tx queue length
8286 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8288 unsigned int orig_len = dev->tx_queue_len;
8291 if (new_len != (unsigned int)new_len)
8294 if (new_len != orig_len) {
8295 dev->tx_queue_len = new_len;
8296 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8297 res = notifier_to_errno(res);
8300 res = dev_qdisc_change_tx_queue_len(dev);
8308 netdev_err(dev, "refused to change device tx_queue_len\n");
8309 dev->tx_queue_len = orig_len;
8314 * dev_set_group - Change group this device belongs to
8316 * @new_group: group this device should belong to
8318 void dev_set_group(struct net_device *dev, int new_group)
8320 dev->group = new_group;
8322 EXPORT_SYMBOL(dev_set_group);
8325 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8327 * @addr: new address
8328 * @extack: netlink extended ack
8330 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8331 struct netlink_ext_ack *extack)
8333 struct netdev_notifier_pre_changeaddr_info info = {
8335 .info.extack = extack,
8340 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8341 return notifier_to_errno(rc);
8343 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8346 * dev_set_mac_address - Change Media Access Control Address
8349 * @extack: netlink extended ack
8351 * Change the hardware (MAC) address of the device
8353 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8354 struct netlink_ext_ack *extack)
8356 const struct net_device_ops *ops = dev->netdev_ops;
8359 if (!ops->ndo_set_mac_address)
8361 if (sa->sa_family != dev->type)
8363 if (!netif_device_present(dev))
8365 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8368 err = ops->ndo_set_mac_address(dev, sa);
8371 dev->addr_assign_type = NET_ADDR_SET;
8372 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8373 add_device_randomness(dev->dev_addr, dev->addr_len);
8376 EXPORT_SYMBOL(dev_set_mac_address);
8379 * dev_change_carrier - Change device carrier
8381 * @new_carrier: new value
8383 * Change device carrier
8385 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8387 const struct net_device_ops *ops = dev->netdev_ops;
8389 if (!ops->ndo_change_carrier)
8391 if (!netif_device_present(dev))
8393 return ops->ndo_change_carrier(dev, new_carrier);
8395 EXPORT_SYMBOL(dev_change_carrier);
8398 * dev_get_phys_port_id - Get device physical port ID
8402 * Get device physical port ID
8404 int dev_get_phys_port_id(struct net_device *dev,
8405 struct netdev_phys_item_id *ppid)
8407 const struct net_device_ops *ops = dev->netdev_ops;
8409 if (!ops->ndo_get_phys_port_id)
8411 return ops->ndo_get_phys_port_id(dev, ppid);
8413 EXPORT_SYMBOL(dev_get_phys_port_id);
8416 * dev_get_phys_port_name - Get device physical port name
8419 * @len: limit of bytes to copy to name
8421 * Get device physical port name
8423 int dev_get_phys_port_name(struct net_device *dev,
8424 char *name, size_t len)
8426 const struct net_device_ops *ops = dev->netdev_ops;
8429 if (ops->ndo_get_phys_port_name) {
8430 err = ops->ndo_get_phys_port_name(dev, name, len);
8431 if (err != -EOPNOTSUPP)
8434 return devlink_compat_phys_port_name_get(dev, name, len);
8436 EXPORT_SYMBOL(dev_get_phys_port_name);
8439 * dev_get_port_parent_id - Get the device's port parent identifier
8440 * @dev: network device
8441 * @ppid: pointer to a storage for the port's parent identifier
8442 * @recurse: allow/disallow recursion to lower devices
8444 * Get the devices's port parent identifier
8446 int dev_get_port_parent_id(struct net_device *dev,
8447 struct netdev_phys_item_id *ppid,
8450 const struct net_device_ops *ops = dev->netdev_ops;
8451 struct netdev_phys_item_id first = { };
8452 struct net_device *lower_dev;
8453 struct list_head *iter;
8456 if (ops->ndo_get_port_parent_id) {
8457 err = ops->ndo_get_port_parent_id(dev, ppid);
8458 if (err != -EOPNOTSUPP)
8462 err = devlink_compat_switch_id_get(dev, ppid);
8463 if (!err || err != -EOPNOTSUPP)
8469 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8470 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8475 else if (memcmp(&first, ppid, sizeof(*ppid)))
8481 EXPORT_SYMBOL(dev_get_port_parent_id);
8484 * netdev_port_same_parent_id - Indicate if two network devices have
8485 * the same port parent identifier
8486 * @a: first network device
8487 * @b: second network device
8489 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8491 struct netdev_phys_item_id a_id = { };
8492 struct netdev_phys_item_id b_id = { };
8494 if (dev_get_port_parent_id(a, &a_id, true) ||
8495 dev_get_port_parent_id(b, &b_id, true))
8498 return netdev_phys_item_id_same(&a_id, &b_id);
8500 EXPORT_SYMBOL(netdev_port_same_parent_id);
8503 * dev_change_proto_down - update protocol port state information
8505 * @proto_down: new value
8507 * This info can be used by switch drivers to set the phys state of the
8510 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8512 const struct net_device_ops *ops = dev->netdev_ops;
8514 if (!ops->ndo_change_proto_down)
8516 if (!netif_device_present(dev))
8518 return ops->ndo_change_proto_down(dev, proto_down);
8520 EXPORT_SYMBOL(dev_change_proto_down);
8523 * dev_change_proto_down_generic - generic implementation for
8524 * ndo_change_proto_down that sets carrier according to
8528 * @proto_down: new value
8530 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8533 netif_carrier_off(dev);
8535 netif_carrier_on(dev);
8536 dev->proto_down = proto_down;
8539 EXPORT_SYMBOL(dev_change_proto_down_generic);
8541 u32 __dev_xdp_query(struct net_device *dev, bpf_op_t bpf_op,
8542 enum bpf_netdev_command cmd)
8544 struct netdev_bpf xdp;
8549 memset(&xdp, 0, sizeof(xdp));
8552 /* Query must always succeed. */
8553 WARN_ON(bpf_op(dev, &xdp) < 0 && cmd == XDP_QUERY_PROG);
8558 static int dev_xdp_install(struct net_device *dev, bpf_op_t bpf_op,
8559 struct netlink_ext_ack *extack, u32 flags,
8560 struct bpf_prog *prog)
8562 bool non_hw = !(flags & XDP_FLAGS_HW_MODE);
8563 struct bpf_prog *prev_prog = NULL;
8564 struct netdev_bpf xdp;
8568 prev_prog = bpf_prog_by_id(__dev_xdp_query(dev, bpf_op,
8570 if (IS_ERR(prev_prog))
8574 memset(&xdp, 0, sizeof(xdp));
8575 if (flags & XDP_FLAGS_HW_MODE)
8576 xdp.command = XDP_SETUP_PROG_HW;
8578 xdp.command = XDP_SETUP_PROG;
8579 xdp.extack = extack;
8583 err = bpf_op(dev, &xdp);
8585 bpf_prog_change_xdp(prev_prog, prog);
8588 bpf_prog_put(prev_prog);
8593 static void dev_xdp_uninstall(struct net_device *dev)
8595 struct netdev_bpf xdp;
8598 /* Remove generic XDP */
8599 WARN_ON(dev_xdp_install(dev, generic_xdp_install, NULL, 0, NULL));
8601 /* Remove from the driver */
8602 ndo_bpf = dev->netdev_ops->ndo_bpf;
8606 memset(&xdp, 0, sizeof(xdp));
8607 xdp.command = XDP_QUERY_PROG;
8608 WARN_ON(ndo_bpf(dev, &xdp));
8610 WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
8613 /* Remove HW offload */
8614 memset(&xdp, 0, sizeof(xdp));
8615 xdp.command = XDP_QUERY_PROG_HW;
8616 if (!ndo_bpf(dev, &xdp) && xdp.prog_id)
8617 WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
8622 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
8624 * @extack: netlink extended ack
8625 * @fd: new program fd or negative value to clear
8626 * @flags: xdp-related flags
8628 * Set or clear a bpf program for a device
8630 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
8633 const struct net_device_ops *ops = dev->netdev_ops;
8634 enum bpf_netdev_command query;
8635 struct bpf_prog *prog = NULL;
8636 bpf_op_t bpf_op, bpf_chk;
8642 offload = flags & XDP_FLAGS_HW_MODE;
8643 query = offload ? XDP_QUERY_PROG_HW : XDP_QUERY_PROG;
8645 bpf_op = bpf_chk = ops->ndo_bpf;
8646 if (!bpf_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE))) {
8647 NL_SET_ERR_MSG(extack, "underlying driver does not support XDP in native mode");
8650 if (!bpf_op || (flags & XDP_FLAGS_SKB_MODE))
8651 bpf_op = generic_xdp_install;
8652 if (bpf_op == bpf_chk)
8653 bpf_chk = generic_xdp_install;
8658 if (!offload && __dev_xdp_query(dev, bpf_chk, XDP_QUERY_PROG)) {
8659 NL_SET_ERR_MSG(extack, "native and generic XDP can't be active at the same time");
8663 prog_id = __dev_xdp_query(dev, bpf_op, query);
8664 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && prog_id) {
8665 NL_SET_ERR_MSG(extack, "XDP program already attached");
8669 prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
8670 bpf_op == ops->ndo_bpf);
8672 return PTR_ERR(prog);
8674 if (!offload && bpf_prog_is_dev_bound(prog->aux)) {
8675 NL_SET_ERR_MSG(extack, "using device-bound program without HW_MODE flag is not supported");
8680 /* prog->aux->id may be 0 for orphaned device-bound progs */
8681 if (prog->aux->id && prog->aux->id == prog_id) {
8686 if (!__dev_xdp_query(dev, bpf_op, query))
8690 err = dev_xdp_install(dev, bpf_op, extack, flags, prog);
8691 if (err < 0 && prog)
8698 * dev_new_index - allocate an ifindex
8699 * @net: the applicable net namespace
8701 * Returns a suitable unique value for a new device interface
8702 * number. The caller must hold the rtnl semaphore or the
8703 * dev_base_lock to be sure it remains unique.
8705 static int dev_new_index(struct net *net)
8707 int ifindex = net->ifindex;
8712 if (!__dev_get_by_index(net, ifindex))
8713 return net->ifindex = ifindex;
8717 /* Delayed registration/unregisteration */
8718 static LIST_HEAD(net_todo_list);
8719 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
8721 static void net_set_todo(struct net_device *dev)
8723 list_add_tail(&dev->todo_list, &net_todo_list);
8724 dev_net(dev)->dev_unreg_count++;
8727 static void rollback_registered_many(struct list_head *head)
8729 struct net_device *dev, *tmp;
8730 LIST_HEAD(close_head);
8732 BUG_ON(dev_boot_phase);
8735 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
8736 /* Some devices call without registering
8737 * for initialization unwind. Remove those
8738 * devices and proceed with the remaining.
8740 if (dev->reg_state == NETREG_UNINITIALIZED) {
8741 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
8745 list_del(&dev->unreg_list);
8748 dev->dismantle = true;
8749 BUG_ON(dev->reg_state != NETREG_REGISTERED);
8752 /* If device is running, close it first. */
8753 list_for_each_entry(dev, head, unreg_list)
8754 list_add_tail(&dev->close_list, &close_head);
8755 dev_close_many(&close_head, true);
8757 list_for_each_entry(dev, head, unreg_list) {
8758 /* And unlink it from device chain. */
8759 unlist_netdevice(dev);
8761 dev->reg_state = NETREG_UNREGISTERING;
8763 flush_all_backlogs();
8767 list_for_each_entry(dev, head, unreg_list) {
8768 struct sk_buff *skb = NULL;
8770 /* Shutdown queueing discipline. */
8773 dev_xdp_uninstall(dev);
8775 /* Notify protocols, that we are about to destroy
8776 * this device. They should clean all the things.
8778 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
8780 if (!dev->rtnl_link_ops ||
8781 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
8782 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
8783 GFP_KERNEL, NULL, 0);
8786 * Flush the unicast and multicast chains
8791 netdev_name_node_alt_flush(dev);
8792 netdev_name_node_free(dev->name_node);
8794 if (dev->netdev_ops->ndo_uninit)
8795 dev->netdev_ops->ndo_uninit(dev);
8798 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
8800 /* Notifier chain MUST detach us all upper devices. */
8801 WARN_ON(netdev_has_any_upper_dev(dev));
8802 WARN_ON(netdev_has_any_lower_dev(dev));
8804 /* Remove entries from kobject tree */
8805 netdev_unregister_kobject(dev);
8807 /* Remove XPS queueing entries */
8808 netif_reset_xps_queues_gt(dev, 0);
8814 list_for_each_entry(dev, head, unreg_list)
8818 static void rollback_registered(struct net_device *dev)
8822 list_add(&dev->unreg_list, &single);
8823 rollback_registered_many(&single);
8827 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
8828 struct net_device *upper, netdev_features_t features)
8830 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
8831 netdev_features_t feature;
8834 for_each_netdev_feature(upper_disables, feature_bit) {
8835 feature = __NETIF_F_BIT(feature_bit);
8836 if (!(upper->wanted_features & feature)
8837 && (features & feature)) {
8838 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
8839 &feature, upper->name);
8840 features &= ~feature;
8847 static void netdev_sync_lower_features(struct net_device *upper,
8848 struct net_device *lower, netdev_features_t features)
8850 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
8851 netdev_features_t feature;
8854 for_each_netdev_feature(upper_disables, feature_bit) {
8855 feature = __NETIF_F_BIT(feature_bit);
8856 if (!(features & feature) && (lower->features & feature)) {
8857 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
8858 &feature, lower->name);
8859 lower->wanted_features &= ~feature;
8860 netdev_update_features(lower);
8862 if (unlikely(lower->features & feature))
8863 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
8864 &feature, lower->name);
8869 static netdev_features_t netdev_fix_features(struct net_device *dev,
8870 netdev_features_t features)
8872 /* Fix illegal checksum combinations */
8873 if ((features & NETIF_F_HW_CSUM) &&
8874 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
8875 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
8876 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
8879 /* TSO requires that SG is present as well. */
8880 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
8881 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
8882 features &= ~NETIF_F_ALL_TSO;
8885 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
8886 !(features & NETIF_F_IP_CSUM)) {
8887 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
8888 features &= ~NETIF_F_TSO;
8889 features &= ~NETIF_F_TSO_ECN;
8892 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
8893 !(features & NETIF_F_IPV6_CSUM)) {
8894 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
8895 features &= ~NETIF_F_TSO6;
8898 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
8899 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
8900 features &= ~NETIF_F_TSO_MANGLEID;
8902 /* TSO ECN requires that TSO is present as well. */
8903 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
8904 features &= ~NETIF_F_TSO_ECN;
8906 /* Software GSO depends on SG. */
8907 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
8908 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
8909 features &= ~NETIF_F_GSO;
8912 /* GSO partial features require GSO partial be set */
8913 if ((features & dev->gso_partial_features) &&
8914 !(features & NETIF_F_GSO_PARTIAL)) {
8916 "Dropping partially supported GSO features since no GSO partial.\n");
8917 features &= ~dev->gso_partial_features;
8920 if (!(features & NETIF_F_RXCSUM)) {
8921 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
8922 * successfully merged by hardware must also have the
8923 * checksum verified by hardware. If the user does not
8924 * want to enable RXCSUM, logically, we should disable GRO_HW.
8926 if (features & NETIF_F_GRO_HW) {
8927 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
8928 features &= ~NETIF_F_GRO_HW;
8932 /* LRO/HW-GRO features cannot be combined with RX-FCS */
8933 if (features & NETIF_F_RXFCS) {
8934 if (features & NETIF_F_LRO) {
8935 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
8936 features &= ~NETIF_F_LRO;
8939 if (features & NETIF_F_GRO_HW) {
8940 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
8941 features &= ~NETIF_F_GRO_HW;
8948 int __netdev_update_features(struct net_device *dev)
8950 struct net_device *upper, *lower;
8951 netdev_features_t features;
8952 struct list_head *iter;
8957 features = netdev_get_wanted_features(dev);
8959 if (dev->netdev_ops->ndo_fix_features)
8960 features = dev->netdev_ops->ndo_fix_features(dev, features);
8962 /* driver might be less strict about feature dependencies */
8963 features = netdev_fix_features(dev, features);
8965 /* some features can't be enabled if they're off an an upper device */
8966 netdev_for_each_upper_dev_rcu(dev, upper, iter)
8967 features = netdev_sync_upper_features(dev, upper, features);
8969 if (dev->features == features)
8972 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
8973 &dev->features, &features);
8975 if (dev->netdev_ops->ndo_set_features)
8976 err = dev->netdev_ops->ndo_set_features(dev, features);
8980 if (unlikely(err < 0)) {
8982 "set_features() failed (%d); wanted %pNF, left %pNF\n",
8983 err, &features, &dev->features);
8984 /* return non-0 since some features might have changed and
8985 * it's better to fire a spurious notification than miss it
8991 /* some features must be disabled on lower devices when disabled
8992 * on an upper device (think: bonding master or bridge)
8994 netdev_for_each_lower_dev(dev, lower, iter)
8995 netdev_sync_lower_features(dev, lower, features);
8998 netdev_features_t diff = features ^ dev->features;
9000 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9001 /* udp_tunnel_{get,drop}_rx_info both need
9002 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9003 * device, or they won't do anything.
9004 * Thus we need to update dev->features
9005 * *before* calling udp_tunnel_get_rx_info,
9006 * but *after* calling udp_tunnel_drop_rx_info.
9008 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9009 dev->features = features;
9010 udp_tunnel_get_rx_info(dev);
9012 udp_tunnel_drop_rx_info(dev);
9016 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9017 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9018 dev->features = features;
9019 err |= vlan_get_rx_ctag_filter_info(dev);
9021 vlan_drop_rx_ctag_filter_info(dev);
9025 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9026 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9027 dev->features = features;
9028 err |= vlan_get_rx_stag_filter_info(dev);
9030 vlan_drop_rx_stag_filter_info(dev);
9034 dev->features = features;
9037 return err < 0 ? 0 : 1;
9041 * netdev_update_features - recalculate device features
9042 * @dev: the device to check
9044 * Recalculate dev->features set and send notifications if it
9045 * has changed. Should be called after driver or hardware dependent
9046 * conditions might have changed that influence the features.
9048 void netdev_update_features(struct net_device *dev)
9050 if (__netdev_update_features(dev))
9051 netdev_features_change(dev);
9053 EXPORT_SYMBOL(netdev_update_features);
9056 * netdev_change_features - recalculate device features
9057 * @dev: the device to check
9059 * Recalculate dev->features set and send notifications even
9060 * if they have not changed. Should be called instead of
9061 * netdev_update_features() if also dev->vlan_features might
9062 * have changed to allow the changes to be propagated to stacked
9065 void netdev_change_features(struct net_device *dev)
9067 __netdev_update_features(dev);
9068 netdev_features_change(dev);
9070 EXPORT_SYMBOL(netdev_change_features);
9073 * netif_stacked_transfer_operstate - transfer operstate
9074 * @rootdev: the root or lower level device to transfer state from
9075 * @dev: the device to transfer operstate to
9077 * Transfer operational state from root to device. This is normally
9078 * called when a stacking relationship exists between the root
9079 * device and the device(a leaf device).
9081 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9082 struct net_device *dev)
9084 if (rootdev->operstate == IF_OPER_DORMANT)
9085 netif_dormant_on(dev);
9087 netif_dormant_off(dev);
9089 if (netif_carrier_ok(rootdev))
9090 netif_carrier_on(dev);
9092 netif_carrier_off(dev);
9094 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9096 static int netif_alloc_rx_queues(struct net_device *dev)
9098 unsigned int i, count = dev->num_rx_queues;
9099 struct netdev_rx_queue *rx;
9100 size_t sz = count * sizeof(*rx);
9105 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9111 for (i = 0; i < count; i++) {
9114 /* XDP RX-queue setup */
9115 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
9122 /* Rollback successful reg's and free other resources */
9124 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9130 static void netif_free_rx_queues(struct net_device *dev)
9132 unsigned int i, count = dev->num_rx_queues;
9134 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9138 for (i = 0; i < count; i++)
9139 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9144 static void netdev_init_one_queue(struct net_device *dev,
9145 struct netdev_queue *queue, void *_unused)
9147 /* Initialize queue lock */
9148 spin_lock_init(&queue->_xmit_lock);
9149 lockdep_set_class(&queue->_xmit_lock, &dev->qdisc_xmit_lock_key);
9150 queue->xmit_lock_owner = -1;
9151 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9154 dql_init(&queue->dql, HZ);
9158 static void netif_free_tx_queues(struct net_device *dev)
9163 static int netif_alloc_netdev_queues(struct net_device *dev)
9165 unsigned int count = dev->num_tx_queues;
9166 struct netdev_queue *tx;
9167 size_t sz = count * sizeof(*tx);
9169 if (count < 1 || count > 0xffff)
9172 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9178 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9179 spin_lock_init(&dev->tx_global_lock);
9184 void netif_tx_stop_all_queues(struct net_device *dev)
9188 for (i = 0; i < dev->num_tx_queues; i++) {
9189 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9191 netif_tx_stop_queue(txq);
9194 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9196 static void netdev_register_lockdep_key(struct net_device *dev)
9198 lockdep_register_key(&dev->qdisc_tx_busylock_key);
9199 lockdep_register_key(&dev->qdisc_running_key);
9200 lockdep_register_key(&dev->qdisc_xmit_lock_key);
9201 lockdep_register_key(&dev->addr_list_lock_key);
9204 static void netdev_unregister_lockdep_key(struct net_device *dev)
9206 lockdep_unregister_key(&dev->qdisc_tx_busylock_key);
9207 lockdep_unregister_key(&dev->qdisc_running_key);
9208 lockdep_unregister_key(&dev->qdisc_xmit_lock_key);
9209 lockdep_unregister_key(&dev->addr_list_lock_key);
9212 void netdev_update_lockdep_key(struct net_device *dev)
9214 lockdep_unregister_key(&dev->addr_list_lock_key);
9215 lockdep_register_key(&dev->addr_list_lock_key);
9217 lockdep_set_class(&dev->addr_list_lock, &dev->addr_list_lock_key);
9219 EXPORT_SYMBOL(netdev_update_lockdep_key);
9222 * register_netdevice - register a network device
9223 * @dev: device to register
9225 * Take a completed network device structure and add it to the kernel
9226 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9227 * chain. 0 is returned on success. A negative errno code is returned
9228 * on a failure to set up the device, or if the name is a duplicate.
9230 * Callers must hold the rtnl semaphore. You may want
9231 * register_netdev() instead of this.
9234 * The locking appears insufficient to guarantee two parallel registers
9235 * will not get the same name.
9238 int register_netdevice(struct net_device *dev)
9241 struct net *net = dev_net(dev);
9243 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9244 NETDEV_FEATURE_COUNT);
9245 BUG_ON(dev_boot_phase);
9250 /* When net_device's are persistent, this will be fatal. */
9251 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9254 spin_lock_init(&dev->addr_list_lock);
9255 lockdep_set_class(&dev->addr_list_lock, &dev->addr_list_lock_key);
9257 ret = dev_get_valid_name(net, dev, dev->name);
9262 dev->name_node = netdev_name_node_head_alloc(dev);
9263 if (!dev->name_node)
9266 /* Init, if this function is available */
9267 if (dev->netdev_ops->ndo_init) {
9268 ret = dev->netdev_ops->ndo_init(dev);
9276 if (((dev->hw_features | dev->features) &
9277 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9278 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9279 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9280 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
9287 dev->ifindex = dev_new_index(net);
9288 else if (__dev_get_by_index(net, dev->ifindex))
9291 /* Transfer changeable features to wanted_features and enable
9292 * software offloads (GSO and GRO).
9294 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
9295 dev->features |= NETIF_F_SOFT_FEATURES;
9297 if (dev->netdev_ops->ndo_udp_tunnel_add) {
9298 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9299 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9302 dev->wanted_features = dev->features & dev->hw_features;
9304 if (!(dev->flags & IFF_LOOPBACK))
9305 dev->hw_features |= NETIF_F_NOCACHE_COPY;
9307 /* If IPv4 TCP segmentation offload is supported we should also
9308 * allow the device to enable segmenting the frame with the option
9309 * of ignoring a static IP ID value. This doesn't enable the
9310 * feature itself but allows the user to enable it later.
9312 if (dev->hw_features & NETIF_F_TSO)
9313 dev->hw_features |= NETIF_F_TSO_MANGLEID;
9314 if (dev->vlan_features & NETIF_F_TSO)
9315 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
9316 if (dev->mpls_features & NETIF_F_TSO)
9317 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
9318 if (dev->hw_enc_features & NETIF_F_TSO)
9319 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9321 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
9323 dev->vlan_features |= NETIF_F_HIGHDMA;
9325 /* Make NETIF_F_SG inheritable to tunnel devices.
9327 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
9329 /* Make NETIF_F_SG inheritable to MPLS.
9331 dev->mpls_features |= NETIF_F_SG;
9333 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
9334 ret = notifier_to_errno(ret);
9338 ret = netdev_register_kobject(dev);
9340 dev->reg_state = NETREG_UNREGISTERED;
9343 dev->reg_state = NETREG_REGISTERED;
9345 __netdev_update_features(dev);
9348 * Default initial state at registry is that the
9349 * device is present.
9352 set_bit(__LINK_STATE_PRESENT, &dev->state);
9354 linkwatch_init_dev(dev);
9356 dev_init_scheduler(dev);
9358 list_netdevice(dev);
9359 add_device_randomness(dev->dev_addr, dev->addr_len);
9361 /* If the device has permanent device address, driver should
9362 * set dev_addr and also addr_assign_type should be set to
9363 * NET_ADDR_PERM (default value).
9365 if (dev->addr_assign_type == NET_ADDR_PERM)
9366 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
9368 /* Notify protocols, that a new device appeared. */
9369 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
9370 ret = notifier_to_errno(ret);
9372 rollback_registered(dev);
9375 dev->reg_state = NETREG_UNREGISTERED;
9378 * Prevent userspace races by waiting until the network
9379 * device is fully setup before sending notifications.
9381 if (!dev->rtnl_link_ops ||
9382 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9383 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9389 if (dev->netdev_ops->ndo_uninit)
9390 dev->netdev_ops->ndo_uninit(dev);
9391 if (dev->priv_destructor)
9392 dev->priv_destructor(dev);
9394 netdev_name_node_free(dev->name_node);
9397 EXPORT_SYMBOL(register_netdevice);
9400 * init_dummy_netdev - init a dummy network device for NAPI
9401 * @dev: device to init
9403 * This takes a network device structure and initialize the minimum
9404 * amount of fields so it can be used to schedule NAPI polls without
9405 * registering a full blown interface. This is to be used by drivers
9406 * that need to tie several hardware interfaces to a single NAPI
9407 * poll scheduler due to HW limitations.
9409 int init_dummy_netdev(struct net_device *dev)
9411 /* Clear everything. Note we don't initialize spinlocks
9412 * are they aren't supposed to be taken by any of the
9413 * NAPI code and this dummy netdev is supposed to be
9414 * only ever used for NAPI polls
9416 memset(dev, 0, sizeof(struct net_device));
9418 /* make sure we BUG if trying to hit standard
9419 * register/unregister code path
9421 dev->reg_state = NETREG_DUMMY;
9423 /* NAPI wants this */
9424 INIT_LIST_HEAD(&dev->napi_list);
9426 /* a dummy interface is started by default */
9427 set_bit(__LINK_STATE_PRESENT, &dev->state);
9428 set_bit(__LINK_STATE_START, &dev->state);
9430 /* napi_busy_loop stats accounting wants this */
9431 dev_net_set(dev, &init_net);
9433 /* Note : We dont allocate pcpu_refcnt for dummy devices,
9434 * because users of this 'device' dont need to change
9440 EXPORT_SYMBOL_GPL(init_dummy_netdev);
9444 * register_netdev - register a network device
9445 * @dev: device to register
9447 * Take a completed network device structure and add it to the kernel
9448 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9449 * chain. 0 is returned on success. A negative errno code is returned
9450 * on a failure to set up the device, or if the name is a duplicate.
9452 * This is a wrapper around register_netdevice that takes the rtnl semaphore
9453 * and expands the device name if you passed a format string to
9456 int register_netdev(struct net_device *dev)
9460 if (rtnl_lock_killable())
9462 err = register_netdevice(dev);
9466 EXPORT_SYMBOL(register_netdev);
9468 int netdev_refcnt_read(const struct net_device *dev)
9472 for_each_possible_cpu(i)
9473 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
9476 EXPORT_SYMBOL(netdev_refcnt_read);
9479 * netdev_wait_allrefs - wait until all references are gone.
9480 * @dev: target net_device
9482 * This is called when unregistering network devices.
9484 * Any protocol or device that holds a reference should register
9485 * for netdevice notification, and cleanup and put back the
9486 * reference if they receive an UNREGISTER event.
9487 * We can get stuck here if buggy protocols don't correctly
9490 static void netdev_wait_allrefs(struct net_device *dev)
9492 unsigned long rebroadcast_time, warning_time;
9495 linkwatch_forget_dev(dev);
9497 rebroadcast_time = warning_time = jiffies;
9498 refcnt = netdev_refcnt_read(dev);
9500 while (refcnt != 0) {
9501 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
9504 /* Rebroadcast unregister notification */
9505 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9511 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
9513 /* We must not have linkwatch events
9514 * pending on unregister. If this
9515 * happens, we simply run the queue
9516 * unscheduled, resulting in a noop
9519 linkwatch_run_queue();
9524 rebroadcast_time = jiffies;
9529 refcnt = netdev_refcnt_read(dev);
9531 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
9532 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
9534 warning_time = jiffies;
9543 * register_netdevice(x1);
9544 * register_netdevice(x2);
9546 * unregister_netdevice(y1);
9547 * unregister_netdevice(y2);
9553 * We are invoked by rtnl_unlock().
9554 * This allows us to deal with problems:
9555 * 1) We can delete sysfs objects which invoke hotplug
9556 * without deadlocking with linkwatch via keventd.
9557 * 2) Since we run with the RTNL semaphore not held, we can sleep
9558 * safely in order to wait for the netdev refcnt to drop to zero.
9560 * We must not return until all unregister events added during
9561 * the interval the lock was held have been completed.
9563 void netdev_run_todo(void)
9565 struct list_head list;
9567 /* Snapshot list, allow later requests */
9568 list_replace_init(&net_todo_list, &list);
9573 /* Wait for rcu callbacks to finish before next phase */
9574 if (!list_empty(&list))
9577 while (!list_empty(&list)) {
9578 struct net_device *dev
9579 = list_first_entry(&list, struct net_device, todo_list);
9580 list_del(&dev->todo_list);
9582 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
9583 pr_err("network todo '%s' but state %d\n",
9584 dev->name, dev->reg_state);
9589 dev->reg_state = NETREG_UNREGISTERED;
9591 netdev_wait_allrefs(dev);
9594 BUG_ON(netdev_refcnt_read(dev));
9595 BUG_ON(!list_empty(&dev->ptype_all));
9596 BUG_ON(!list_empty(&dev->ptype_specific));
9597 WARN_ON(rcu_access_pointer(dev->ip_ptr));
9598 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
9599 #if IS_ENABLED(CONFIG_DECNET)
9600 WARN_ON(dev->dn_ptr);
9602 if (dev->priv_destructor)
9603 dev->priv_destructor(dev);
9604 if (dev->needs_free_netdev)
9607 /* Report a network device has been unregistered */
9609 dev_net(dev)->dev_unreg_count--;
9611 wake_up(&netdev_unregistering_wq);
9613 /* Free network device */
9614 kobject_put(&dev->dev.kobj);
9618 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
9619 * all the same fields in the same order as net_device_stats, with only
9620 * the type differing, but rtnl_link_stats64 may have additional fields
9621 * at the end for newer counters.
9623 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
9624 const struct net_device_stats *netdev_stats)
9626 #if BITS_PER_LONG == 64
9627 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
9628 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
9629 /* zero out counters that only exist in rtnl_link_stats64 */
9630 memset((char *)stats64 + sizeof(*netdev_stats), 0,
9631 sizeof(*stats64) - sizeof(*netdev_stats));
9633 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
9634 const unsigned long *src = (const unsigned long *)netdev_stats;
9635 u64 *dst = (u64 *)stats64;
9637 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
9638 for (i = 0; i < n; i++)
9640 /* zero out counters that only exist in rtnl_link_stats64 */
9641 memset((char *)stats64 + n * sizeof(u64), 0,
9642 sizeof(*stats64) - n * sizeof(u64));
9645 EXPORT_SYMBOL(netdev_stats_to_stats64);
9648 * dev_get_stats - get network device statistics
9649 * @dev: device to get statistics from
9650 * @storage: place to store stats
9652 * Get network statistics from device. Return @storage.
9653 * The device driver may provide its own method by setting
9654 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
9655 * otherwise the internal statistics structure is used.
9657 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
9658 struct rtnl_link_stats64 *storage)
9660 const struct net_device_ops *ops = dev->netdev_ops;
9662 if (ops->ndo_get_stats64) {
9663 memset(storage, 0, sizeof(*storage));
9664 ops->ndo_get_stats64(dev, storage);
9665 } else if (ops->ndo_get_stats) {
9666 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
9668 netdev_stats_to_stats64(storage, &dev->stats);
9670 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
9671 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
9672 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
9675 EXPORT_SYMBOL(dev_get_stats);
9677 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
9679 struct netdev_queue *queue = dev_ingress_queue(dev);
9681 #ifdef CONFIG_NET_CLS_ACT
9684 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
9687 netdev_init_one_queue(dev, queue, NULL);
9688 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
9689 queue->qdisc_sleeping = &noop_qdisc;
9690 rcu_assign_pointer(dev->ingress_queue, queue);
9695 static const struct ethtool_ops default_ethtool_ops;
9697 void netdev_set_default_ethtool_ops(struct net_device *dev,
9698 const struct ethtool_ops *ops)
9700 if (dev->ethtool_ops == &default_ethtool_ops)
9701 dev->ethtool_ops = ops;
9703 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
9705 void netdev_freemem(struct net_device *dev)
9707 char *addr = (char *)dev - dev->padded;
9713 * alloc_netdev_mqs - allocate network device
9714 * @sizeof_priv: size of private data to allocate space for
9715 * @name: device name format string
9716 * @name_assign_type: origin of device name
9717 * @setup: callback to initialize device
9718 * @txqs: the number of TX subqueues to allocate
9719 * @rxqs: the number of RX subqueues to allocate
9721 * Allocates a struct net_device with private data area for driver use
9722 * and performs basic initialization. Also allocates subqueue structs
9723 * for each queue on the device.
9725 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
9726 unsigned char name_assign_type,
9727 void (*setup)(struct net_device *),
9728 unsigned int txqs, unsigned int rxqs)
9730 struct net_device *dev;
9731 unsigned int alloc_size;
9732 struct net_device *p;
9734 BUG_ON(strlen(name) >= sizeof(dev->name));
9737 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
9742 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
9746 alloc_size = sizeof(struct net_device);
9748 /* ensure 32-byte alignment of private area */
9749 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
9750 alloc_size += sizeof_priv;
9752 /* ensure 32-byte alignment of whole construct */
9753 alloc_size += NETDEV_ALIGN - 1;
9755 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9759 dev = PTR_ALIGN(p, NETDEV_ALIGN);
9760 dev->padded = (char *)dev - (char *)p;
9762 dev->pcpu_refcnt = alloc_percpu(int);
9763 if (!dev->pcpu_refcnt)
9766 if (dev_addr_init(dev))
9772 dev_net_set(dev, &init_net);
9774 netdev_register_lockdep_key(dev);
9776 dev->gso_max_size = GSO_MAX_SIZE;
9777 dev->gso_max_segs = GSO_MAX_SEGS;
9778 dev->upper_level = 1;
9779 dev->lower_level = 1;
9781 INIT_LIST_HEAD(&dev->napi_list);
9782 INIT_LIST_HEAD(&dev->unreg_list);
9783 INIT_LIST_HEAD(&dev->close_list);
9784 INIT_LIST_HEAD(&dev->link_watch_list);
9785 INIT_LIST_HEAD(&dev->adj_list.upper);
9786 INIT_LIST_HEAD(&dev->adj_list.lower);
9787 INIT_LIST_HEAD(&dev->ptype_all);
9788 INIT_LIST_HEAD(&dev->ptype_specific);
9789 #ifdef CONFIG_NET_SCHED
9790 hash_init(dev->qdisc_hash);
9792 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
9795 if (!dev->tx_queue_len) {
9796 dev->priv_flags |= IFF_NO_QUEUE;
9797 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
9800 dev->num_tx_queues = txqs;
9801 dev->real_num_tx_queues = txqs;
9802 if (netif_alloc_netdev_queues(dev))
9805 dev->num_rx_queues = rxqs;
9806 dev->real_num_rx_queues = rxqs;
9807 if (netif_alloc_rx_queues(dev))
9810 strcpy(dev->name, name);
9811 dev->name_assign_type = name_assign_type;
9812 dev->group = INIT_NETDEV_GROUP;
9813 if (!dev->ethtool_ops)
9814 dev->ethtool_ops = &default_ethtool_ops;
9816 nf_hook_ingress_init(dev);
9825 free_percpu(dev->pcpu_refcnt);
9827 netdev_freemem(dev);
9830 EXPORT_SYMBOL(alloc_netdev_mqs);
9833 * free_netdev - free network device
9836 * This function does the last stage of destroying an allocated device
9837 * interface. The reference to the device object is released. If this
9838 * is the last reference then it will be freed.Must be called in process
9841 void free_netdev(struct net_device *dev)
9843 struct napi_struct *p, *n;
9846 netif_free_tx_queues(dev);
9847 netif_free_rx_queues(dev);
9849 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
9851 /* Flush device addresses */
9852 dev_addr_flush(dev);
9854 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
9857 free_percpu(dev->pcpu_refcnt);
9858 dev->pcpu_refcnt = NULL;
9859 free_percpu(dev->xdp_bulkq);
9860 dev->xdp_bulkq = NULL;
9862 netdev_unregister_lockdep_key(dev);
9864 /* Compatibility with error handling in drivers */
9865 if (dev->reg_state == NETREG_UNINITIALIZED) {
9866 netdev_freemem(dev);
9870 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
9871 dev->reg_state = NETREG_RELEASED;
9873 /* will free via device release */
9874 put_device(&dev->dev);
9876 EXPORT_SYMBOL(free_netdev);
9879 * synchronize_net - Synchronize with packet receive processing
9881 * Wait for packets currently being received to be done.
9882 * Does not block later packets from starting.
9884 void synchronize_net(void)
9887 if (rtnl_is_locked())
9888 synchronize_rcu_expedited();
9892 EXPORT_SYMBOL(synchronize_net);
9895 * unregister_netdevice_queue - remove device from the kernel
9899 * This function shuts down a device interface and removes it
9900 * from the kernel tables.
9901 * If head not NULL, device is queued to be unregistered later.
9903 * Callers must hold the rtnl semaphore. You may want
9904 * unregister_netdev() instead of this.
9907 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
9912 list_move_tail(&dev->unreg_list, head);
9914 rollback_registered(dev);
9915 /* Finish processing unregister after unlock */
9919 EXPORT_SYMBOL(unregister_netdevice_queue);
9922 * unregister_netdevice_many - unregister many devices
9923 * @head: list of devices
9925 * Note: As most callers use a stack allocated list_head,
9926 * we force a list_del() to make sure stack wont be corrupted later.
9928 void unregister_netdevice_many(struct list_head *head)
9930 struct net_device *dev;
9932 if (!list_empty(head)) {
9933 rollback_registered_many(head);
9934 list_for_each_entry(dev, head, unreg_list)
9939 EXPORT_SYMBOL(unregister_netdevice_many);
9942 * unregister_netdev - remove device from the kernel
9945 * This function shuts down a device interface and removes it
9946 * from the kernel tables.
9948 * This is just a wrapper for unregister_netdevice that takes
9949 * the rtnl semaphore. In general you want to use this and not
9950 * unregister_netdevice.
9952 void unregister_netdev(struct net_device *dev)
9955 unregister_netdevice(dev);
9958 EXPORT_SYMBOL(unregister_netdev);
9961 * dev_change_net_namespace - move device to different nethost namespace
9963 * @net: network namespace
9964 * @pat: If not NULL name pattern to try if the current device name
9965 * is already taken in the destination network namespace.
9967 * This function shuts down a device interface and moves it
9968 * to a new network namespace. On success 0 is returned, on
9969 * a failure a netagive errno code is returned.
9971 * Callers must hold the rtnl semaphore.
9974 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
9976 int err, new_nsid, new_ifindex;
9980 /* Don't allow namespace local devices to be moved. */
9982 if (dev->features & NETIF_F_NETNS_LOCAL)
9985 /* Ensure the device has been registrered */
9986 if (dev->reg_state != NETREG_REGISTERED)
9989 /* Get out if there is nothing todo */
9991 if (net_eq(dev_net(dev), net))
9994 /* Pick the destination device name, and ensure
9995 * we can use it in the destination network namespace.
9998 if (__dev_get_by_name(net, dev->name)) {
9999 /* We get here if we can't use the current device name */
10002 err = dev_get_valid_name(net, dev, pat);
10008 * And now a mini version of register_netdevice unregister_netdevice.
10011 /* If device is running close it first. */
10014 /* And unlink it from device chain */
10015 unlist_netdevice(dev);
10019 /* Shutdown queueing discipline. */
10022 /* Notify protocols, that we are about to destroy
10023 * this device. They should clean all the things.
10025 * Note that dev->reg_state stays at NETREG_REGISTERED.
10026 * This is wanted because this way 8021q and macvlan know
10027 * the device is just moving and can keep their slaves up.
10029 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10032 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10033 /* If there is an ifindex conflict assign a new one */
10034 if (__dev_get_by_index(net, dev->ifindex))
10035 new_ifindex = dev_new_index(net);
10037 new_ifindex = dev->ifindex;
10039 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10043 * Flush the unicast and multicast chains
10048 /* Send a netdev-removed uevent to the old namespace */
10049 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10050 netdev_adjacent_del_links(dev);
10052 /* Actually switch the network namespace */
10053 dev_net_set(dev, net);
10054 dev->ifindex = new_ifindex;
10056 /* Send a netdev-add uevent to the new namespace */
10057 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10058 netdev_adjacent_add_links(dev);
10060 /* Fixup kobjects */
10061 err = device_rename(&dev->dev, dev->name);
10064 /* Add the device back in the hashes */
10065 list_netdevice(dev);
10067 /* Notify protocols, that a new device appeared. */
10068 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10071 * Prevent userspace races by waiting until the network
10072 * device is fully setup before sending notifications.
10074 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10081 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
10083 static int dev_cpu_dead(unsigned int oldcpu)
10085 struct sk_buff **list_skb;
10086 struct sk_buff *skb;
10088 struct softnet_data *sd, *oldsd, *remsd = NULL;
10090 local_irq_disable();
10091 cpu = smp_processor_id();
10092 sd = &per_cpu(softnet_data, cpu);
10093 oldsd = &per_cpu(softnet_data, oldcpu);
10095 /* Find end of our completion_queue. */
10096 list_skb = &sd->completion_queue;
10098 list_skb = &(*list_skb)->next;
10099 /* Append completion queue from offline CPU. */
10100 *list_skb = oldsd->completion_queue;
10101 oldsd->completion_queue = NULL;
10103 /* Append output queue from offline CPU. */
10104 if (oldsd->output_queue) {
10105 *sd->output_queue_tailp = oldsd->output_queue;
10106 sd->output_queue_tailp = oldsd->output_queue_tailp;
10107 oldsd->output_queue = NULL;
10108 oldsd->output_queue_tailp = &oldsd->output_queue;
10110 /* Append NAPI poll list from offline CPU, with one exception :
10111 * process_backlog() must be called by cpu owning percpu backlog.
10112 * We properly handle process_queue & input_pkt_queue later.
10114 while (!list_empty(&oldsd->poll_list)) {
10115 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10116 struct napi_struct,
10119 list_del_init(&napi->poll_list);
10120 if (napi->poll == process_backlog)
10123 ____napi_schedule(sd, napi);
10126 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10127 local_irq_enable();
10130 remsd = oldsd->rps_ipi_list;
10131 oldsd->rps_ipi_list = NULL;
10133 /* send out pending IPI's on offline CPU */
10134 net_rps_send_ipi(remsd);
10136 /* Process offline CPU's input_pkt_queue */
10137 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
10139 input_queue_head_incr(oldsd);
10141 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
10143 input_queue_head_incr(oldsd);
10150 * netdev_increment_features - increment feature set by one
10151 * @all: current feature set
10152 * @one: new feature set
10153 * @mask: mask feature set
10155 * Computes a new feature set after adding a device with feature set
10156 * @one to the master device with current feature set @all. Will not
10157 * enable anything that is off in @mask. Returns the new feature set.
10159 netdev_features_t netdev_increment_features(netdev_features_t all,
10160 netdev_features_t one, netdev_features_t mask)
10162 if (mask & NETIF_F_HW_CSUM)
10163 mask |= NETIF_F_CSUM_MASK;
10164 mask |= NETIF_F_VLAN_CHALLENGED;
10166 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
10167 all &= one | ~NETIF_F_ALL_FOR_ALL;
10169 /* If one device supports hw checksumming, set for all. */
10170 if (all & NETIF_F_HW_CSUM)
10171 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
10175 EXPORT_SYMBOL(netdev_increment_features);
10177 static struct hlist_head * __net_init netdev_create_hash(void)
10180 struct hlist_head *hash;
10182 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
10184 for (i = 0; i < NETDEV_HASHENTRIES; i++)
10185 INIT_HLIST_HEAD(&hash[i]);
10190 /* Initialize per network namespace state */
10191 static int __net_init netdev_init(struct net *net)
10193 BUILD_BUG_ON(GRO_HASH_BUCKETS >
10194 8 * sizeof_field(struct napi_struct, gro_bitmask));
10196 if (net != &init_net)
10197 INIT_LIST_HEAD(&net->dev_base_head);
10199 net->dev_name_head = netdev_create_hash();
10200 if (net->dev_name_head == NULL)
10203 net->dev_index_head = netdev_create_hash();
10204 if (net->dev_index_head == NULL)
10207 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
10212 kfree(net->dev_name_head);
10218 * netdev_drivername - network driver for the device
10219 * @dev: network device
10221 * Determine network driver for device.
10223 const char *netdev_drivername(const struct net_device *dev)
10225 const struct device_driver *driver;
10226 const struct device *parent;
10227 const char *empty = "";
10229 parent = dev->dev.parent;
10233 driver = parent->driver;
10234 if (driver && driver->name)
10235 return driver->name;
10239 static void __netdev_printk(const char *level, const struct net_device *dev,
10240 struct va_format *vaf)
10242 if (dev && dev->dev.parent) {
10243 dev_printk_emit(level[1] - '0',
10246 dev_driver_string(dev->dev.parent),
10247 dev_name(dev->dev.parent),
10248 netdev_name(dev), netdev_reg_state(dev),
10251 printk("%s%s%s: %pV",
10252 level, netdev_name(dev), netdev_reg_state(dev), vaf);
10254 printk("%s(NULL net_device): %pV", level, vaf);
10258 void netdev_printk(const char *level, const struct net_device *dev,
10259 const char *format, ...)
10261 struct va_format vaf;
10264 va_start(args, format);
10269 __netdev_printk(level, dev, &vaf);
10273 EXPORT_SYMBOL(netdev_printk);
10275 #define define_netdev_printk_level(func, level) \
10276 void func(const struct net_device *dev, const char *fmt, ...) \
10278 struct va_format vaf; \
10281 va_start(args, fmt); \
10286 __netdev_printk(level, dev, &vaf); \
10290 EXPORT_SYMBOL(func);
10292 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
10293 define_netdev_printk_level(netdev_alert, KERN_ALERT);
10294 define_netdev_printk_level(netdev_crit, KERN_CRIT);
10295 define_netdev_printk_level(netdev_err, KERN_ERR);
10296 define_netdev_printk_level(netdev_warn, KERN_WARNING);
10297 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
10298 define_netdev_printk_level(netdev_info, KERN_INFO);
10300 static void __net_exit netdev_exit(struct net *net)
10302 kfree(net->dev_name_head);
10303 kfree(net->dev_index_head);
10304 if (net != &init_net)
10305 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
10308 static struct pernet_operations __net_initdata netdev_net_ops = {
10309 .init = netdev_init,
10310 .exit = netdev_exit,
10313 static void __net_exit default_device_exit(struct net *net)
10315 struct net_device *dev, *aux;
10317 * Push all migratable network devices back to the
10318 * initial network namespace
10321 for_each_netdev_safe(net, dev, aux) {
10323 char fb_name[IFNAMSIZ];
10325 /* Ignore unmoveable devices (i.e. loopback) */
10326 if (dev->features & NETIF_F_NETNS_LOCAL)
10329 /* Leave virtual devices for the generic cleanup */
10330 if (dev->rtnl_link_ops)
10333 /* Push remaining network devices to init_net */
10334 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
10335 if (__dev_get_by_name(&init_net, fb_name))
10336 snprintf(fb_name, IFNAMSIZ, "dev%%d");
10337 err = dev_change_net_namespace(dev, &init_net, fb_name);
10339 pr_emerg("%s: failed to move %s to init_net: %d\n",
10340 __func__, dev->name, err);
10347 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
10349 /* Return with the rtnl_lock held when there are no network
10350 * devices unregistering in any network namespace in net_list.
10353 bool unregistering;
10354 DEFINE_WAIT_FUNC(wait, woken_wake_function);
10356 add_wait_queue(&netdev_unregistering_wq, &wait);
10358 unregistering = false;
10360 list_for_each_entry(net, net_list, exit_list) {
10361 if (net->dev_unreg_count > 0) {
10362 unregistering = true;
10366 if (!unregistering)
10370 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
10372 remove_wait_queue(&netdev_unregistering_wq, &wait);
10375 static void __net_exit default_device_exit_batch(struct list_head *net_list)
10377 /* At exit all network devices most be removed from a network
10378 * namespace. Do this in the reverse order of registration.
10379 * Do this across as many network namespaces as possible to
10380 * improve batching efficiency.
10382 struct net_device *dev;
10384 LIST_HEAD(dev_kill_list);
10386 /* To prevent network device cleanup code from dereferencing
10387 * loopback devices or network devices that have been freed
10388 * wait here for all pending unregistrations to complete,
10389 * before unregistring the loopback device and allowing the
10390 * network namespace be freed.
10392 * The netdev todo list containing all network devices
10393 * unregistrations that happen in default_device_exit_batch
10394 * will run in the rtnl_unlock() at the end of
10395 * default_device_exit_batch.
10397 rtnl_lock_unregistering(net_list);
10398 list_for_each_entry(net, net_list, exit_list) {
10399 for_each_netdev_reverse(net, dev) {
10400 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
10401 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
10403 unregister_netdevice_queue(dev, &dev_kill_list);
10406 unregister_netdevice_many(&dev_kill_list);
10410 static struct pernet_operations __net_initdata default_device_ops = {
10411 .exit = default_device_exit,
10412 .exit_batch = default_device_exit_batch,
10416 * Initialize the DEV module. At boot time this walks the device list and
10417 * unhooks any devices that fail to initialise (normally hardware not
10418 * present) and leaves us with a valid list of present and active devices.
10423 * This is called single threaded during boot, so no need
10424 * to take the rtnl semaphore.
10426 static int __init net_dev_init(void)
10428 int i, rc = -ENOMEM;
10430 BUG_ON(!dev_boot_phase);
10432 if (dev_proc_init())
10435 if (netdev_kobject_init())
10438 INIT_LIST_HEAD(&ptype_all);
10439 for (i = 0; i < PTYPE_HASH_SIZE; i++)
10440 INIT_LIST_HEAD(&ptype_base[i]);
10442 INIT_LIST_HEAD(&offload_base);
10444 if (register_pernet_subsys(&netdev_net_ops))
10448 * Initialise the packet receive queues.
10451 for_each_possible_cpu(i) {
10452 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
10453 struct softnet_data *sd = &per_cpu(softnet_data, i);
10455 INIT_WORK(flush, flush_backlog);
10457 skb_queue_head_init(&sd->input_pkt_queue);
10458 skb_queue_head_init(&sd->process_queue);
10459 #ifdef CONFIG_XFRM_OFFLOAD
10460 skb_queue_head_init(&sd->xfrm_backlog);
10462 INIT_LIST_HEAD(&sd->poll_list);
10463 sd->output_queue_tailp = &sd->output_queue;
10465 sd->csd.func = rps_trigger_softirq;
10470 init_gro_hash(&sd->backlog);
10471 sd->backlog.poll = process_backlog;
10472 sd->backlog.weight = weight_p;
10475 dev_boot_phase = 0;
10477 /* The loopback device is special if any other network devices
10478 * is present in a network namespace the loopback device must
10479 * be present. Since we now dynamically allocate and free the
10480 * loopback device ensure this invariant is maintained by
10481 * keeping the loopback device as the first device on the
10482 * list of network devices. Ensuring the loopback devices
10483 * is the first device that appears and the last network device
10486 if (register_pernet_device(&loopback_net_ops))
10489 if (register_pernet_device(&default_device_ops))
10492 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
10493 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
10495 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
10496 NULL, dev_cpu_dead);
10503 subsys_initcall(net_dev_init);