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 /* Device list insertion */
233 static void list_netdevice(struct net_device *dev)
235 struct net *net = dev_net(dev);
239 write_lock_bh(&dev_base_lock);
240 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
241 hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
242 hlist_add_head_rcu(&dev->index_hlist,
243 dev_index_hash(net, dev->ifindex));
244 write_unlock_bh(&dev_base_lock);
246 dev_base_seq_inc(net);
249 /* Device list removal
250 * caller must respect a RCU grace period before freeing/reusing dev
252 static void unlist_netdevice(struct net_device *dev)
256 /* Unlink dev from the device chain */
257 write_lock_bh(&dev_base_lock);
258 list_del_rcu(&dev->dev_list);
259 hlist_del_rcu(&dev->name_hlist);
260 hlist_del_rcu(&dev->index_hlist);
261 write_unlock_bh(&dev_base_lock);
263 dev_base_seq_inc(dev_net(dev));
270 static RAW_NOTIFIER_HEAD(netdev_chain);
273 * Device drivers call our routines to queue packets here. We empty the
274 * queue in the local softnet handler.
277 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
278 EXPORT_PER_CPU_SYMBOL(softnet_data);
280 #ifdef CONFIG_LOCKDEP
282 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
283 * according to dev->type
285 static const unsigned short netdev_lock_type[] = {
286 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
287 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
288 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
289 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
290 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
291 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
292 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
293 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
294 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
295 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
296 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
297 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
298 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
299 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
300 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
302 static const char *const netdev_lock_name[] = {
303 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
304 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
305 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
306 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
307 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
308 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
309 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
310 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
311 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
312 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
313 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
314 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
315 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
316 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
317 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
319 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
320 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
322 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
326 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
327 if (netdev_lock_type[i] == dev_type)
329 /* the last key is used by default */
330 return ARRAY_SIZE(netdev_lock_type) - 1;
333 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
334 unsigned short dev_type)
338 i = netdev_lock_pos(dev_type);
339 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
340 netdev_lock_name[i]);
343 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
347 i = netdev_lock_pos(dev->type);
348 lockdep_set_class_and_name(&dev->addr_list_lock,
349 &netdev_addr_lock_key[i],
350 netdev_lock_name[i]);
353 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
354 unsigned short dev_type)
357 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
362 /*******************************************************************************
364 * Protocol management and registration routines
366 *******************************************************************************/
370 * Add a protocol ID to the list. Now that the input handler is
371 * smarter we can dispense with all the messy stuff that used to be
374 * BEWARE!!! Protocol handlers, mangling input packets,
375 * MUST BE last in hash buckets and checking protocol handlers
376 * MUST start from promiscuous ptype_all chain in net_bh.
377 * It is true now, do not change it.
378 * Explanation follows: if protocol handler, mangling packet, will
379 * be the first on list, it is not able to sense, that packet
380 * is cloned and should be copied-on-write, so that it will
381 * change it and subsequent readers will get broken packet.
385 static inline struct list_head *ptype_head(const struct packet_type *pt)
387 if (pt->type == htons(ETH_P_ALL))
388 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
390 return pt->dev ? &pt->dev->ptype_specific :
391 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
395 * dev_add_pack - add packet handler
396 * @pt: packet type declaration
398 * Add a protocol handler to the networking stack. The passed &packet_type
399 * is linked into kernel lists and may not be freed until it has been
400 * removed from the kernel lists.
402 * This call does not sleep therefore it can not
403 * guarantee all CPU's that are in middle of receiving packets
404 * will see the new packet type (until the next received packet).
407 void dev_add_pack(struct packet_type *pt)
409 struct list_head *head = ptype_head(pt);
411 spin_lock(&ptype_lock);
412 list_add_rcu(&pt->list, head);
413 spin_unlock(&ptype_lock);
415 EXPORT_SYMBOL(dev_add_pack);
418 * __dev_remove_pack - remove packet handler
419 * @pt: packet type declaration
421 * Remove a protocol handler that was previously added to the kernel
422 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
423 * from the kernel lists and can be freed or reused once this function
426 * The packet type might still be in use by receivers
427 * and must not be freed until after all the CPU's have gone
428 * through a quiescent state.
430 void __dev_remove_pack(struct packet_type *pt)
432 struct list_head *head = ptype_head(pt);
433 struct packet_type *pt1;
435 spin_lock(&ptype_lock);
437 list_for_each_entry(pt1, head, list) {
439 list_del_rcu(&pt->list);
444 pr_warn("dev_remove_pack: %p not found\n", pt);
446 spin_unlock(&ptype_lock);
448 EXPORT_SYMBOL(__dev_remove_pack);
451 * dev_remove_pack - remove packet handler
452 * @pt: packet type declaration
454 * Remove a protocol handler that was previously added to the kernel
455 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
456 * from the kernel lists and can be freed or reused once this function
459 * This call sleeps to guarantee that no CPU is looking at the packet
462 void dev_remove_pack(struct packet_type *pt)
464 __dev_remove_pack(pt);
468 EXPORT_SYMBOL(dev_remove_pack);
472 * dev_add_offload - register offload handlers
473 * @po: protocol offload declaration
475 * Add protocol offload handlers to the networking stack. The passed
476 * &proto_offload is linked into kernel lists and may not be freed until
477 * it has been removed from the kernel lists.
479 * This call does not sleep therefore it can not
480 * guarantee all CPU's that are in middle of receiving packets
481 * will see the new offload handlers (until the next received packet).
483 void dev_add_offload(struct packet_offload *po)
485 struct packet_offload *elem;
487 spin_lock(&offload_lock);
488 list_for_each_entry(elem, &offload_base, list) {
489 if (po->priority < elem->priority)
492 list_add_rcu(&po->list, elem->list.prev);
493 spin_unlock(&offload_lock);
495 EXPORT_SYMBOL(dev_add_offload);
498 * __dev_remove_offload - remove offload handler
499 * @po: packet offload declaration
501 * Remove a protocol offload handler that was previously added to the
502 * kernel offload handlers by dev_add_offload(). The passed &offload_type
503 * is removed from the kernel lists and can be freed or reused once this
506 * The packet type might still be in use by receivers
507 * and must not be freed until after all the CPU's have gone
508 * through a quiescent state.
510 static void __dev_remove_offload(struct packet_offload *po)
512 struct list_head *head = &offload_base;
513 struct packet_offload *po1;
515 spin_lock(&offload_lock);
517 list_for_each_entry(po1, head, list) {
519 list_del_rcu(&po->list);
524 pr_warn("dev_remove_offload: %p not found\n", po);
526 spin_unlock(&offload_lock);
530 * dev_remove_offload - remove packet offload handler
531 * @po: packet offload declaration
533 * Remove a packet offload handler that was previously added to the kernel
534 * offload handlers by dev_add_offload(). The passed &offload_type is
535 * removed from the kernel lists and can be freed or reused once this
538 * This call sleeps to guarantee that no CPU is looking at the packet
541 void dev_remove_offload(struct packet_offload *po)
543 __dev_remove_offload(po);
547 EXPORT_SYMBOL(dev_remove_offload);
549 /******************************************************************************
551 * Device Boot-time Settings Routines
553 ******************************************************************************/
555 /* Boot time configuration table */
556 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
559 * netdev_boot_setup_add - add new setup entry
560 * @name: name of the device
561 * @map: configured settings for the device
563 * Adds new setup entry to the dev_boot_setup list. The function
564 * returns 0 on error and 1 on success. This is a generic routine to
567 static int netdev_boot_setup_add(char *name, struct ifmap *map)
569 struct netdev_boot_setup *s;
573 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
574 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
575 memset(s[i].name, 0, sizeof(s[i].name));
576 strlcpy(s[i].name, name, IFNAMSIZ);
577 memcpy(&s[i].map, map, sizeof(s[i].map));
582 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
586 * netdev_boot_setup_check - check boot time settings
587 * @dev: the netdevice
589 * Check boot time settings for the device.
590 * The found settings are set for the device to be used
591 * later in the device probing.
592 * Returns 0 if no settings found, 1 if they are.
594 int netdev_boot_setup_check(struct net_device *dev)
596 struct netdev_boot_setup *s = dev_boot_setup;
599 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
600 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
601 !strcmp(dev->name, s[i].name)) {
602 dev->irq = s[i].map.irq;
603 dev->base_addr = s[i].map.base_addr;
604 dev->mem_start = s[i].map.mem_start;
605 dev->mem_end = s[i].map.mem_end;
611 EXPORT_SYMBOL(netdev_boot_setup_check);
615 * netdev_boot_base - get address from boot time settings
616 * @prefix: prefix for network device
617 * @unit: id for network device
619 * Check boot time settings for the base address of device.
620 * The found settings are set for the device to be used
621 * later in the device probing.
622 * Returns 0 if no settings found.
624 unsigned long netdev_boot_base(const char *prefix, int unit)
626 const struct netdev_boot_setup *s = dev_boot_setup;
630 sprintf(name, "%s%d", prefix, unit);
633 * If device already registered then return base of 1
634 * to indicate not to probe for this interface
636 if (__dev_get_by_name(&init_net, name))
639 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
640 if (!strcmp(name, s[i].name))
641 return s[i].map.base_addr;
646 * Saves at boot time configured settings for any netdevice.
648 int __init netdev_boot_setup(char *str)
653 str = get_options(str, ARRAY_SIZE(ints), ints);
658 memset(&map, 0, sizeof(map));
662 map.base_addr = ints[2];
664 map.mem_start = ints[3];
666 map.mem_end = ints[4];
668 /* Add new entry to the list */
669 return netdev_boot_setup_add(str, &map);
672 __setup("netdev=", netdev_boot_setup);
674 /*******************************************************************************
676 * Device Interface Subroutines
678 *******************************************************************************/
681 * dev_get_iflink - get 'iflink' value of a interface
682 * @dev: targeted interface
684 * Indicates the ifindex the interface is linked to.
685 * Physical interfaces have the same 'ifindex' and 'iflink' values.
688 int dev_get_iflink(const struct net_device *dev)
690 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
691 return dev->netdev_ops->ndo_get_iflink(dev);
695 EXPORT_SYMBOL(dev_get_iflink);
698 * dev_fill_metadata_dst - Retrieve tunnel egress information.
699 * @dev: targeted interface
702 * For better visibility of tunnel traffic OVS needs to retrieve
703 * egress tunnel information for a packet. Following API allows
704 * user to get this info.
706 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
708 struct ip_tunnel_info *info;
710 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
713 info = skb_tunnel_info_unclone(skb);
716 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
719 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
721 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
724 * __dev_get_by_name - find a device by its name
725 * @net: the applicable net namespace
726 * @name: name to find
728 * Find an interface by name. Must be called under RTNL semaphore
729 * or @dev_base_lock. If the name is found a pointer to the device
730 * is returned. If the name is not found then %NULL is returned. The
731 * reference counters are not incremented so the caller must be
732 * careful with locks.
735 struct net_device *__dev_get_by_name(struct net *net, const char *name)
737 struct net_device *dev;
738 struct hlist_head *head = dev_name_hash(net, name);
740 hlist_for_each_entry(dev, head, name_hlist)
741 if (!strncmp(dev->name, name, IFNAMSIZ))
746 EXPORT_SYMBOL(__dev_get_by_name);
749 * dev_get_by_name_rcu - find a device by its name
750 * @net: the applicable net namespace
751 * @name: name to find
753 * Find an interface by name.
754 * If the name is found a pointer to the device is returned.
755 * If the name is not found then %NULL is returned.
756 * The reference counters are not incremented so the caller must be
757 * careful with locks. The caller must hold RCU lock.
760 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
762 struct net_device *dev;
763 struct hlist_head *head = dev_name_hash(net, name);
765 hlist_for_each_entry_rcu(dev, head, name_hlist)
766 if (!strncmp(dev->name, name, IFNAMSIZ))
771 EXPORT_SYMBOL(dev_get_by_name_rcu);
774 * dev_get_by_name - find a device by its name
775 * @net: the applicable net namespace
776 * @name: name to find
778 * Find an interface by name. This can be called from any
779 * context and does its own locking. The returned handle has
780 * the usage count incremented and the caller must use dev_put() to
781 * release it when it is no longer needed. %NULL is returned if no
782 * matching device is found.
785 struct net_device *dev_get_by_name(struct net *net, const char *name)
787 struct net_device *dev;
790 dev = dev_get_by_name_rcu(net, name);
796 EXPORT_SYMBOL(dev_get_by_name);
799 * __dev_get_by_index - find a device by its ifindex
800 * @net: the applicable net namespace
801 * @ifindex: index of device
803 * Search for an interface by index. Returns %NULL if the device
804 * is not found or a pointer to the device. The device has not
805 * had its reference counter increased so the caller must be careful
806 * about locking. The caller must hold either the RTNL semaphore
810 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
812 struct net_device *dev;
813 struct hlist_head *head = dev_index_hash(net, ifindex);
815 hlist_for_each_entry(dev, head, index_hlist)
816 if (dev->ifindex == ifindex)
821 EXPORT_SYMBOL(__dev_get_by_index);
824 * dev_get_by_index_rcu - find a device by its ifindex
825 * @net: the applicable net namespace
826 * @ifindex: index of device
828 * Search for an interface by index. Returns %NULL if the device
829 * is not found or a pointer to the device. The device has not
830 * had its reference counter increased so the caller must be careful
831 * about locking. The caller must hold RCU lock.
834 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
836 struct net_device *dev;
837 struct hlist_head *head = dev_index_hash(net, ifindex);
839 hlist_for_each_entry_rcu(dev, head, index_hlist)
840 if (dev->ifindex == ifindex)
845 EXPORT_SYMBOL(dev_get_by_index_rcu);
849 * dev_get_by_index - find a device by its ifindex
850 * @net: the applicable net namespace
851 * @ifindex: index of device
853 * Search for an interface by index. Returns NULL if the device
854 * is not found or a pointer to the device. The device returned has
855 * had a reference added and the pointer is safe until the user calls
856 * dev_put to indicate they have finished with it.
859 struct net_device *dev_get_by_index(struct net *net, int ifindex)
861 struct net_device *dev;
864 dev = dev_get_by_index_rcu(net, ifindex);
870 EXPORT_SYMBOL(dev_get_by_index);
873 * dev_get_by_napi_id - find a device by napi_id
874 * @napi_id: ID of the NAPI struct
876 * Search for an interface by NAPI ID. Returns %NULL if the device
877 * is not found or a pointer to the device. The device has not had
878 * its reference counter increased so the caller must be careful
879 * about locking. The caller must hold RCU lock.
882 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
884 struct napi_struct *napi;
886 WARN_ON_ONCE(!rcu_read_lock_held());
888 if (napi_id < MIN_NAPI_ID)
891 napi = napi_by_id(napi_id);
893 return napi ? napi->dev : NULL;
895 EXPORT_SYMBOL(dev_get_by_napi_id);
898 * netdev_get_name - get a netdevice name, knowing its ifindex.
899 * @net: network namespace
900 * @name: a pointer to the buffer where the name will be stored.
901 * @ifindex: the ifindex of the interface to get the name from.
903 * The use of raw_seqcount_begin() and cond_resched() before
904 * retrying is required as we want to give the writers a chance
905 * to complete when CONFIG_PREEMPT is not set.
907 int netdev_get_name(struct net *net, char *name, int ifindex)
909 struct net_device *dev;
913 seq = raw_seqcount_begin(&devnet_rename_seq);
915 dev = dev_get_by_index_rcu(net, ifindex);
921 strcpy(name, dev->name);
923 if (read_seqcount_retry(&devnet_rename_seq, seq)) {
932 * dev_getbyhwaddr_rcu - find a device by its hardware address
933 * @net: the applicable net namespace
934 * @type: media type of device
935 * @ha: hardware address
937 * Search for an interface by MAC address. Returns NULL if the device
938 * is not found or a pointer to the device.
939 * The caller must hold RCU or RTNL.
940 * The returned device has not had its ref count increased
941 * and the caller must therefore be careful about locking
945 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
948 struct net_device *dev;
950 for_each_netdev_rcu(net, dev)
951 if (dev->type == type &&
952 !memcmp(dev->dev_addr, ha, dev->addr_len))
957 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
959 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
961 struct net_device *dev;
964 for_each_netdev(net, dev)
965 if (dev->type == type)
970 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
972 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
974 struct net_device *dev, *ret = NULL;
977 for_each_netdev_rcu(net, dev)
978 if (dev->type == type) {
986 EXPORT_SYMBOL(dev_getfirstbyhwtype);
989 * __dev_get_by_flags - find any device with given flags
990 * @net: the applicable net namespace
991 * @if_flags: IFF_* values
992 * @mask: bitmask of bits in if_flags to check
994 * Search for any interface with the given flags. Returns NULL if a device
995 * is not found or a pointer to the device. Must be called inside
996 * rtnl_lock(), and result refcount is unchanged.
999 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1000 unsigned short mask)
1002 struct net_device *dev, *ret;
1007 for_each_netdev(net, dev) {
1008 if (((dev->flags ^ if_flags) & mask) == 0) {
1015 EXPORT_SYMBOL(__dev_get_by_flags);
1018 * dev_valid_name - check if name is okay for network device
1019 * @name: name string
1021 * Network device names need to be valid file names to
1022 * to allow sysfs to work. We also disallow any kind of
1025 bool dev_valid_name(const char *name)
1029 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1031 if (!strcmp(name, ".") || !strcmp(name, ".."))
1035 if (*name == '/' || *name == ':' || isspace(*name))
1041 EXPORT_SYMBOL(dev_valid_name);
1044 * __dev_alloc_name - allocate a name for a device
1045 * @net: network namespace to allocate the device name in
1046 * @name: name format string
1047 * @buf: scratch buffer and result name string
1049 * Passed a format string - eg "lt%d" it will try and find a suitable
1050 * id. It scans list of devices to build up a free map, then chooses
1051 * the first empty slot. The caller must hold the dev_base or rtnl lock
1052 * while allocating the name and adding the device in order to avoid
1054 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1055 * Returns the number of the unit assigned or a negative errno code.
1058 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1062 const int max_netdevices = 8*PAGE_SIZE;
1063 unsigned long *inuse;
1064 struct net_device *d;
1066 if (!dev_valid_name(name))
1069 p = strchr(name, '%');
1072 * Verify the string as this thing may have come from
1073 * the user. There must be either one "%d" and no other "%"
1076 if (p[1] != 'd' || strchr(p + 2, '%'))
1079 /* Use one page as a bit array of possible slots */
1080 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1084 for_each_netdev(net, d) {
1085 if (!sscanf(d->name, name, &i))
1087 if (i < 0 || i >= max_netdevices)
1090 /* avoid cases where sscanf is not exact inverse of printf */
1091 snprintf(buf, IFNAMSIZ, name, i);
1092 if (!strncmp(buf, d->name, IFNAMSIZ))
1096 i = find_first_zero_bit(inuse, max_netdevices);
1097 free_page((unsigned long) inuse);
1100 snprintf(buf, IFNAMSIZ, name, i);
1101 if (!__dev_get_by_name(net, buf))
1104 /* It is possible to run out of possible slots
1105 * when the name is long and there isn't enough space left
1106 * for the digits, or if all bits are used.
1111 static int dev_alloc_name_ns(struct net *net,
1112 struct net_device *dev,
1119 ret = __dev_alloc_name(net, name, buf);
1121 strlcpy(dev->name, buf, IFNAMSIZ);
1126 * dev_alloc_name - allocate a name for a device
1128 * @name: name format string
1130 * Passed a format string - eg "lt%d" it will try and find a suitable
1131 * id. It scans list of devices to build up a free map, then chooses
1132 * the first empty slot. The caller must hold the dev_base or rtnl lock
1133 * while allocating the name and adding the device in order to avoid
1135 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1136 * Returns the number of the unit assigned or a negative errno code.
1139 int dev_alloc_name(struct net_device *dev, const char *name)
1141 return dev_alloc_name_ns(dev_net(dev), dev, name);
1143 EXPORT_SYMBOL(dev_alloc_name);
1145 int dev_get_valid_name(struct net *net, struct net_device *dev,
1150 if (!dev_valid_name(name))
1153 if (strchr(name, '%'))
1154 return dev_alloc_name_ns(net, dev, name);
1155 else if (__dev_get_by_name(net, name))
1157 else if (dev->name != name)
1158 strlcpy(dev->name, name, IFNAMSIZ);
1162 EXPORT_SYMBOL(dev_get_valid_name);
1165 * dev_change_name - change name of a device
1167 * @newname: name (or format string) must be at least IFNAMSIZ
1169 * Change name of a device, can pass format strings "eth%d".
1172 int dev_change_name(struct net_device *dev, const char *newname)
1174 unsigned char old_assign_type;
1175 char oldname[IFNAMSIZ];
1181 BUG_ON(!dev_net(dev));
1185 /* Some auto-enslaved devices e.g. failover slaves are
1186 * special, as userspace might rename the device after
1187 * the interface had been brought up and running since
1188 * the point kernel initiated auto-enslavement. Allow
1189 * live name change even when these slave devices are
1192 * Typically, users of these auto-enslaving devices
1193 * don't actually care about slave name change, as
1194 * they are supposed to operate on master interface
1197 if (dev->flags & IFF_UP &&
1198 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1201 write_seqcount_begin(&devnet_rename_seq);
1203 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1204 write_seqcount_end(&devnet_rename_seq);
1208 memcpy(oldname, dev->name, IFNAMSIZ);
1210 err = dev_get_valid_name(net, dev, newname);
1212 write_seqcount_end(&devnet_rename_seq);
1216 if (oldname[0] && !strchr(oldname, '%'))
1217 netdev_info(dev, "renamed from %s\n", oldname);
1219 old_assign_type = dev->name_assign_type;
1220 dev->name_assign_type = NET_NAME_RENAMED;
1223 ret = device_rename(&dev->dev, dev->name);
1225 memcpy(dev->name, oldname, IFNAMSIZ);
1226 dev->name_assign_type = old_assign_type;
1227 write_seqcount_end(&devnet_rename_seq);
1231 write_seqcount_end(&devnet_rename_seq);
1233 netdev_adjacent_rename_links(dev, oldname);
1235 write_lock_bh(&dev_base_lock);
1236 hlist_del_rcu(&dev->name_hlist);
1237 write_unlock_bh(&dev_base_lock);
1241 write_lock_bh(&dev_base_lock);
1242 hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
1243 write_unlock_bh(&dev_base_lock);
1245 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1246 ret = notifier_to_errno(ret);
1249 /* err >= 0 after dev_alloc_name() or stores the first errno */
1252 write_seqcount_begin(&devnet_rename_seq);
1253 memcpy(dev->name, oldname, IFNAMSIZ);
1254 memcpy(oldname, newname, IFNAMSIZ);
1255 dev->name_assign_type = old_assign_type;
1256 old_assign_type = NET_NAME_RENAMED;
1259 pr_err("%s: name change rollback failed: %d\n",
1268 * dev_set_alias - change ifalias of a device
1270 * @alias: name up to IFALIASZ
1271 * @len: limit of bytes to copy from info
1273 * Set ifalias for a device,
1275 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1277 struct dev_ifalias *new_alias = NULL;
1279 if (len >= IFALIASZ)
1283 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1287 memcpy(new_alias->ifalias, alias, len);
1288 new_alias->ifalias[len] = 0;
1291 mutex_lock(&ifalias_mutex);
1292 rcu_swap_protected(dev->ifalias, new_alias,
1293 mutex_is_locked(&ifalias_mutex));
1294 mutex_unlock(&ifalias_mutex);
1297 kfree_rcu(new_alias, rcuhead);
1301 EXPORT_SYMBOL(dev_set_alias);
1304 * dev_get_alias - get ifalias of a device
1306 * @name: buffer to store name of ifalias
1307 * @len: size of buffer
1309 * get ifalias for a device. Caller must make sure dev cannot go
1310 * away, e.g. rcu read lock or own a reference count to device.
1312 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1314 const struct dev_ifalias *alias;
1318 alias = rcu_dereference(dev->ifalias);
1320 ret = snprintf(name, len, "%s", alias->ifalias);
1327 * netdev_features_change - device changes features
1328 * @dev: device to cause notification
1330 * Called to indicate a device has changed features.
1332 void netdev_features_change(struct net_device *dev)
1334 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1336 EXPORT_SYMBOL(netdev_features_change);
1339 * netdev_state_change - device changes state
1340 * @dev: device to cause notification
1342 * Called to indicate a device has changed state. This function calls
1343 * the notifier chains for netdev_chain and sends a NEWLINK message
1344 * to the routing socket.
1346 void netdev_state_change(struct net_device *dev)
1348 if (dev->flags & IFF_UP) {
1349 struct netdev_notifier_change_info change_info = {
1353 call_netdevice_notifiers_info(NETDEV_CHANGE,
1355 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1358 EXPORT_SYMBOL(netdev_state_change);
1361 * netdev_notify_peers - notify network peers about existence of @dev
1362 * @dev: network device
1364 * Generate traffic such that interested network peers are aware of
1365 * @dev, such as by generating a gratuitous ARP. This may be used when
1366 * a device wants to inform the rest of the network about some sort of
1367 * reconfiguration such as a failover event or virtual machine
1370 void netdev_notify_peers(struct net_device *dev)
1373 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1374 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1377 EXPORT_SYMBOL(netdev_notify_peers);
1379 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1381 const struct net_device_ops *ops = dev->netdev_ops;
1386 if (!netif_device_present(dev))
1389 /* Block netpoll from trying to do any rx path servicing.
1390 * If we don't do this there is a chance ndo_poll_controller
1391 * or ndo_poll may be running while we open the device
1393 netpoll_poll_disable(dev);
1395 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1396 ret = notifier_to_errno(ret);
1400 set_bit(__LINK_STATE_START, &dev->state);
1402 if (ops->ndo_validate_addr)
1403 ret = ops->ndo_validate_addr(dev);
1405 if (!ret && ops->ndo_open)
1406 ret = ops->ndo_open(dev);
1408 netpoll_poll_enable(dev);
1411 clear_bit(__LINK_STATE_START, &dev->state);
1413 dev->flags |= IFF_UP;
1414 dev_set_rx_mode(dev);
1416 add_device_randomness(dev->dev_addr, dev->addr_len);
1423 * dev_open - prepare an interface for use.
1424 * @dev: device to open
1425 * @extack: netlink extended ack
1427 * Takes a device from down to up state. The device's private open
1428 * function is invoked and then the multicast lists are loaded. Finally
1429 * the device is moved into the up state and a %NETDEV_UP message is
1430 * sent to the netdev notifier chain.
1432 * Calling this function on an active interface is a nop. On a failure
1433 * a negative errno code is returned.
1435 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1439 if (dev->flags & IFF_UP)
1442 ret = __dev_open(dev, extack);
1446 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1447 call_netdevice_notifiers(NETDEV_UP, dev);
1451 EXPORT_SYMBOL(dev_open);
1453 static void __dev_close_many(struct list_head *head)
1455 struct net_device *dev;
1460 list_for_each_entry(dev, head, close_list) {
1461 /* Temporarily disable netpoll until the interface is down */
1462 netpoll_poll_disable(dev);
1464 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1466 clear_bit(__LINK_STATE_START, &dev->state);
1468 /* Synchronize to scheduled poll. We cannot touch poll list, it
1469 * can be even on different cpu. So just clear netif_running().
1471 * dev->stop() will invoke napi_disable() on all of it's
1472 * napi_struct instances on this device.
1474 smp_mb__after_atomic(); /* Commit netif_running(). */
1477 dev_deactivate_many(head);
1479 list_for_each_entry(dev, head, close_list) {
1480 const struct net_device_ops *ops = dev->netdev_ops;
1483 * Call the device specific close. This cannot fail.
1484 * Only if device is UP
1486 * We allow it to be called even after a DETACH hot-plug
1492 dev->flags &= ~IFF_UP;
1493 netpoll_poll_enable(dev);
1497 static void __dev_close(struct net_device *dev)
1501 list_add(&dev->close_list, &single);
1502 __dev_close_many(&single);
1506 void dev_close_many(struct list_head *head, bool unlink)
1508 struct net_device *dev, *tmp;
1510 /* Remove the devices that don't need to be closed */
1511 list_for_each_entry_safe(dev, tmp, head, close_list)
1512 if (!(dev->flags & IFF_UP))
1513 list_del_init(&dev->close_list);
1515 __dev_close_many(head);
1517 list_for_each_entry_safe(dev, tmp, head, close_list) {
1518 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1519 call_netdevice_notifiers(NETDEV_DOWN, dev);
1521 list_del_init(&dev->close_list);
1524 EXPORT_SYMBOL(dev_close_many);
1527 * dev_close - shutdown an interface.
1528 * @dev: device to shutdown
1530 * This function moves an active device into down state. A
1531 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1532 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1535 void dev_close(struct net_device *dev)
1537 if (dev->flags & IFF_UP) {
1540 list_add(&dev->close_list, &single);
1541 dev_close_many(&single, true);
1545 EXPORT_SYMBOL(dev_close);
1549 * dev_disable_lro - disable Large Receive Offload on a device
1552 * Disable Large Receive Offload (LRO) on a net device. Must be
1553 * called under RTNL. This is needed if received packets may be
1554 * forwarded to another interface.
1556 void dev_disable_lro(struct net_device *dev)
1558 struct net_device *lower_dev;
1559 struct list_head *iter;
1561 dev->wanted_features &= ~NETIF_F_LRO;
1562 netdev_update_features(dev);
1564 if (unlikely(dev->features & NETIF_F_LRO))
1565 netdev_WARN(dev, "failed to disable LRO!\n");
1567 netdev_for_each_lower_dev(dev, lower_dev, iter)
1568 dev_disable_lro(lower_dev);
1570 EXPORT_SYMBOL(dev_disable_lro);
1573 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1576 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1577 * called under RTNL. This is needed if Generic XDP is installed on
1580 static void dev_disable_gro_hw(struct net_device *dev)
1582 dev->wanted_features &= ~NETIF_F_GRO_HW;
1583 netdev_update_features(dev);
1585 if (unlikely(dev->features & NETIF_F_GRO_HW))
1586 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1589 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1592 case NETDEV_##val: \
1593 return "NETDEV_" __stringify(val);
1595 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1596 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1597 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1598 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1599 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1600 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1601 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1602 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1603 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1607 return "UNKNOWN_NETDEV_EVENT";
1609 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1611 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1612 struct net_device *dev)
1614 struct netdev_notifier_info info = {
1618 return nb->notifier_call(nb, val, &info);
1621 static int dev_boot_phase = 1;
1624 * register_netdevice_notifier - register a network notifier block
1627 * Register a notifier to be called when network device events occur.
1628 * The notifier passed is linked into the kernel structures and must
1629 * not be reused until it has been unregistered. A negative errno code
1630 * is returned on a failure.
1632 * When registered all registration and up events are replayed
1633 * to the new notifier to allow device to have a race free
1634 * view of the network device list.
1637 int register_netdevice_notifier(struct notifier_block *nb)
1639 struct net_device *dev;
1640 struct net_device *last;
1644 /* Close race with setup_net() and cleanup_net() */
1645 down_write(&pernet_ops_rwsem);
1647 err = raw_notifier_chain_register(&netdev_chain, nb);
1653 for_each_netdev(net, dev) {
1654 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1655 err = notifier_to_errno(err);
1659 if (!(dev->flags & IFF_UP))
1662 call_netdevice_notifier(nb, NETDEV_UP, dev);
1668 up_write(&pernet_ops_rwsem);
1674 for_each_netdev(net, dev) {
1678 if (dev->flags & IFF_UP) {
1679 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1681 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1683 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1688 raw_notifier_chain_unregister(&netdev_chain, nb);
1691 EXPORT_SYMBOL(register_netdevice_notifier);
1694 * unregister_netdevice_notifier - unregister a network notifier block
1697 * Unregister a notifier previously registered by
1698 * register_netdevice_notifier(). The notifier is unlinked into the
1699 * kernel structures and may then be reused. A negative errno code
1700 * is returned on a failure.
1702 * After unregistering unregister and down device events are synthesized
1703 * for all devices on the device list to the removed notifier to remove
1704 * the need for special case cleanup code.
1707 int unregister_netdevice_notifier(struct notifier_block *nb)
1709 struct net_device *dev;
1713 /* Close race with setup_net() and cleanup_net() */
1714 down_write(&pernet_ops_rwsem);
1716 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1721 for_each_netdev(net, dev) {
1722 if (dev->flags & IFF_UP) {
1723 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1725 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1727 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1732 up_write(&pernet_ops_rwsem);
1735 EXPORT_SYMBOL(unregister_netdevice_notifier);
1738 * call_netdevice_notifiers_info - call all network notifier blocks
1739 * @val: value passed unmodified to notifier function
1740 * @info: notifier information data
1742 * Call all network notifier blocks. Parameters and return value
1743 * are as for raw_notifier_call_chain().
1746 static int call_netdevice_notifiers_info(unsigned long val,
1747 struct netdev_notifier_info *info)
1750 return raw_notifier_call_chain(&netdev_chain, val, info);
1753 static int call_netdevice_notifiers_extack(unsigned long val,
1754 struct net_device *dev,
1755 struct netlink_ext_ack *extack)
1757 struct netdev_notifier_info info = {
1762 return call_netdevice_notifiers_info(val, &info);
1766 * call_netdevice_notifiers - call all network notifier blocks
1767 * @val: value passed unmodified to notifier function
1768 * @dev: net_device pointer passed unmodified to notifier function
1770 * Call all network notifier blocks. Parameters and return value
1771 * are as for raw_notifier_call_chain().
1774 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
1776 return call_netdevice_notifiers_extack(val, dev, NULL);
1778 EXPORT_SYMBOL(call_netdevice_notifiers);
1781 * call_netdevice_notifiers_mtu - call all network notifier blocks
1782 * @val: value passed unmodified to notifier function
1783 * @dev: net_device pointer passed unmodified to notifier function
1784 * @arg: additional u32 argument passed to the notifier function
1786 * Call all network notifier blocks. Parameters and return value
1787 * are as for raw_notifier_call_chain().
1789 static int call_netdevice_notifiers_mtu(unsigned long val,
1790 struct net_device *dev, u32 arg)
1792 struct netdev_notifier_info_ext info = {
1797 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
1799 return call_netdevice_notifiers_info(val, &info.info);
1802 #ifdef CONFIG_NET_INGRESS
1803 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
1805 void net_inc_ingress_queue(void)
1807 static_branch_inc(&ingress_needed_key);
1809 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
1811 void net_dec_ingress_queue(void)
1813 static_branch_dec(&ingress_needed_key);
1815 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
1818 #ifdef CONFIG_NET_EGRESS
1819 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
1821 void net_inc_egress_queue(void)
1823 static_branch_inc(&egress_needed_key);
1825 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
1827 void net_dec_egress_queue(void)
1829 static_branch_dec(&egress_needed_key);
1831 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
1834 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
1835 #ifdef CONFIG_JUMP_LABEL
1836 static atomic_t netstamp_needed_deferred;
1837 static atomic_t netstamp_wanted;
1838 static void netstamp_clear(struct work_struct *work)
1840 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
1843 wanted = atomic_add_return(deferred, &netstamp_wanted);
1845 static_branch_enable(&netstamp_needed_key);
1847 static_branch_disable(&netstamp_needed_key);
1849 static DECLARE_WORK(netstamp_work, netstamp_clear);
1852 void net_enable_timestamp(void)
1854 #ifdef CONFIG_JUMP_LABEL
1858 wanted = atomic_read(&netstamp_wanted);
1861 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
1864 atomic_inc(&netstamp_needed_deferred);
1865 schedule_work(&netstamp_work);
1867 static_branch_inc(&netstamp_needed_key);
1870 EXPORT_SYMBOL(net_enable_timestamp);
1872 void net_disable_timestamp(void)
1874 #ifdef CONFIG_JUMP_LABEL
1878 wanted = atomic_read(&netstamp_wanted);
1881 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
1884 atomic_dec(&netstamp_needed_deferred);
1885 schedule_work(&netstamp_work);
1887 static_branch_dec(&netstamp_needed_key);
1890 EXPORT_SYMBOL(net_disable_timestamp);
1892 static inline void net_timestamp_set(struct sk_buff *skb)
1895 if (static_branch_unlikely(&netstamp_needed_key))
1896 __net_timestamp(skb);
1899 #define net_timestamp_check(COND, SKB) \
1900 if (static_branch_unlikely(&netstamp_needed_key)) { \
1901 if ((COND) && !(SKB)->tstamp) \
1902 __net_timestamp(SKB); \
1905 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
1909 if (!(dev->flags & IFF_UP))
1912 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
1913 if (skb->len <= len)
1916 /* if TSO is enabled, we don't care about the length as the packet
1917 * could be forwarded without being segmented before
1919 if (skb_is_gso(skb))
1924 EXPORT_SYMBOL_GPL(is_skb_forwardable);
1926 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1928 int ret = ____dev_forward_skb(dev, skb);
1931 skb->protocol = eth_type_trans(skb, dev);
1932 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
1937 EXPORT_SYMBOL_GPL(__dev_forward_skb);
1940 * dev_forward_skb - loopback an skb to another netif
1942 * @dev: destination network device
1943 * @skb: buffer to forward
1946 * NET_RX_SUCCESS (no congestion)
1947 * NET_RX_DROP (packet was dropped, but freed)
1949 * dev_forward_skb can be used for injecting an skb from the
1950 * start_xmit function of one device into the receive queue
1951 * of another device.
1953 * The receiving device may be in another namespace, so
1954 * we have to clear all information in the skb that could
1955 * impact namespace isolation.
1957 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
1959 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
1961 EXPORT_SYMBOL_GPL(dev_forward_skb);
1963 static inline int deliver_skb(struct sk_buff *skb,
1964 struct packet_type *pt_prev,
1965 struct net_device *orig_dev)
1967 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
1969 refcount_inc(&skb->users);
1970 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
1973 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
1974 struct packet_type **pt,
1975 struct net_device *orig_dev,
1977 struct list_head *ptype_list)
1979 struct packet_type *ptype, *pt_prev = *pt;
1981 list_for_each_entry_rcu(ptype, ptype_list, list) {
1982 if (ptype->type != type)
1985 deliver_skb(skb, pt_prev, orig_dev);
1991 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
1993 if (!ptype->af_packet_priv || !skb->sk)
1996 if (ptype->id_match)
1997 return ptype->id_match(ptype, skb->sk);
1998 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2005 * dev_nit_active - return true if any network interface taps are in use
2007 * @dev: network device to check for the presence of taps
2009 bool dev_nit_active(struct net_device *dev)
2011 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2013 EXPORT_SYMBOL_GPL(dev_nit_active);
2016 * Support routine. Sends outgoing frames to any network
2017 * taps currently in use.
2020 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2022 struct packet_type *ptype;
2023 struct sk_buff *skb2 = NULL;
2024 struct packet_type *pt_prev = NULL;
2025 struct list_head *ptype_list = &ptype_all;
2029 list_for_each_entry_rcu(ptype, ptype_list, list) {
2030 if (ptype->ignore_outgoing)
2033 /* Never send packets back to the socket
2034 * they originated from - MvS (miquels@drinkel.ow.org)
2036 if (skb_loop_sk(ptype, skb))
2040 deliver_skb(skb2, pt_prev, skb->dev);
2045 /* need to clone skb, done only once */
2046 skb2 = skb_clone(skb, GFP_ATOMIC);
2050 net_timestamp_set(skb2);
2052 /* skb->nh should be correctly
2053 * set by sender, so that the second statement is
2054 * just protection against buggy protocols.
2056 skb_reset_mac_header(skb2);
2058 if (skb_network_header(skb2) < skb2->data ||
2059 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2060 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2061 ntohs(skb2->protocol),
2063 skb_reset_network_header(skb2);
2066 skb2->transport_header = skb2->network_header;
2067 skb2->pkt_type = PACKET_OUTGOING;
2071 if (ptype_list == &ptype_all) {
2072 ptype_list = &dev->ptype_all;
2077 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2078 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2084 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2087 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2088 * @dev: Network device
2089 * @txq: number of queues available
2091 * If real_num_tx_queues is changed the tc mappings may no longer be
2092 * valid. To resolve this verify the tc mapping remains valid and if
2093 * not NULL the mapping. With no priorities mapping to this
2094 * offset/count pair it will no longer be used. In the worst case TC0
2095 * is invalid nothing can be done so disable priority mappings. If is
2096 * expected that drivers will fix this mapping if they can before
2097 * calling netif_set_real_num_tx_queues.
2099 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2102 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2104 /* If TC0 is invalidated disable TC mapping */
2105 if (tc->offset + tc->count > txq) {
2106 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2111 /* Invalidated prio to tc mappings set to TC0 */
2112 for (i = 1; i < TC_BITMASK + 1; i++) {
2113 int q = netdev_get_prio_tc_map(dev, i);
2115 tc = &dev->tc_to_txq[q];
2116 if (tc->offset + tc->count > txq) {
2117 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2119 netdev_set_prio_tc_map(dev, i, 0);
2124 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2127 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2130 /* walk through the TCs and see if it falls into any of them */
2131 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2132 if ((txq - tc->offset) < tc->count)
2136 /* didn't find it, just return -1 to indicate no match */
2142 EXPORT_SYMBOL(netdev_txq_to_tc);
2145 struct static_key xps_needed __read_mostly;
2146 EXPORT_SYMBOL(xps_needed);
2147 struct static_key xps_rxqs_needed __read_mostly;
2148 EXPORT_SYMBOL(xps_rxqs_needed);
2149 static DEFINE_MUTEX(xps_map_mutex);
2150 #define xmap_dereference(P) \
2151 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2153 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2156 struct xps_map *map = NULL;
2160 map = xmap_dereference(dev_maps->attr_map[tci]);
2164 for (pos = map->len; pos--;) {
2165 if (map->queues[pos] != index)
2169 map->queues[pos] = map->queues[--map->len];
2173 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2174 kfree_rcu(map, rcu);
2181 static bool remove_xps_queue_cpu(struct net_device *dev,
2182 struct xps_dev_maps *dev_maps,
2183 int cpu, u16 offset, u16 count)
2185 int num_tc = dev->num_tc ? : 1;
2186 bool active = false;
2189 for (tci = cpu * num_tc; num_tc--; tci++) {
2192 for (i = count, j = offset; i--; j++) {
2193 if (!remove_xps_queue(dev_maps, tci, j))
2203 static void reset_xps_maps(struct net_device *dev,
2204 struct xps_dev_maps *dev_maps,
2208 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2209 RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2211 RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2213 static_key_slow_dec_cpuslocked(&xps_needed);
2214 kfree_rcu(dev_maps, rcu);
2217 static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2218 struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2219 u16 offset, u16 count, bool is_rxqs_map)
2221 bool active = false;
2224 for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2226 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2229 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2232 for (i = offset + (count - 1); count--; i--) {
2233 netdev_queue_numa_node_write(
2234 netdev_get_tx_queue(dev, i),
2240 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2243 const unsigned long *possible_mask = NULL;
2244 struct xps_dev_maps *dev_maps;
2245 unsigned int nr_ids;
2247 if (!static_key_false(&xps_needed))
2251 mutex_lock(&xps_map_mutex);
2253 if (static_key_false(&xps_rxqs_needed)) {
2254 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2256 nr_ids = dev->num_rx_queues;
2257 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2258 offset, count, true);
2262 dev_maps = xmap_dereference(dev->xps_cpus_map);
2266 if (num_possible_cpus() > 1)
2267 possible_mask = cpumask_bits(cpu_possible_mask);
2268 nr_ids = nr_cpu_ids;
2269 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2273 mutex_unlock(&xps_map_mutex);
2277 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2279 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2282 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2283 u16 index, bool is_rxqs_map)
2285 struct xps_map *new_map;
2286 int alloc_len = XPS_MIN_MAP_ALLOC;
2289 for (pos = 0; map && pos < map->len; pos++) {
2290 if (map->queues[pos] != index)
2295 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2297 if (pos < map->alloc_len)
2300 alloc_len = map->alloc_len * 2;
2303 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2307 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2309 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2310 cpu_to_node(attr_index));
2314 for (i = 0; i < pos; i++)
2315 new_map->queues[i] = map->queues[i];
2316 new_map->alloc_len = alloc_len;
2322 /* Must be called under cpus_read_lock */
2323 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2324 u16 index, bool is_rxqs_map)
2326 const unsigned long *online_mask = NULL, *possible_mask = NULL;
2327 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2328 int i, j, tci, numa_node_id = -2;
2329 int maps_sz, num_tc = 1, tc = 0;
2330 struct xps_map *map, *new_map;
2331 bool active = false;
2332 unsigned int nr_ids;
2335 /* Do not allow XPS on subordinate device directly */
2336 num_tc = dev->num_tc;
2340 /* If queue belongs to subordinate dev use its map */
2341 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2343 tc = netdev_txq_to_tc(dev, index);
2348 mutex_lock(&xps_map_mutex);
2350 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2351 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2352 nr_ids = dev->num_rx_queues;
2354 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2355 if (num_possible_cpus() > 1) {
2356 online_mask = cpumask_bits(cpu_online_mask);
2357 possible_mask = cpumask_bits(cpu_possible_mask);
2359 dev_maps = xmap_dereference(dev->xps_cpus_map);
2360 nr_ids = nr_cpu_ids;
2363 if (maps_sz < L1_CACHE_BYTES)
2364 maps_sz = L1_CACHE_BYTES;
2366 /* allocate memory for queue storage */
2367 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2370 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2371 if (!new_dev_maps) {
2372 mutex_unlock(&xps_map_mutex);
2376 tci = j * num_tc + tc;
2377 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2380 map = expand_xps_map(map, j, index, is_rxqs_map);
2384 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2388 goto out_no_new_maps;
2391 /* Increment static keys at most once per type */
2392 static_key_slow_inc_cpuslocked(&xps_needed);
2394 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2397 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2399 /* copy maps belonging to foreign traffic classes */
2400 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2401 /* fill in the new device map from the old device map */
2402 map = xmap_dereference(dev_maps->attr_map[tci]);
2403 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2406 /* We need to explicitly update tci as prevous loop
2407 * could break out early if dev_maps is NULL.
2409 tci = j * num_tc + tc;
2411 if (netif_attr_test_mask(j, mask, nr_ids) &&
2412 netif_attr_test_online(j, online_mask, nr_ids)) {
2413 /* add tx-queue to CPU/rx-queue maps */
2416 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2417 while ((pos < map->len) && (map->queues[pos] != index))
2420 if (pos == map->len)
2421 map->queues[map->len++] = index;
2424 if (numa_node_id == -2)
2425 numa_node_id = cpu_to_node(j);
2426 else if (numa_node_id != cpu_to_node(j))
2430 } else if (dev_maps) {
2431 /* fill in the new device map from the old device map */
2432 map = xmap_dereference(dev_maps->attr_map[tci]);
2433 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2436 /* copy maps belonging to foreign traffic classes */
2437 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2438 /* fill in the new device map from the old device map */
2439 map = xmap_dereference(dev_maps->attr_map[tci]);
2440 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2445 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2447 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2449 /* Cleanup old maps */
2451 goto out_no_old_maps;
2453 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2455 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2456 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2457 map = xmap_dereference(dev_maps->attr_map[tci]);
2458 if (map && map != new_map)
2459 kfree_rcu(map, rcu);
2463 kfree_rcu(dev_maps, rcu);
2466 dev_maps = new_dev_maps;
2471 /* update Tx queue numa node */
2472 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2473 (numa_node_id >= 0) ?
2474 numa_node_id : NUMA_NO_NODE);
2480 /* removes tx-queue from unused CPUs/rx-queues */
2481 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2483 for (i = tc, tci = j * num_tc; i--; tci++)
2484 active |= remove_xps_queue(dev_maps, tci, index);
2485 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2486 !netif_attr_test_online(j, online_mask, nr_ids))
2487 active |= remove_xps_queue(dev_maps, tci, index);
2488 for (i = num_tc - tc, tci++; --i; tci++)
2489 active |= remove_xps_queue(dev_maps, tci, index);
2492 /* free map if not active */
2494 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2497 mutex_unlock(&xps_map_mutex);
2501 /* remove any maps that we added */
2502 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2504 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2505 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2507 xmap_dereference(dev_maps->attr_map[tci]) :
2509 if (new_map && new_map != map)
2514 mutex_unlock(&xps_map_mutex);
2516 kfree(new_dev_maps);
2519 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2521 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2527 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2532 EXPORT_SYMBOL(netif_set_xps_queue);
2535 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2537 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2539 /* Unbind any subordinate channels */
2540 while (txq-- != &dev->_tx[0]) {
2542 netdev_unbind_sb_channel(dev, txq->sb_dev);
2546 void netdev_reset_tc(struct net_device *dev)
2549 netif_reset_xps_queues_gt(dev, 0);
2551 netdev_unbind_all_sb_channels(dev);
2553 /* Reset TC configuration of device */
2555 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2556 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2558 EXPORT_SYMBOL(netdev_reset_tc);
2560 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2562 if (tc >= dev->num_tc)
2566 netif_reset_xps_queues(dev, offset, count);
2568 dev->tc_to_txq[tc].count = count;
2569 dev->tc_to_txq[tc].offset = offset;
2572 EXPORT_SYMBOL(netdev_set_tc_queue);
2574 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2576 if (num_tc > TC_MAX_QUEUE)
2580 netif_reset_xps_queues_gt(dev, 0);
2582 netdev_unbind_all_sb_channels(dev);
2584 dev->num_tc = num_tc;
2587 EXPORT_SYMBOL(netdev_set_num_tc);
2589 void netdev_unbind_sb_channel(struct net_device *dev,
2590 struct net_device *sb_dev)
2592 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2595 netif_reset_xps_queues_gt(sb_dev, 0);
2597 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2598 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2600 while (txq-- != &dev->_tx[0]) {
2601 if (txq->sb_dev == sb_dev)
2605 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2607 int netdev_bind_sb_channel_queue(struct net_device *dev,
2608 struct net_device *sb_dev,
2609 u8 tc, u16 count, u16 offset)
2611 /* Make certain the sb_dev and dev are already configured */
2612 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2615 /* We cannot hand out queues we don't have */
2616 if ((offset + count) > dev->real_num_tx_queues)
2619 /* Record the mapping */
2620 sb_dev->tc_to_txq[tc].count = count;
2621 sb_dev->tc_to_txq[tc].offset = offset;
2623 /* Provide a way for Tx queue to find the tc_to_txq map or
2624 * XPS map for itself.
2627 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2631 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2633 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2635 /* Do not use a multiqueue device to represent a subordinate channel */
2636 if (netif_is_multiqueue(dev))
2639 /* We allow channels 1 - 32767 to be used for subordinate channels.
2640 * Channel 0 is meant to be "native" mode and used only to represent
2641 * the main root device. We allow writing 0 to reset the device back
2642 * to normal mode after being used as a subordinate channel.
2644 if (channel > S16_MAX)
2647 dev->num_tc = -channel;
2651 EXPORT_SYMBOL(netdev_set_sb_channel);
2654 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2655 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2657 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2662 disabling = txq < dev->real_num_tx_queues;
2664 if (txq < 1 || txq > dev->num_tx_queues)
2667 if (dev->reg_state == NETREG_REGISTERED ||
2668 dev->reg_state == NETREG_UNREGISTERING) {
2671 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2677 netif_setup_tc(dev, txq);
2679 dev->real_num_tx_queues = txq;
2683 qdisc_reset_all_tx_gt(dev, txq);
2685 netif_reset_xps_queues_gt(dev, txq);
2689 dev->real_num_tx_queues = txq;
2694 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2698 * netif_set_real_num_rx_queues - set actual number of RX queues used
2699 * @dev: Network device
2700 * @rxq: Actual number of RX queues
2702 * This must be called either with the rtnl_lock held or before
2703 * registration of the net device. Returns 0 on success, or a
2704 * negative error code. If called before registration, it always
2707 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2711 if (rxq < 1 || rxq > dev->num_rx_queues)
2714 if (dev->reg_state == NETREG_REGISTERED) {
2717 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2723 dev->real_num_rx_queues = rxq;
2726 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2730 * netif_get_num_default_rss_queues - default number of RSS queues
2732 * This routine should set an upper limit on the number of RSS queues
2733 * used by default by multiqueue devices.
2735 int netif_get_num_default_rss_queues(void)
2737 return is_kdump_kernel() ?
2738 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2740 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2742 static void __netif_reschedule(struct Qdisc *q)
2744 struct softnet_data *sd;
2745 unsigned long flags;
2747 local_irq_save(flags);
2748 sd = this_cpu_ptr(&softnet_data);
2749 q->next_sched = NULL;
2750 *sd->output_queue_tailp = q;
2751 sd->output_queue_tailp = &q->next_sched;
2752 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2753 local_irq_restore(flags);
2756 void __netif_schedule(struct Qdisc *q)
2758 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2759 __netif_reschedule(q);
2761 EXPORT_SYMBOL(__netif_schedule);
2763 struct dev_kfree_skb_cb {
2764 enum skb_free_reason reason;
2767 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
2769 return (struct dev_kfree_skb_cb *)skb->cb;
2772 void netif_schedule_queue(struct netdev_queue *txq)
2775 if (!(txq->state & QUEUE_STATE_ANY_XOFF)) {
2776 struct Qdisc *q = rcu_dereference(txq->qdisc);
2778 __netif_schedule(q);
2782 EXPORT_SYMBOL(netif_schedule_queue);
2784 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
2786 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
2790 q = rcu_dereference(dev_queue->qdisc);
2791 __netif_schedule(q);
2795 EXPORT_SYMBOL(netif_tx_wake_queue);
2797 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
2799 unsigned long flags;
2804 if (likely(refcount_read(&skb->users) == 1)) {
2806 refcount_set(&skb->users, 0);
2807 } else if (likely(!refcount_dec_and_test(&skb->users))) {
2810 get_kfree_skb_cb(skb)->reason = reason;
2811 local_irq_save(flags);
2812 skb->next = __this_cpu_read(softnet_data.completion_queue);
2813 __this_cpu_write(softnet_data.completion_queue, skb);
2814 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2815 local_irq_restore(flags);
2817 EXPORT_SYMBOL(__dev_kfree_skb_irq);
2819 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
2821 if (in_irq() || irqs_disabled())
2822 __dev_kfree_skb_irq(skb, reason);
2826 EXPORT_SYMBOL(__dev_kfree_skb_any);
2830 * netif_device_detach - mark device as removed
2831 * @dev: network device
2833 * Mark device as removed from system and therefore no longer available.
2835 void netif_device_detach(struct net_device *dev)
2837 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
2838 netif_running(dev)) {
2839 netif_tx_stop_all_queues(dev);
2842 EXPORT_SYMBOL(netif_device_detach);
2845 * netif_device_attach - mark device as attached
2846 * @dev: network device
2848 * Mark device as attached from system and restart if needed.
2850 void netif_device_attach(struct net_device *dev)
2852 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
2853 netif_running(dev)) {
2854 netif_tx_wake_all_queues(dev);
2855 __netdev_watchdog_up(dev);
2858 EXPORT_SYMBOL(netif_device_attach);
2861 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
2862 * to be used as a distribution range.
2864 static u16 skb_tx_hash(const struct net_device *dev,
2865 const struct net_device *sb_dev,
2866 struct sk_buff *skb)
2870 u16 qcount = dev->real_num_tx_queues;
2873 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
2875 qoffset = sb_dev->tc_to_txq[tc].offset;
2876 qcount = sb_dev->tc_to_txq[tc].count;
2879 if (skb_rx_queue_recorded(skb)) {
2880 hash = skb_get_rx_queue(skb);
2881 while (unlikely(hash >= qcount))
2883 return hash + qoffset;
2886 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
2889 static void skb_warn_bad_offload(const struct sk_buff *skb)
2891 static const netdev_features_t null_features;
2892 struct net_device *dev = skb->dev;
2893 const char *name = "";
2895 if (!net_ratelimit())
2899 if (dev->dev.parent)
2900 name = dev_driver_string(dev->dev.parent);
2902 name = netdev_name(dev);
2904 skb_dump(KERN_WARNING, skb, false);
2905 WARN(1, "%s: caps=(%pNF, %pNF)\n",
2906 name, dev ? &dev->features : &null_features,
2907 skb->sk ? &skb->sk->sk_route_caps : &null_features);
2911 * Invalidate hardware checksum when packet is to be mangled, and
2912 * complete checksum manually on outgoing path.
2914 int skb_checksum_help(struct sk_buff *skb)
2917 int ret = 0, offset;
2919 if (skb->ip_summed == CHECKSUM_COMPLETE)
2920 goto out_set_summed;
2922 if (unlikely(skb_shinfo(skb)->gso_size)) {
2923 skb_warn_bad_offload(skb);
2927 /* Before computing a checksum, we should make sure no frag could
2928 * be modified by an external entity : checksum could be wrong.
2930 if (skb_has_shared_frag(skb)) {
2931 ret = __skb_linearize(skb);
2936 offset = skb_checksum_start_offset(skb);
2937 BUG_ON(offset >= skb_headlen(skb));
2938 csum = skb_checksum(skb, offset, skb->len - offset, 0);
2940 offset += skb->csum_offset;
2941 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
2943 if (skb_cloned(skb) &&
2944 !skb_clone_writable(skb, offset + sizeof(__sum16))) {
2945 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2950 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
2952 skb->ip_summed = CHECKSUM_NONE;
2956 EXPORT_SYMBOL(skb_checksum_help);
2958 int skb_crc32c_csum_help(struct sk_buff *skb)
2961 int ret = 0, offset, start;
2963 if (skb->ip_summed != CHECKSUM_PARTIAL)
2966 if (unlikely(skb_is_gso(skb)))
2969 /* Before computing a checksum, we should make sure no frag could
2970 * be modified by an external entity : checksum could be wrong.
2972 if (unlikely(skb_has_shared_frag(skb))) {
2973 ret = __skb_linearize(skb);
2977 start = skb_checksum_start_offset(skb);
2978 offset = start + offsetof(struct sctphdr, checksum);
2979 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
2983 if (skb_cloned(skb) &&
2984 !skb_clone_writable(skb, offset + sizeof(__le32))) {
2985 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2989 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
2990 skb->len - start, ~(__u32)0,
2992 *(__le32 *)(skb->data + offset) = crc32c_csum;
2993 skb->ip_summed = CHECKSUM_NONE;
2994 skb->csum_not_inet = 0;
2999 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3001 __be16 type = skb->protocol;
3003 /* Tunnel gso handlers can set protocol to ethernet. */
3004 if (type == htons(ETH_P_TEB)) {
3007 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3010 eth = (struct ethhdr *)skb->data;
3011 type = eth->h_proto;
3014 return __vlan_get_protocol(skb, type, depth);
3018 * skb_mac_gso_segment - mac layer segmentation handler.
3019 * @skb: buffer to segment
3020 * @features: features for the output path (see dev->features)
3022 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3023 netdev_features_t features)
3025 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3026 struct packet_offload *ptype;
3027 int vlan_depth = skb->mac_len;
3028 __be16 type = skb_network_protocol(skb, &vlan_depth);
3030 if (unlikely(!type))
3031 return ERR_PTR(-EINVAL);
3033 __skb_pull(skb, vlan_depth);
3036 list_for_each_entry_rcu(ptype, &offload_base, list) {
3037 if (ptype->type == type && ptype->callbacks.gso_segment) {
3038 segs = ptype->callbacks.gso_segment(skb, features);
3044 __skb_push(skb, skb->data - skb_mac_header(skb));
3048 EXPORT_SYMBOL(skb_mac_gso_segment);
3051 /* openvswitch calls this on rx path, so we need a different check.
3053 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3056 return skb->ip_summed != CHECKSUM_PARTIAL &&
3057 skb->ip_summed != CHECKSUM_UNNECESSARY;
3059 return skb->ip_summed == CHECKSUM_NONE;
3063 * __skb_gso_segment - Perform segmentation on skb.
3064 * @skb: buffer to segment
3065 * @features: features for the output path (see dev->features)
3066 * @tx_path: whether it is called in TX path
3068 * This function segments the given skb and returns a list of segments.
3070 * It may return NULL if the skb requires no segmentation. This is
3071 * only possible when GSO is used for verifying header integrity.
3073 * Segmentation preserves SKB_SGO_CB_OFFSET bytes of previous skb cb.
3075 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3076 netdev_features_t features, bool tx_path)
3078 struct sk_buff *segs;
3080 if (unlikely(skb_needs_check(skb, tx_path))) {
3083 /* We're going to init ->check field in TCP or UDP header */
3084 err = skb_cow_head(skb, 0);
3086 return ERR_PTR(err);
3089 /* Only report GSO partial support if it will enable us to
3090 * support segmentation on this frame without needing additional
3093 if (features & NETIF_F_GSO_PARTIAL) {
3094 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3095 struct net_device *dev = skb->dev;
3097 partial_features |= dev->features & dev->gso_partial_features;
3098 if (!skb_gso_ok(skb, features | partial_features))
3099 features &= ~NETIF_F_GSO_PARTIAL;
3102 BUILD_BUG_ON(SKB_SGO_CB_OFFSET +
3103 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3105 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3106 SKB_GSO_CB(skb)->encap_level = 0;
3108 skb_reset_mac_header(skb);
3109 skb_reset_mac_len(skb);
3111 segs = skb_mac_gso_segment(skb, features);
3113 if (unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3114 skb_warn_bad_offload(skb);
3118 EXPORT_SYMBOL(__skb_gso_segment);
3120 /* Take action when hardware reception checksum errors are detected. */
3122 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3124 if (net_ratelimit()) {
3125 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3126 skb_dump(KERN_ERR, skb, true);
3130 EXPORT_SYMBOL(netdev_rx_csum_fault);
3133 /* XXX: check that highmem exists at all on the given machine. */
3134 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3136 #ifdef CONFIG_HIGHMEM
3139 if (!(dev->features & NETIF_F_HIGHDMA)) {
3140 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3141 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3143 if (PageHighMem(skb_frag_page(frag)))
3151 /* If MPLS offload request, verify we are testing hardware MPLS features
3152 * instead of standard features for the netdev.
3154 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3155 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3156 netdev_features_t features,
3159 if (eth_p_mpls(type))
3160 features &= skb->dev->mpls_features;
3165 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3166 netdev_features_t features,
3173 static netdev_features_t harmonize_features(struct sk_buff *skb,
3174 netdev_features_t features)
3179 type = skb_network_protocol(skb, &tmp);
3180 features = net_mpls_features(skb, features, type);
3182 if (skb->ip_summed != CHECKSUM_NONE &&
3183 !can_checksum_protocol(features, type)) {
3184 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3186 if (illegal_highdma(skb->dev, skb))
3187 features &= ~NETIF_F_SG;
3192 netdev_features_t passthru_features_check(struct sk_buff *skb,
3193 struct net_device *dev,
3194 netdev_features_t features)
3198 EXPORT_SYMBOL(passthru_features_check);
3200 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3201 struct net_device *dev,
3202 netdev_features_t features)
3204 return vlan_features_check(skb, features);
3207 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3208 struct net_device *dev,
3209 netdev_features_t features)
3211 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3213 if (gso_segs > dev->gso_max_segs)
3214 return features & ~NETIF_F_GSO_MASK;
3216 /* Support for GSO partial features requires software
3217 * intervention before we can actually process the packets
3218 * so we need to strip support for any partial features now
3219 * and we can pull them back in after we have partially
3220 * segmented the frame.
3222 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3223 features &= ~dev->gso_partial_features;
3225 /* Make sure to clear the IPv4 ID mangling feature if the
3226 * IPv4 header has the potential to be fragmented.
3228 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3229 struct iphdr *iph = skb->encapsulation ?
3230 inner_ip_hdr(skb) : ip_hdr(skb);
3232 if (!(iph->frag_off & htons(IP_DF)))
3233 features &= ~NETIF_F_TSO_MANGLEID;
3239 netdev_features_t netif_skb_features(struct sk_buff *skb)
3241 struct net_device *dev = skb->dev;
3242 netdev_features_t features = dev->features;
3244 if (skb_is_gso(skb))
3245 features = gso_features_check(skb, dev, features);
3247 /* If encapsulation offload request, verify we are testing
3248 * hardware encapsulation features instead of standard
3249 * features for the netdev
3251 if (skb->encapsulation)
3252 features &= dev->hw_enc_features;
3254 if (skb_vlan_tagged(skb))
3255 features = netdev_intersect_features(features,
3256 dev->vlan_features |
3257 NETIF_F_HW_VLAN_CTAG_TX |
3258 NETIF_F_HW_VLAN_STAG_TX);
3260 if (dev->netdev_ops->ndo_features_check)
3261 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3264 features &= dflt_features_check(skb, dev, features);
3266 return harmonize_features(skb, features);
3268 EXPORT_SYMBOL(netif_skb_features);
3270 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3271 struct netdev_queue *txq, bool more)
3276 if (dev_nit_active(dev))
3277 dev_queue_xmit_nit(skb, dev);
3280 trace_net_dev_start_xmit(skb, dev);
3281 rc = netdev_start_xmit(skb, dev, txq, more);
3282 trace_net_dev_xmit(skb, rc, dev, len);
3287 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3288 struct netdev_queue *txq, int *ret)
3290 struct sk_buff *skb = first;
3291 int rc = NETDEV_TX_OK;
3294 struct sk_buff *next = skb->next;
3296 skb_mark_not_on_list(skb);
3297 rc = xmit_one(skb, dev, txq, next != NULL);
3298 if (unlikely(!dev_xmit_complete(rc))) {
3304 if (netif_tx_queue_stopped(txq) && skb) {
3305 rc = NETDEV_TX_BUSY;
3315 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3316 netdev_features_t features)
3318 if (skb_vlan_tag_present(skb) &&
3319 !vlan_hw_offload_capable(features, skb->vlan_proto))
3320 skb = __vlan_hwaccel_push_inside(skb);
3324 int skb_csum_hwoffload_help(struct sk_buff *skb,
3325 const netdev_features_t features)
3327 if (unlikely(skb->csum_not_inet))
3328 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3329 skb_crc32c_csum_help(skb);
3331 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3333 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3335 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3337 netdev_features_t features;
3339 features = netif_skb_features(skb);
3340 skb = validate_xmit_vlan(skb, features);
3344 skb = sk_validate_xmit_skb(skb, dev);
3348 if (netif_needs_gso(skb, features)) {
3349 struct sk_buff *segs;
3351 segs = skb_gso_segment(skb, features);
3359 if (skb_needs_linearize(skb, features) &&
3360 __skb_linearize(skb))
3363 /* If packet is not checksummed and device does not
3364 * support checksumming for this protocol, complete
3365 * checksumming here.
3367 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3368 if (skb->encapsulation)
3369 skb_set_inner_transport_header(skb,
3370 skb_checksum_start_offset(skb));
3372 skb_set_transport_header(skb,
3373 skb_checksum_start_offset(skb));
3374 if (skb_csum_hwoffload_help(skb, features))
3379 skb = validate_xmit_xfrm(skb, features, again);
3386 atomic_long_inc(&dev->tx_dropped);
3390 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3392 struct sk_buff *next, *head = NULL, *tail;
3394 for (; skb != NULL; skb = next) {
3396 skb_mark_not_on_list(skb);
3398 /* in case skb wont be segmented, point to itself */
3401 skb = validate_xmit_skb(skb, dev, again);
3409 /* If skb was segmented, skb->prev points to
3410 * the last segment. If not, it still contains skb.
3416 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3418 static void qdisc_pkt_len_init(struct sk_buff *skb)
3420 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3422 qdisc_skb_cb(skb)->pkt_len = skb->len;
3424 /* To get more precise estimation of bytes sent on wire,
3425 * we add to pkt_len the headers size of all segments
3427 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3428 unsigned int hdr_len;
3429 u16 gso_segs = shinfo->gso_segs;
3431 /* mac layer + network layer */
3432 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3434 /* + transport layer */
3435 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3436 const struct tcphdr *th;
3437 struct tcphdr _tcphdr;
3439 th = skb_header_pointer(skb, skb_transport_offset(skb),
3440 sizeof(_tcphdr), &_tcphdr);
3442 hdr_len += __tcp_hdrlen(th);
3444 struct udphdr _udphdr;
3446 if (skb_header_pointer(skb, skb_transport_offset(skb),
3447 sizeof(_udphdr), &_udphdr))
3448 hdr_len += sizeof(struct udphdr);
3451 if (shinfo->gso_type & SKB_GSO_DODGY)
3452 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3455 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3459 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3460 struct net_device *dev,
3461 struct netdev_queue *txq)
3463 spinlock_t *root_lock = qdisc_lock(q);
3464 struct sk_buff *to_free = NULL;
3468 qdisc_calculate_pkt_len(skb, q);
3470 if (q->flags & TCQ_F_NOLOCK) {
3471 if ((q->flags & TCQ_F_CAN_BYPASS) && q->empty &&
3472 qdisc_run_begin(q)) {
3473 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
3475 __qdisc_drop(skb, &to_free);
3479 qdisc_bstats_cpu_update(q, skb);
3481 rc = NET_XMIT_SUCCESS;
3482 if (sch_direct_xmit(skb, q, dev, txq, NULL, true))
3488 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3492 if (unlikely(to_free))
3493 kfree_skb_list(to_free);
3498 * Heuristic to force contended enqueues to serialize on a
3499 * separate lock before trying to get qdisc main lock.
3500 * This permits qdisc->running owner to get the lock more
3501 * often and dequeue packets faster.
3503 contended = qdisc_is_running(q);
3504 if (unlikely(contended))
3505 spin_lock(&q->busylock);
3507 spin_lock(root_lock);
3508 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3509 __qdisc_drop(skb, &to_free);
3511 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3512 qdisc_run_begin(q)) {
3514 * This is a work-conserving queue; there are no old skbs
3515 * waiting to be sent out; and the qdisc is not running -
3516 * xmit the skb directly.
3519 qdisc_bstats_update(q, skb);
3521 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3522 if (unlikely(contended)) {
3523 spin_unlock(&q->busylock);
3530 rc = NET_XMIT_SUCCESS;
3532 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3533 if (qdisc_run_begin(q)) {
3534 if (unlikely(contended)) {
3535 spin_unlock(&q->busylock);
3542 spin_unlock(root_lock);
3543 if (unlikely(to_free))
3544 kfree_skb_list(to_free);
3545 if (unlikely(contended))
3546 spin_unlock(&q->busylock);
3550 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3551 static void skb_update_prio(struct sk_buff *skb)
3553 const struct netprio_map *map;
3554 const struct sock *sk;
3555 unsigned int prioidx;
3559 map = rcu_dereference_bh(skb->dev->priomap);
3562 sk = skb_to_full_sk(skb);
3566 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3568 if (prioidx < map->priomap_len)
3569 skb->priority = map->priomap[prioidx];
3572 #define skb_update_prio(skb)
3576 * dev_loopback_xmit - loop back @skb
3577 * @net: network namespace this loopback is happening in
3578 * @sk: sk needed to be a netfilter okfn
3579 * @skb: buffer to transmit
3581 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3583 skb_reset_mac_header(skb);
3584 __skb_pull(skb, skb_network_offset(skb));
3585 skb->pkt_type = PACKET_LOOPBACK;
3586 skb->ip_summed = CHECKSUM_UNNECESSARY;
3587 WARN_ON(!skb_dst(skb));
3592 EXPORT_SYMBOL(dev_loopback_xmit);
3594 #ifdef CONFIG_NET_EGRESS
3595 static struct sk_buff *
3596 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3598 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3599 struct tcf_result cl_res;
3604 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3605 mini_qdisc_bstats_cpu_update(miniq, skb);
3607 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3609 case TC_ACT_RECLASSIFY:
3610 skb->tc_index = TC_H_MIN(cl_res.classid);
3613 mini_qdisc_qstats_cpu_drop(miniq);
3614 *ret = NET_XMIT_DROP;
3620 *ret = NET_XMIT_SUCCESS;
3623 case TC_ACT_REDIRECT:
3624 /* No need to push/pop skb's mac_header here on egress! */
3625 skb_do_redirect(skb);
3626 *ret = NET_XMIT_SUCCESS;
3634 #endif /* CONFIG_NET_EGRESS */
3637 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3638 struct xps_dev_maps *dev_maps, unsigned int tci)
3640 struct xps_map *map;
3641 int queue_index = -1;
3645 tci += netdev_get_prio_tc_map(dev, skb->priority);
3648 map = rcu_dereference(dev_maps->attr_map[tci]);
3651 queue_index = map->queues[0];
3653 queue_index = map->queues[reciprocal_scale(
3654 skb_get_hash(skb), map->len)];
3655 if (unlikely(queue_index >= dev->real_num_tx_queues))
3662 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3663 struct sk_buff *skb)
3666 struct xps_dev_maps *dev_maps;
3667 struct sock *sk = skb->sk;
3668 int queue_index = -1;
3670 if (!static_key_false(&xps_needed))
3674 if (!static_key_false(&xps_rxqs_needed))
3677 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3679 int tci = sk_rx_queue_get(sk);
3681 if (tci >= 0 && tci < dev->num_rx_queues)
3682 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3687 if (queue_index < 0) {
3688 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3690 unsigned int tci = skb->sender_cpu - 1;
3692 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3704 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3705 struct net_device *sb_dev)
3709 EXPORT_SYMBOL(dev_pick_tx_zero);
3711 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3712 struct net_device *sb_dev)
3714 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
3716 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
3718 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
3719 struct net_device *sb_dev)
3721 struct sock *sk = skb->sk;
3722 int queue_index = sk_tx_queue_get(sk);
3724 sb_dev = sb_dev ? : dev;
3726 if (queue_index < 0 || skb->ooo_okay ||
3727 queue_index >= dev->real_num_tx_queues) {
3728 int new_index = get_xps_queue(dev, sb_dev, skb);
3731 new_index = skb_tx_hash(dev, sb_dev, skb);
3733 if (queue_index != new_index && sk &&
3735 rcu_access_pointer(sk->sk_dst_cache))
3736 sk_tx_queue_set(sk, new_index);
3738 queue_index = new_index;
3743 EXPORT_SYMBOL(netdev_pick_tx);
3745 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
3746 struct sk_buff *skb,
3747 struct net_device *sb_dev)
3749 int queue_index = 0;
3752 u32 sender_cpu = skb->sender_cpu - 1;
3754 if (sender_cpu >= (u32)NR_CPUS)
3755 skb->sender_cpu = raw_smp_processor_id() + 1;
3758 if (dev->real_num_tx_queues != 1) {
3759 const struct net_device_ops *ops = dev->netdev_ops;
3761 if (ops->ndo_select_queue)
3762 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
3764 queue_index = netdev_pick_tx(dev, skb, sb_dev);
3766 queue_index = netdev_cap_txqueue(dev, queue_index);
3769 skb_set_queue_mapping(skb, queue_index);
3770 return netdev_get_tx_queue(dev, queue_index);
3774 * __dev_queue_xmit - transmit a buffer
3775 * @skb: buffer to transmit
3776 * @sb_dev: suboordinate device used for L2 forwarding offload
3778 * Queue a buffer for transmission to a network device. The caller must
3779 * have set the device and priority and built the buffer before calling
3780 * this function. The function can be called from an interrupt.
3782 * A negative errno code is returned on a failure. A success does not
3783 * guarantee the frame will be transmitted as it may be dropped due
3784 * to congestion or traffic shaping.
3786 * -----------------------------------------------------------------------------------
3787 * I notice this method can also return errors from the queue disciplines,
3788 * including NET_XMIT_DROP, which is a positive value. So, errors can also
3791 * Regardless of the return value, the skb is consumed, so it is currently
3792 * difficult to retry a send to this method. (You can bump the ref count
3793 * before sending to hold a reference for retry if you are careful.)
3795 * When calling this method, interrupts MUST be enabled. This is because
3796 * the BH enable code must have IRQs enabled so that it will not deadlock.
3799 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
3801 struct net_device *dev = skb->dev;
3802 struct netdev_queue *txq;
3807 skb_reset_mac_header(skb);
3809 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
3810 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
3812 /* Disable soft irqs for various locks below. Also
3813 * stops preemption for RCU.
3817 skb_update_prio(skb);
3819 qdisc_pkt_len_init(skb);
3820 #ifdef CONFIG_NET_CLS_ACT
3821 skb->tc_at_ingress = 0;
3822 # ifdef CONFIG_NET_EGRESS
3823 if (static_branch_unlikely(&egress_needed_key)) {
3824 skb = sch_handle_egress(skb, &rc, dev);
3830 /* If device/qdisc don't need skb->dst, release it right now while
3831 * its hot in this cpu cache.
3833 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
3838 txq = netdev_core_pick_tx(dev, skb, sb_dev);
3839 q = rcu_dereference_bh(txq->qdisc);
3841 trace_net_dev_queue(skb);
3843 rc = __dev_xmit_skb(skb, q, dev, txq);
3847 /* The device has no queue. Common case for software devices:
3848 * loopback, all the sorts of tunnels...
3850 * Really, it is unlikely that netif_tx_lock protection is necessary
3851 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
3853 * However, it is possible, that they rely on protection
3856 * Check this and shot the lock. It is not prone from deadlocks.
3857 *Either shot noqueue qdisc, it is even simpler 8)
3859 if (dev->flags & IFF_UP) {
3860 int cpu = smp_processor_id(); /* ok because BHs are off */
3862 if (txq->xmit_lock_owner != cpu) {
3863 if (dev_xmit_recursion())
3864 goto recursion_alert;
3866 skb = validate_xmit_skb(skb, dev, &again);
3870 HARD_TX_LOCK(dev, txq, cpu);
3872 if (!netif_xmit_stopped(txq)) {
3873 dev_xmit_recursion_inc();
3874 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
3875 dev_xmit_recursion_dec();
3876 if (dev_xmit_complete(rc)) {
3877 HARD_TX_UNLOCK(dev, txq);
3881 HARD_TX_UNLOCK(dev, txq);
3882 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
3885 /* Recursion is detected! It is possible,
3889 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
3895 rcu_read_unlock_bh();
3897 atomic_long_inc(&dev->tx_dropped);
3898 kfree_skb_list(skb);
3901 rcu_read_unlock_bh();
3905 int dev_queue_xmit(struct sk_buff *skb)
3907 return __dev_queue_xmit(skb, NULL);
3909 EXPORT_SYMBOL(dev_queue_xmit);
3911 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
3913 return __dev_queue_xmit(skb, sb_dev);
3915 EXPORT_SYMBOL(dev_queue_xmit_accel);
3917 int dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
3919 struct net_device *dev = skb->dev;
3920 struct sk_buff *orig_skb = skb;
3921 struct netdev_queue *txq;
3922 int ret = NETDEV_TX_BUSY;
3925 if (unlikely(!netif_running(dev) ||
3926 !netif_carrier_ok(dev)))
3929 skb = validate_xmit_skb_list(skb, dev, &again);
3930 if (skb != orig_skb)
3933 skb_set_queue_mapping(skb, queue_id);
3934 txq = skb_get_tx_queue(dev, skb);
3938 HARD_TX_LOCK(dev, txq, smp_processor_id());
3939 if (!netif_xmit_frozen_or_drv_stopped(txq))
3940 ret = netdev_start_xmit(skb, dev, txq, false);
3941 HARD_TX_UNLOCK(dev, txq);
3945 if (!dev_xmit_complete(ret))
3950 atomic_long_inc(&dev->tx_dropped);
3951 kfree_skb_list(skb);
3952 return NET_XMIT_DROP;
3954 EXPORT_SYMBOL(dev_direct_xmit);
3956 /*************************************************************************
3958 *************************************************************************/
3960 int netdev_max_backlog __read_mostly = 1000;
3961 EXPORT_SYMBOL(netdev_max_backlog);
3963 int netdev_tstamp_prequeue __read_mostly = 1;
3964 int netdev_budget __read_mostly = 300;
3965 unsigned int __read_mostly netdev_budget_usecs = 2000;
3966 int weight_p __read_mostly = 64; /* old backlog weight */
3967 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
3968 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
3969 int dev_rx_weight __read_mostly = 64;
3970 int dev_tx_weight __read_mostly = 64;
3971 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
3972 int gro_normal_batch __read_mostly = 8;
3974 /* Called with irq disabled */
3975 static inline void ____napi_schedule(struct softnet_data *sd,
3976 struct napi_struct *napi)
3978 list_add_tail(&napi->poll_list, &sd->poll_list);
3979 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
3984 /* One global table that all flow-based protocols share. */
3985 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
3986 EXPORT_SYMBOL(rps_sock_flow_table);
3987 u32 rps_cpu_mask __read_mostly;
3988 EXPORT_SYMBOL(rps_cpu_mask);
3990 struct static_key_false rps_needed __read_mostly;
3991 EXPORT_SYMBOL(rps_needed);
3992 struct static_key_false rfs_needed __read_mostly;
3993 EXPORT_SYMBOL(rfs_needed);
3995 static struct rps_dev_flow *
3996 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
3997 struct rps_dev_flow *rflow, u16 next_cpu)
3999 if (next_cpu < nr_cpu_ids) {
4000 #ifdef CONFIG_RFS_ACCEL
4001 struct netdev_rx_queue *rxqueue;
4002 struct rps_dev_flow_table *flow_table;
4003 struct rps_dev_flow *old_rflow;
4008 /* Should we steer this flow to a different hardware queue? */
4009 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4010 !(dev->features & NETIF_F_NTUPLE))
4012 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4013 if (rxq_index == skb_get_rx_queue(skb))
4016 rxqueue = dev->_rx + rxq_index;
4017 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4020 flow_id = skb_get_hash(skb) & flow_table->mask;
4021 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4022 rxq_index, flow_id);
4026 rflow = &flow_table->flows[flow_id];
4028 if (old_rflow->filter == rflow->filter)
4029 old_rflow->filter = RPS_NO_FILTER;
4033 per_cpu(softnet_data, next_cpu).input_queue_head;
4036 rflow->cpu = next_cpu;
4041 * get_rps_cpu is called from netif_receive_skb and returns the target
4042 * CPU from the RPS map of the receiving queue for a given skb.
4043 * rcu_read_lock must be held on entry.
4045 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4046 struct rps_dev_flow **rflowp)
4048 const struct rps_sock_flow_table *sock_flow_table;
4049 struct netdev_rx_queue *rxqueue = dev->_rx;
4050 struct rps_dev_flow_table *flow_table;
4051 struct rps_map *map;
4056 if (skb_rx_queue_recorded(skb)) {
4057 u16 index = skb_get_rx_queue(skb);
4059 if (unlikely(index >= dev->real_num_rx_queues)) {
4060 WARN_ONCE(dev->real_num_rx_queues > 1,
4061 "%s received packet on queue %u, but number "
4062 "of RX queues is %u\n",
4063 dev->name, index, dev->real_num_rx_queues);
4069 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4071 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4072 map = rcu_dereference(rxqueue->rps_map);
4073 if (!flow_table && !map)
4076 skb_reset_network_header(skb);
4077 hash = skb_get_hash(skb);
4081 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4082 if (flow_table && sock_flow_table) {
4083 struct rps_dev_flow *rflow;
4087 /* First check into global flow table if there is a match */
4088 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4089 if ((ident ^ hash) & ~rps_cpu_mask)
4092 next_cpu = ident & rps_cpu_mask;
4094 /* OK, now we know there is a match,
4095 * we can look at the local (per receive queue) flow table
4097 rflow = &flow_table->flows[hash & flow_table->mask];
4101 * If the desired CPU (where last recvmsg was done) is
4102 * different from current CPU (one in the rx-queue flow
4103 * table entry), switch if one of the following holds:
4104 * - Current CPU is unset (>= nr_cpu_ids).
4105 * - Current CPU is offline.
4106 * - The current CPU's queue tail has advanced beyond the
4107 * last packet that was enqueued using this table entry.
4108 * This guarantees that all previous packets for the flow
4109 * have been dequeued, thus preserving in order delivery.
4111 if (unlikely(tcpu != next_cpu) &&
4112 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4113 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4114 rflow->last_qtail)) >= 0)) {
4116 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4119 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4129 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4130 if (cpu_online(tcpu)) {
4140 #ifdef CONFIG_RFS_ACCEL
4143 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4144 * @dev: Device on which the filter was set
4145 * @rxq_index: RX queue index
4146 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4147 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4149 * Drivers that implement ndo_rx_flow_steer() should periodically call
4150 * this function for each installed filter and remove the filters for
4151 * which it returns %true.
4153 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4154 u32 flow_id, u16 filter_id)
4156 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4157 struct rps_dev_flow_table *flow_table;
4158 struct rps_dev_flow *rflow;
4163 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4164 if (flow_table && flow_id <= flow_table->mask) {
4165 rflow = &flow_table->flows[flow_id];
4166 cpu = READ_ONCE(rflow->cpu);
4167 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4168 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4169 rflow->last_qtail) <
4170 (int)(10 * flow_table->mask)))
4176 EXPORT_SYMBOL(rps_may_expire_flow);
4178 #endif /* CONFIG_RFS_ACCEL */
4180 /* Called from hardirq (IPI) context */
4181 static void rps_trigger_softirq(void *data)
4183 struct softnet_data *sd = data;
4185 ____napi_schedule(sd, &sd->backlog);
4189 #endif /* CONFIG_RPS */
4192 * Check if this softnet_data structure is another cpu one
4193 * If yes, queue it to our IPI list and return 1
4196 static int rps_ipi_queued(struct softnet_data *sd)
4199 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4202 sd->rps_ipi_next = mysd->rps_ipi_list;
4203 mysd->rps_ipi_list = sd;
4205 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4208 #endif /* CONFIG_RPS */
4212 #ifdef CONFIG_NET_FLOW_LIMIT
4213 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4216 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4218 #ifdef CONFIG_NET_FLOW_LIMIT
4219 struct sd_flow_limit *fl;
4220 struct softnet_data *sd;
4221 unsigned int old_flow, new_flow;
4223 if (qlen < (netdev_max_backlog >> 1))
4226 sd = this_cpu_ptr(&softnet_data);
4229 fl = rcu_dereference(sd->flow_limit);
4231 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4232 old_flow = fl->history[fl->history_head];
4233 fl->history[fl->history_head] = new_flow;
4236 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4238 if (likely(fl->buckets[old_flow]))
4239 fl->buckets[old_flow]--;
4241 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4253 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4254 * queue (may be a remote CPU queue).
4256 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4257 unsigned int *qtail)
4259 struct softnet_data *sd;
4260 unsigned long flags;
4263 sd = &per_cpu(softnet_data, cpu);
4265 local_irq_save(flags);
4268 if (!netif_running(skb->dev))
4270 qlen = skb_queue_len(&sd->input_pkt_queue);
4271 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4274 __skb_queue_tail(&sd->input_pkt_queue, skb);
4275 input_queue_tail_incr_save(sd, qtail);
4277 local_irq_restore(flags);
4278 return NET_RX_SUCCESS;
4281 /* Schedule NAPI for backlog device
4282 * We can use non atomic operation since we own the queue lock
4284 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4285 if (!rps_ipi_queued(sd))
4286 ____napi_schedule(sd, &sd->backlog);
4295 local_irq_restore(flags);
4297 atomic_long_inc(&skb->dev->rx_dropped);
4302 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4304 struct net_device *dev = skb->dev;
4305 struct netdev_rx_queue *rxqueue;
4309 if (skb_rx_queue_recorded(skb)) {
4310 u16 index = skb_get_rx_queue(skb);
4312 if (unlikely(index >= dev->real_num_rx_queues)) {
4313 WARN_ONCE(dev->real_num_rx_queues > 1,
4314 "%s received packet on queue %u, but number "
4315 "of RX queues is %u\n",
4316 dev->name, index, dev->real_num_rx_queues);
4318 return rxqueue; /* Return first rxqueue */
4325 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4326 struct xdp_buff *xdp,
4327 struct bpf_prog *xdp_prog)
4329 struct netdev_rx_queue *rxqueue;
4330 void *orig_data, *orig_data_end;
4331 u32 metalen, act = XDP_DROP;
4332 __be16 orig_eth_type;
4338 /* Reinjected packets coming from act_mirred or similar should
4339 * not get XDP generic processing.
4341 if (skb_cloned(skb) || skb_is_tc_redirected(skb))
4344 /* XDP packets must be linear and must have sufficient headroom
4345 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4346 * native XDP provides, thus we need to do it here as well.
4348 if (skb_is_nonlinear(skb) ||
4349 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4350 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4351 int troom = skb->tail + skb->data_len - skb->end;
4353 /* In case we have to go down the path and also linearize,
4354 * then lets do the pskb_expand_head() work just once here.
4356 if (pskb_expand_head(skb,
4357 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4358 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4360 if (skb_linearize(skb))
4364 /* The XDP program wants to see the packet starting at the MAC
4367 mac_len = skb->data - skb_mac_header(skb);
4368 hlen = skb_headlen(skb) + mac_len;
4369 xdp->data = skb->data - mac_len;
4370 xdp->data_meta = xdp->data;
4371 xdp->data_end = xdp->data + hlen;
4372 xdp->data_hard_start = skb->data - skb_headroom(skb);
4373 orig_data_end = xdp->data_end;
4374 orig_data = xdp->data;
4375 eth = (struct ethhdr *)xdp->data;
4376 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4377 orig_eth_type = eth->h_proto;
4379 rxqueue = netif_get_rxqueue(skb);
4380 xdp->rxq = &rxqueue->xdp_rxq;
4382 act = bpf_prog_run_xdp(xdp_prog, xdp);
4384 /* check if bpf_xdp_adjust_head was used */
4385 off = xdp->data - orig_data;
4388 __skb_pull(skb, off);
4390 __skb_push(skb, -off);
4392 skb->mac_header += off;
4393 skb_reset_network_header(skb);
4396 /* check if bpf_xdp_adjust_tail was used. it can only "shrink"
4399 off = orig_data_end - xdp->data_end;
4401 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4406 /* check if XDP changed eth hdr such SKB needs update */
4407 eth = (struct ethhdr *)xdp->data;
4408 if ((orig_eth_type != eth->h_proto) ||
4409 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4410 __skb_push(skb, ETH_HLEN);
4411 skb->protocol = eth_type_trans(skb, skb->dev);
4417 __skb_push(skb, mac_len);
4420 metalen = xdp->data - xdp->data_meta;
4422 skb_metadata_set(skb, metalen);
4425 bpf_warn_invalid_xdp_action(act);
4428 trace_xdp_exception(skb->dev, xdp_prog, act);
4439 /* When doing generic XDP we have to bypass the qdisc layer and the
4440 * network taps in order to match in-driver-XDP behavior.
4442 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4444 struct net_device *dev = skb->dev;
4445 struct netdev_queue *txq;
4446 bool free_skb = true;
4449 txq = netdev_core_pick_tx(dev, skb, NULL);
4450 cpu = smp_processor_id();
4451 HARD_TX_LOCK(dev, txq, cpu);
4452 if (!netif_xmit_stopped(txq)) {
4453 rc = netdev_start_xmit(skb, dev, txq, 0);
4454 if (dev_xmit_complete(rc))
4457 HARD_TX_UNLOCK(dev, txq);
4459 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4463 EXPORT_SYMBOL_GPL(generic_xdp_tx);
4465 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4467 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4470 struct xdp_buff xdp;
4474 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4475 if (act != XDP_PASS) {
4478 err = xdp_do_generic_redirect(skb->dev, skb,
4484 generic_xdp_tx(skb, xdp_prog);
4495 EXPORT_SYMBOL_GPL(do_xdp_generic);
4497 static int netif_rx_internal(struct sk_buff *skb)
4501 net_timestamp_check(netdev_tstamp_prequeue, skb);
4503 trace_netif_rx(skb);
4506 if (static_branch_unlikely(&rps_needed)) {
4507 struct rps_dev_flow voidflow, *rflow = &voidflow;
4513 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4515 cpu = smp_processor_id();
4517 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4526 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4533 * netif_rx - post buffer to the network code
4534 * @skb: buffer to post
4536 * This function receives a packet from a device driver and queues it for
4537 * the upper (protocol) levels to process. It always succeeds. The buffer
4538 * may be dropped during processing for congestion control or by the
4542 * NET_RX_SUCCESS (no congestion)
4543 * NET_RX_DROP (packet was dropped)
4547 int netif_rx(struct sk_buff *skb)
4551 trace_netif_rx_entry(skb);
4553 ret = netif_rx_internal(skb);
4554 trace_netif_rx_exit(ret);
4558 EXPORT_SYMBOL(netif_rx);
4560 int netif_rx_ni(struct sk_buff *skb)
4564 trace_netif_rx_ni_entry(skb);
4567 err = netif_rx_internal(skb);
4568 if (local_softirq_pending())
4571 trace_netif_rx_ni_exit(err);
4575 EXPORT_SYMBOL(netif_rx_ni);
4577 static __latent_entropy void net_tx_action(struct softirq_action *h)
4579 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4581 if (sd->completion_queue) {
4582 struct sk_buff *clist;
4584 local_irq_disable();
4585 clist = sd->completion_queue;
4586 sd->completion_queue = NULL;
4590 struct sk_buff *skb = clist;
4592 clist = clist->next;
4594 WARN_ON(refcount_read(&skb->users));
4595 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4596 trace_consume_skb(skb);
4598 trace_kfree_skb(skb, net_tx_action);
4600 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4603 __kfree_skb_defer(skb);
4606 __kfree_skb_flush();
4609 if (sd->output_queue) {
4612 local_irq_disable();
4613 head = sd->output_queue;
4614 sd->output_queue = NULL;
4615 sd->output_queue_tailp = &sd->output_queue;
4619 struct Qdisc *q = head;
4620 spinlock_t *root_lock = NULL;
4622 head = head->next_sched;
4624 if (!(q->flags & TCQ_F_NOLOCK)) {
4625 root_lock = qdisc_lock(q);
4626 spin_lock(root_lock);
4628 /* We need to make sure head->next_sched is read
4629 * before clearing __QDISC_STATE_SCHED
4631 smp_mb__before_atomic();
4632 clear_bit(__QDISC_STATE_SCHED, &q->state);
4635 spin_unlock(root_lock);
4639 xfrm_dev_backlog(sd);
4642 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4643 /* This hook is defined here for ATM LANE */
4644 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4645 unsigned char *addr) __read_mostly;
4646 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4649 static inline struct sk_buff *
4650 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4651 struct net_device *orig_dev)
4653 #ifdef CONFIG_NET_CLS_ACT
4654 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4655 struct tcf_result cl_res;
4657 /* If there's at least one ingress present somewhere (so
4658 * we get here via enabled static key), remaining devices
4659 * that are not configured with an ingress qdisc will bail
4666 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4670 qdisc_skb_cb(skb)->pkt_len = skb->len;
4671 skb->tc_at_ingress = 1;
4672 mini_qdisc_bstats_cpu_update(miniq, skb);
4674 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
4676 case TC_ACT_RECLASSIFY:
4677 skb->tc_index = TC_H_MIN(cl_res.classid);
4680 mini_qdisc_qstats_cpu_drop(miniq);
4688 case TC_ACT_REDIRECT:
4689 /* skb_mac_header check was done by cls/act_bpf, so
4690 * we can safely push the L2 header back before
4691 * redirecting to another netdev
4693 __skb_push(skb, skb->mac_len);
4694 skb_do_redirect(skb);
4696 case TC_ACT_CONSUMED:
4701 #endif /* CONFIG_NET_CLS_ACT */
4706 * netdev_is_rx_handler_busy - check if receive handler is registered
4707 * @dev: device to check
4709 * Check if a receive handler is already registered for a given device.
4710 * Return true if there one.
4712 * The caller must hold the rtnl_mutex.
4714 bool netdev_is_rx_handler_busy(struct net_device *dev)
4717 return dev && rtnl_dereference(dev->rx_handler);
4719 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
4722 * netdev_rx_handler_register - register receive handler
4723 * @dev: device to register a handler for
4724 * @rx_handler: receive handler to register
4725 * @rx_handler_data: data pointer that is used by rx handler
4727 * Register a receive handler for a device. This handler will then be
4728 * called from __netif_receive_skb. A negative errno code is returned
4731 * The caller must hold the rtnl_mutex.
4733 * For a general description of rx_handler, see enum rx_handler_result.
4735 int netdev_rx_handler_register(struct net_device *dev,
4736 rx_handler_func_t *rx_handler,
4737 void *rx_handler_data)
4739 if (netdev_is_rx_handler_busy(dev))
4742 if (dev->priv_flags & IFF_NO_RX_HANDLER)
4745 /* Note: rx_handler_data must be set before rx_handler */
4746 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
4747 rcu_assign_pointer(dev->rx_handler, rx_handler);
4751 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
4754 * netdev_rx_handler_unregister - unregister receive handler
4755 * @dev: device to unregister a handler from
4757 * Unregister a receive handler from a device.
4759 * The caller must hold the rtnl_mutex.
4761 void netdev_rx_handler_unregister(struct net_device *dev)
4765 RCU_INIT_POINTER(dev->rx_handler, NULL);
4766 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
4767 * section has a guarantee to see a non NULL rx_handler_data
4771 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
4773 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
4776 * Limit the use of PFMEMALLOC reserves to those protocols that implement
4777 * the special handling of PFMEMALLOC skbs.
4779 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
4781 switch (skb->protocol) {
4782 case htons(ETH_P_ARP):
4783 case htons(ETH_P_IP):
4784 case htons(ETH_P_IPV6):
4785 case htons(ETH_P_8021Q):
4786 case htons(ETH_P_8021AD):
4793 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
4794 int *ret, struct net_device *orig_dev)
4796 #ifdef CONFIG_NETFILTER_INGRESS
4797 if (nf_hook_ingress_active(skb)) {
4801 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4806 ingress_retval = nf_hook_ingress(skb);
4808 return ingress_retval;
4810 #endif /* CONFIG_NETFILTER_INGRESS */
4814 static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc,
4815 struct packet_type **ppt_prev)
4817 struct packet_type *ptype, *pt_prev;
4818 rx_handler_func_t *rx_handler;
4819 struct net_device *orig_dev;
4820 bool deliver_exact = false;
4821 int ret = NET_RX_DROP;
4824 net_timestamp_check(!netdev_tstamp_prequeue, skb);
4826 trace_netif_receive_skb(skb);
4828 orig_dev = skb->dev;
4830 skb_reset_network_header(skb);
4831 if (!skb_transport_header_was_set(skb))
4832 skb_reset_transport_header(skb);
4833 skb_reset_mac_len(skb);
4838 skb->skb_iif = skb->dev->ifindex;
4840 __this_cpu_inc(softnet_data.processed);
4842 if (static_branch_unlikely(&generic_xdp_needed_key)) {
4846 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
4849 if (ret2 != XDP_PASS)
4851 skb_reset_mac_len(skb);
4854 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
4855 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
4856 skb = skb_vlan_untag(skb);
4861 if (skb_skip_tc_classify(skb))
4867 list_for_each_entry_rcu(ptype, &ptype_all, list) {
4869 ret = deliver_skb(skb, pt_prev, orig_dev);
4873 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
4875 ret = deliver_skb(skb, pt_prev, orig_dev);
4880 #ifdef CONFIG_NET_INGRESS
4881 if (static_branch_unlikely(&ingress_needed_key)) {
4882 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
4886 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
4892 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
4895 if (skb_vlan_tag_present(skb)) {
4897 ret = deliver_skb(skb, pt_prev, orig_dev);
4900 if (vlan_do_receive(&skb))
4902 else if (unlikely(!skb))
4906 rx_handler = rcu_dereference(skb->dev->rx_handler);
4909 ret = deliver_skb(skb, pt_prev, orig_dev);
4912 switch (rx_handler(&skb)) {
4913 case RX_HANDLER_CONSUMED:
4914 ret = NET_RX_SUCCESS;
4916 case RX_HANDLER_ANOTHER:
4918 case RX_HANDLER_EXACT:
4919 deliver_exact = true;
4920 case RX_HANDLER_PASS:
4927 if (unlikely(skb_vlan_tag_present(skb))) {
4929 if (skb_vlan_tag_get_id(skb)) {
4930 /* Vlan id is non 0 and vlan_do_receive() above couldn't
4933 skb->pkt_type = PACKET_OTHERHOST;
4934 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
4935 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
4936 /* Outer header is 802.1P with vlan 0, inner header is
4937 * 802.1Q or 802.1AD and vlan_do_receive() above could
4938 * not find vlan dev for vlan id 0.
4940 __vlan_hwaccel_clear_tag(skb);
4941 skb = skb_vlan_untag(skb);
4944 if (vlan_do_receive(&skb))
4945 /* After stripping off 802.1P header with vlan 0
4946 * vlan dev is found for inner header.
4949 else if (unlikely(!skb))
4952 /* We have stripped outer 802.1P vlan 0 header.
4953 * But could not find vlan dev.
4954 * check again for vlan id to set OTHERHOST.
4958 /* Note: we might in the future use prio bits
4959 * and set skb->priority like in vlan_do_receive()
4960 * For the time being, just ignore Priority Code Point
4962 __vlan_hwaccel_clear_tag(skb);
4965 type = skb->protocol;
4967 /* deliver only exact match when indicated */
4968 if (likely(!deliver_exact)) {
4969 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4970 &ptype_base[ntohs(type) &
4974 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4975 &orig_dev->ptype_specific);
4977 if (unlikely(skb->dev != orig_dev)) {
4978 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
4979 &skb->dev->ptype_specific);
4983 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
4985 *ppt_prev = pt_prev;
4989 atomic_long_inc(&skb->dev->rx_dropped);
4991 atomic_long_inc(&skb->dev->rx_nohandler);
4993 /* Jamal, now you will not able to escape explaining
4994 * me how you were going to use this. :-)
5003 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5005 struct net_device *orig_dev = skb->dev;
5006 struct packet_type *pt_prev = NULL;
5009 ret = __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
5011 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5012 skb->dev, pt_prev, orig_dev);
5017 * netif_receive_skb_core - special purpose version of netif_receive_skb
5018 * @skb: buffer to process
5020 * More direct receive version of netif_receive_skb(). It should
5021 * only be used by callers that have a need to skip RPS and Generic XDP.
5022 * Caller must also take care of handling if (page_is_)pfmemalloc.
5024 * This function may only be called from softirq context and interrupts
5025 * should be enabled.
5027 * Return values (usually ignored):
5028 * NET_RX_SUCCESS: no congestion
5029 * NET_RX_DROP: packet was dropped
5031 int netif_receive_skb_core(struct sk_buff *skb)
5036 ret = __netif_receive_skb_one_core(skb, false);
5041 EXPORT_SYMBOL(netif_receive_skb_core);
5043 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5044 struct packet_type *pt_prev,
5045 struct net_device *orig_dev)
5047 struct sk_buff *skb, *next;
5051 if (list_empty(head))
5053 if (pt_prev->list_func != NULL)
5054 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5055 ip_list_rcv, head, pt_prev, orig_dev);
5057 list_for_each_entry_safe(skb, next, head, list) {
5058 skb_list_del_init(skb);
5059 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5063 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5065 /* Fast-path assumptions:
5066 * - There is no RX handler.
5067 * - Only one packet_type matches.
5068 * If either of these fails, we will end up doing some per-packet
5069 * processing in-line, then handling the 'last ptype' for the whole
5070 * sublist. This can't cause out-of-order delivery to any single ptype,
5071 * because the 'last ptype' must be constant across the sublist, and all
5072 * other ptypes are handled per-packet.
5074 /* Current (common) ptype of sublist */
5075 struct packet_type *pt_curr = NULL;
5076 /* Current (common) orig_dev of sublist */
5077 struct net_device *od_curr = NULL;
5078 struct list_head sublist;
5079 struct sk_buff *skb, *next;
5081 INIT_LIST_HEAD(&sublist);
5082 list_for_each_entry_safe(skb, next, head, list) {
5083 struct net_device *orig_dev = skb->dev;
5084 struct packet_type *pt_prev = NULL;
5086 skb_list_del_init(skb);
5087 __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
5090 if (pt_curr != pt_prev || od_curr != orig_dev) {
5091 /* dispatch old sublist */
5092 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5093 /* start new sublist */
5094 INIT_LIST_HEAD(&sublist);
5098 list_add_tail(&skb->list, &sublist);
5101 /* dispatch final sublist */
5102 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5105 static int __netif_receive_skb(struct sk_buff *skb)
5109 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5110 unsigned int noreclaim_flag;
5113 * PFMEMALLOC skbs are special, they should
5114 * - be delivered to SOCK_MEMALLOC sockets only
5115 * - stay away from userspace
5116 * - have bounded memory usage
5118 * Use PF_MEMALLOC as this saves us from propagating the allocation
5119 * context down to all allocation sites.
5121 noreclaim_flag = memalloc_noreclaim_save();
5122 ret = __netif_receive_skb_one_core(skb, true);
5123 memalloc_noreclaim_restore(noreclaim_flag);
5125 ret = __netif_receive_skb_one_core(skb, false);
5130 static void __netif_receive_skb_list(struct list_head *head)
5132 unsigned long noreclaim_flag = 0;
5133 struct sk_buff *skb, *next;
5134 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5136 list_for_each_entry_safe(skb, next, head, list) {
5137 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5138 struct list_head sublist;
5140 /* Handle the previous sublist */
5141 list_cut_before(&sublist, head, &skb->list);
5142 if (!list_empty(&sublist))
5143 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5144 pfmemalloc = !pfmemalloc;
5145 /* See comments in __netif_receive_skb */
5147 noreclaim_flag = memalloc_noreclaim_save();
5149 memalloc_noreclaim_restore(noreclaim_flag);
5152 /* Handle the remaining sublist */
5153 if (!list_empty(head))
5154 __netif_receive_skb_list_core(head, pfmemalloc);
5155 /* Restore pflags */
5157 memalloc_noreclaim_restore(noreclaim_flag);
5160 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5162 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5163 struct bpf_prog *new = xdp->prog;
5166 switch (xdp->command) {
5167 case XDP_SETUP_PROG:
5168 rcu_assign_pointer(dev->xdp_prog, new);
5173 static_branch_dec(&generic_xdp_needed_key);
5174 } else if (new && !old) {
5175 static_branch_inc(&generic_xdp_needed_key);
5176 dev_disable_lro(dev);
5177 dev_disable_gro_hw(dev);
5181 case XDP_QUERY_PROG:
5182 xdp->prog_id = old ? old->aux->id : 0;
5193 static int netif_receive_skb_internal(struct sk_buff *skb)
5197 net_timestamp_check(netdev_tstamp_prequeue, skb);
5199 if (skb_defer_rx_timestamp(skb))
5200 return NET_RX_SUCCESS;
5204 if (static_branch_unlikely(&rps_needed)) {
5205 struct rps_dev_flow voidflow, *rflow = &voidflow;
5206 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5209 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5215 ret = __netif_receive_skb(skb);
5220 static void netif_receive_skb_list_internal(struct list_head *head)
5222 struct sk_buff *skb, *next;
5223 struct list_head sublist;
5225 INIT_LIST_HEAD(&sublist);
5226 list_for_each_entry_safe(skb, next, head, list) {
5227 net_timestamp_check(netdev_tstamp_prequeue, skb);
5228 skb_list_del_init(skb);
5229 if (!skb_defer_rx_timestamp(skb))
5230 list_add_tail(&skb->list, &sublist);
5232 list_splice_init(&sublist, head);
5236 if (static_branch_unlikely(&rps_needed)) {
5237 list_for_each_entry_safe(skb, next, head, list) {
5238 struct rps_dev_flow voidflow, *rflow = &voidflow;
5239 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5242 /* Will be handled, remove from list */
5243 skb_list_del_init(skb);
5244 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5249 __netif_receive_skb_list(head);
5254 * netif_receive_skb - process receive buffer from network
5255 * @skb: buffer to process
5257 * netif_receive_skb() is the main receive data processing function.
5258 * It always succeeds. The buffer may be dropped during processing
5259 * for congestion control or by the protocol layers.
5261 * This function may only be called from softirq context and interrupts
5262 * should be enabled.
5264 * Return values (usually ignored):
5265 * NET_RX_SUCCESS: no congestion
5266 * NET_RX_DROP: packet was dropped
5268 int netif_receive_skb(struct sk_buff *skb)
5272 trace_netif_receive_skb_entry(skb);
5274 ret = netif_receive_skb_internal(skb);
5275 trace_netif_receive_skb_exit(ret);
5279 EXPORT_SYMBOL(netif_receive_skb);
5282 * netif_receive_skb_list - process many receive buffers from network
5283 * @head: list of skbs to process.
5285 * Since return value of netif_receive_skb() is normally ignored, and
5286 * wouldn't be meaningful for a list, this function returns void.
5288 * This function may only be called from softirq context and interrupts
5289 * should be enabled.
5291 void netif_receive_skb_list(struct list_head *head)
5293 struct sk_buff *skb;
5295 if (list_empty(head))
5297 if (trace_netif_receive_skb_list_entry_enabled()) {
5298 list_for_each_entry(skb, head, list)
5299 trace_netif_receive_skb_list_entry(skb);
5301 netif_receive_skb_list_internal(head);
5302 trace_netif_receive_skb_list_exit(0);
5304 EXPORT_SYMBOL(netif_receive_skb_list);
5306 DEFINE_PER_CPU(struct work_struct, flush_works);
5308 /* Network device is going away, flush any packets still pending */
5309 static void flush_backlog(struct work_struct *work)
5311 struct sk_buff *skb, *tmp;
5312 struct softnet_data *sd;
5315 sd = this_cpu_ptr(&softnet_data);
5317 local_irq_disable();
5319 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5320 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5321 __skb_unlink(skb, &sd->input_pkt_queue);
5323 input_queue_head_incr(sd);
5329 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5330 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5331 __skb_unlink(skb, &sd->process_queue);
5333 input_queue_head_incr(sd);
5339 static void flush_all_backlogs(void)
5345 for_each_online_cpu(cpu)
5346 queue_work_on(cpu, system_highpri_wq,
5347 per_cpu_ptr(&flush_works, cpu));
5349 for_each_online_cpu(cpu)
5350 flush_work(per_cpu_ptr(&flush_works, cpu));
5355 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5356 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5357 static int napi_gro_complete(struct sk_buff *skb)
5359 struct packet_offload *ptype;
5360 __be16 type = skb->protocol;
5361 struct list_head *head = &offload_base;
5364 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5366 if (NAPI_GRO_CB(skb)->count == 1) {
5367 skb_shinfo(skb)->gso_size = 0;
5372 list_for_each_entry_rcu(ptype, head, list) {
5373 if (ptype->type != type || !ptype->callbacks.gro_complete)
5376 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5377 ipv6_gro_complete, inet_gro_complete,
5384 WARN_ON(&ptype->list == head);
5386 return NET_RX_SUCCESS;
5390 return netif_receive_skb_internal(skb);
5393 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5396 struct list_head *head = &napi->gro_hash[index].list;
5397 struct sk_buff *skb, *p;
5399 list_for_each_entry_safe_reverse(skb, p, head, list) {
5400 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5402 skb_list_del_init(skb);
5403 napi_gro_complete(skb);
5404 napi->gro_hash[index].count--;
5407 if (!napi->gro_hash[index].count)
5408 __clear_bit(index, &napi->gro_bitmask);
5411 /* napi->gro_hash[].list contains packets ordered by age.
5412 * youngest packets at the head of it.
5413 * Complete skbs in reverse order to reduce latencies.
5415 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5417 unsigned long bitmask = napi->gro_bitmask;
5418 unsigned int i, base = ~0U;
5420 while ((i = ffs(bitmask)) != 0) {
5423 __napi_gro_flush_chain(napi, base, flush_old);
5426 EXPORT_SYMBOL(napi_gro_flush);
5428 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5429 struct sk_buff *skb)
5431 unsigned int maclen = skb->dev->hard_header_len;
5432 u32 hash = skb_get_hash_raw(skb);
5433 struct list_head *head;
5436 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5437 list_for_each_entry(p, head, list) {
5438 unsigned long diffs;
5440 NAPI_GRO_CB(p)->flush = 0;
5442 if (hash != skb_get_hash_raw(p)) {
5443 NAPI_GRO_CB(p)->same_flow = 0;
5447 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5448 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5449 if (skb_vlan_tag_present(p))
5450 diffs |= p->vlan_tci ^ skb->vlan_tci;
5451 diffs |= skb_metadata_dst_cmp(p, skb);
5452 diffs |= skb_metadata_differs(p, skb);
5453 if (maclen == ETH_HLEN)
5454 diffs |= compare_ether_header(skb_mac_header(p),
5455 skb_mac_header(skb));
5457 diffs = memcmp(skb_mac_header(p),
5458 skb_mac_header(skb),
5460 NAPI_GRO_CB(p)->same_flow = !diffs;
5466 static void skb_gro_reset_offset(struct sk_buff *skb)
5468 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5469 const skb_frag_t *frag0 = &pinfo->frags[0];
5471 NAPI_GRO_CB(skb)->data_offset = 0;
5472 NAPI_GRO_CB(skb)->frag0 = NULL;
5473 NAPI_GRO_CB(skb)->frag0_len = 0;
5475 if (skb_mac_header(skb) == skb_tail_pointer(skb) &&
5477 !PageHighMem(skb_frag_page(frag0))) {
5478 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5479 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5480 skb_frag_size(frag0),
5481 skb->end - skb->tail);
5485 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5487 struct skb_shared_info *pinfo = skb_shinfo(skb);
5489 BUG_ON(skb->end - skb->tail < grow);
5491 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5493 skb->data_len -= grow;
5496 skb_frag_off_add(&pinfo->frags[0], grow);
5497 skb_frag_size_sub(&pinfo->frags[0], grow);
5499 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5500 skb_frag_unref(skb, 0);
5501 memmove(pinfo->frags, pinfo->frags + 1,
5502 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5506 static void gro_flush_oldest(struct list_head *head)
5508 struct sk_buff *oldest;
5510 oldest = list_last_entry(head, struct sk_buff, list);
5512 /* We are called with head length >= MAX_GRO_SKBS, so this is
5515 if (WARN_ON_ONCE(!oldest))
5518 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5521 skb_list_del_init(oldest);
5522 napi_gro_complete(oldest);
5525 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5527 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5529 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5531 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5532 struct list_head *head = &offload_base;
5533 struct packet_offload *ptype;
5534 __be16 type = skb->protocol;
5535 struct list_head *gro_head;
5536 struct sk_buff *pp = NULL;
5537 enum gro_result ret;
5541 if (netif_elide_gro(skb->dev))
5544 gro_head = gro_list_prepare(napi, skb);
5547 list_for_each_entry_rcu(ptype, head, list) {
5548 if (ptype->type != type || !ptype->callbacks.gro_receive)
5551 skb_set_network_header(skb, skb_gro_offset(skb));
5552 skb_reset_mac_len(skb);
5553 NAPI_GRO_CB(skb)->same_flow = 0;
5554 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5555 NAPI_GRO_CB(skb)->free = 0;
5556 NAPI_GRO_CB(skb)->encap_mark = 0;
5557 NAPI_GRO_CB(skb)->recursion_counter = 0;
5558 NAPI_GRO_CB(skb)->is_fou = 0;
5559 NAPI_GRO_CB(skb)->is_atomic = 1;
5560 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5562 /* Setup for GRO checksum validation */
5563 switch (skb->ip_summed) {
5564 case CHECKSUM_COMPLETE:
5565 NAPI_GRO_CB(skb)->csum = skb->csum;
5566 NAPI_GRO_CB(skb)->csum_valid = 1;
5567 NAPI_GRO_CB(skb)->csum_cnt = 0;
5569 case CHECKSUM_UNNECESSARY:
5570 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
5571 NAPI_GRO_CB(skb)->csum_valid = 0;
5574 NAPI_GRO_CB(skb)->csum_cnt = 0;
5575 NAPI_GRO_CB(skb)->csum_valid = 0;
5578 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
5579 ipv6_gro_receive, inet_gro_receive,
5585 if (&ptype->list == head)
5588 if (IS_ERR(pp) && PTR_ERR(pp) == -EINPROGRESS) {
5593 same_flow = NAPI_GRO_CB(skb)->same_flow;
5594 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
5597 skb_list_del_init(pp);
5598 napi_gro_complete(pp);
5599 napi->gro_hash[hash].count--;
5605 if (NAPI_GRO_CB(skb)->flush)
5608 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
5609 gro_flush_oldest(gro_head);
5611 napi->gro_hash[hash].count++;
5613 NAPI_GRO_CB(skb)->count = 1;
5614 NAPI_GRO_CB(skb)->age = jiffies;
5615 NAPI_GRO_CB(skb)->last = skb;
5616 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
5617 list_add(&skb->list, gro_head);
5621 grow = skb_gro_offset(skb) - skb_headlen(skb);
5623 gro_pull_from_frag0(skb, grow);
5625 if (napi->gro_hash[hash].count) {
5626 if (!test_bit(hash, &napi->gro_bitmask))
5627 __set_bit(hash, &napi->gro_bitmask);
5628 } else if (test_bit(hash, &napi->gro_bitmask)) {
5629 __clear_bit(hash, &napi->gro_bitmask);
5639 struct packet_offload *gro_find_receive_by_type(__be16 type)
5641 struct list_head *offload_head = &offload_base;
5642 struct packet_offload *ptype;
5644 list_for_each_entry_rcu(ptype, offload_head, list) {
5645 if (ptype->type != type || !ptype->callbacks.gro_receive)
5651 EXPORT_SYMBOL(gro_find_receive_by_type);
5653 struct packet_offload *gro_find_complete_by_type(__be16 type)
5655 struct list_head *offload_head = &offload_base;
5656 struct packet_offload *ptype;
5658 list_for_each_entry_rcu(ptype, offload_head, list) {
5659 if (ptype->type != type || !ptype->callbacks.gro_complete)
5665 EXPORT_SYMBOL(gro_find_complete_by_type);
5667 static void napi_skb_free_stolen_head(struct sk_buff *skb)
5671 kmem_cache_free(skbuff_head_cache, skb);
5674 static gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
5678 if (netif_receive_skb_internal(skb))
5686 case GRO_MERGED_FREE:
5687 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5688 napi_skb_free_stolen_head(skb);
5702 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5706 skb_mark_napi_id(skb, napi);
5707 trace_napi_gro_receive_entry(skb);
5709 skb_gro_reset_offset(skb);
5711 ret = napi_skb_finish(dev_gro_receive(napi, skb), skb);
5712 trace_napi_gro_receive_exit(ret);
5716 EXPORT_SYMBOL(napi_gro_receive);
5718 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
5720 if (unlikely(skb->pfmemalloc)) {
5724 __skb_pull(skb, skb_headlen(skb));
5725 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
5726 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
5727 __vlan_hwaccel_clear_tag(skb);
5728 skb->dev = napi->dev;
5731 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
5732 skb->pkt_type = PACKET_HOST;
5734 skb->encapsulation = 0;
5735 skb_shinfo(skb)->gso_type = 0;
5736 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
5742 struct sk_buff *napi_get_frags(struct napi_struct *napi)
5744 struct sk_buff *skb = napi->skb;
5747 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
5750 skb_mark_napi_id(skb, napi);
5755 EXPORT_SYMBOL(napi_get_frags);
5757 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
5758 static void gro_normal_list(struct napi_struct *napi)
5760 if (!napi->rx_count)
5762 netif_receive_skb_list_internal(&napi->rx_list);
5763 INIT_LIST_HEAD(&napi->rx_list);
5767 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5768 * pass the whole batch up to the stack.
5770 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb)
5772 list_add_tail(&skb->list, &napi->rx_list);
5773 if (++napi->rx_count >= gro_normal_batch)
5774 gro_normal_list(napi);
5777 static gro_result_t napi_frags_finish(struct napi_struct *napi,
5778 struct sk_buff *skb,
5784 __skb_push(skb, ETH_HLEN);
5785 skb->protocol = eth_type_trans(skb, skb->dev);
5786 if (ret == GRO_NORMAL)
5787 gro_normal_one(napi, skb);
5791 napi_reuse_skb(napi, skb);
5794 case GRO_MERGED_FREE:
5795 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5796 napi_skb_free_stolen_head(skb);
5798 napi_reuse_skb(napi, skb);
5809 /* Upper GRO stack assumes network header starts at gro_offset=0
5810 * Drivers could call both napi_gro_frags() and napi_gro_receive()
5811 * We copy ethernet header into skb->data to have a common layout.
5813 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
5815 struct sk_buff *skb = napi->skb;
5816 const struct ethhdr *eth;
5817 unsigned int hlen = sizeof(*eth);
5821 skb_reset_mac_header(skb);
5822 skb_gro_reset_offset(skb);
5824 if (unlikely(skb_gro_header_hard(skb, hlen))) {
5825 eth = skb_gro_header_slow(skb, hlen, 0);
5826 if (unlikely(!eth)) {
5827 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
5828 __func__, napi->dev->name);
5829 napi_reuse_skb(napi, skb);
5833 eth = (const struct ethhdr *)skb->data;
5834 gro_pull_from_frag0(skb, hlen);
5835 NAPI_GRO_CB(skb)->frag0 += hlen;
5836 NAPI_GRO_CB(skb)->frag0_len -= hlen;
5838 __skb_pull(skb, hlen);
5841 * This works because the only protocols we care about don't require
5843 * We'll fix it up properly in napi_frags_finish()
5845 skb->protocol = eth->h_proto;
5850 gro_result_t napi_gro_frags(struct napi_struct *napi)
5853 struct sk_buff *skb = napi_frags_skb(napi);
5858 trace_napi_gro_frags_entry(skb);
5860 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
5861 trace_napi_gro_frags_exit(ret);
5865 EXPORT_SYMBOL(napi_gro_frags);
5867 /* Compute the checksum from gro_offset and return the folded value
5868 * after adding in any pseudo checksum.
5870 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
5875 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
5877 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
5878 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
5879 /* See comments in __skb_checksum_complete(). */
5881 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
5882 !skb->csum_complete_sw)
5883 netdev_rx_csum_fault(skb->dev, skb);
5886 NAPI_GRO_CB(skb)->csum = wsum;
5887 NAPI_GRO_CB(skb)->csum_valid = 1;
5891 EXPORT_SYMBOL(__skb_gro_checksum_complete);
5893 static void net_rps_send_ipi(struct softnet_data *remsd)
5897 struct softnet_data *next = remsd->rps_ipi_next;
5899 if (cpu_online(remsd->cpu))
5900 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5907 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5908 * Note: called with local irq disabled, but exits with local irq enabled.
5910 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5913 struct softnet_data *remsd = sd->rps_ipi_list;
5916 sd->rps_ipi_list = NULL;
5920 /* Send pending IPI's to kick RPS processing on remote cpus. */
5921 net_rps_send_ipi(remsd);
5927 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5930 return sd->rps_ipi_list != NULL;
5936 static int process_backlog(struct napi_struct *napi, int quota)
5938 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5942 /* Check if we have pending ipi, its better to send them now,
5943 * not waiting net_rx_action() end.
5945 if (sd_has_rps_ipi_waiting(sd)) {
5946 local_irq_disable();
5947 net_rps_action_and_irq_enable(sd);
5950 napi->weight = dev_rx_weight;
5952 struct sk_buff *skb;
5954 while ((skb = __skb_dequeue(&sd->process_queue))) {
5956 __netif_receive_skb(skb);
5958 input_queue_head_incr(sd);
5959 if (++work >= quota)
5964 local_irq_disable();
5966 if (skb_queue_empty(&sd->input_pkt_queue)) {
5968 * Inline a custom version of __napi_complete().
5969 * only current cpu owns and manipulates this napi,
5970 * and NAPI_STATE_SCHED is the only possible flag set
5972 * We can use a plain write instead of clear_bit(),
5973 * and we dont need an smp_mb() memory barrier.
5978 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5979 &sd->process_queue);
5989 * __napi_schedule - schedule for receive
5990 * @n: entry to schedule
5992 * The entry's receive function will be scheduled to run.
5993 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
5995 void __napi_schedule(struct napi_struct *n)
5997 unsigned long flags;
5999 local_irq_save(flags);
6000 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6001 local_irq_restore(flags);
6003 EXPORT_SYMBOL(__napi_schedule);
6006 * napi_schedule_prep - check if napi can be scheduled
6009 * Test if NAPI routine is already running, and if not mark
6010 * it as running. This is used as a condition variable
6011 * insure only one NAPI poll instance runs. We also make
6012 * sure there is no pending NAPI disable.
6014 bool napi_schedule_prep(struct napi_struct *n)
6016 unsigned long val, new;
6019 val = READ_ONCE(n->state);
6020 if (unlikely(val & NAPIF_STATE_DISABLE))
6022 new = val | NAPIF_STATE_SCHED;
6024 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6025 * This was suggested by Alexander Duyck, as compiler
6026 * emits better code than :
6027 * if (val & NAPIF_STATE_SCHED)
6028 * new |= NAPIF_STATE_MISSED;
6030 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6032 } while (cmpxchg(&n->state, val, new) != val);
6034 return !(val & NAPIF_STATE_SCHED);
6036 EXPORT_SYMBOL(napi_schedule_prep);
6039 * __napi_schedule_irqoff - schedule for receive
6040 * @n: entry to schedule
6042 * Variant of __napi_schedule() assuming hard irqs are masked
6044 void __napi_schedule_irqoff(struct napi_struct *n)
6046 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6048 EXPORT_SYMBOL(__napi_schedule_irqoff);
6050 bool napi_complete_done(struct napi_struct *n, int work_done)
6052 unsigned long flags, val, new;
6055 * 1) Don't let napi dequeue from the cpu poll list
6056 * just in case its running on a different cpu.
6057 * 2) If we are busy polling, do nothing here, we have
6058 * the guarantee we will be called later.
6060 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6061 NAPIF_STATE_IN_BUSY_POLL)))
6066 if (n->gro_bitmask) {
6067 unsigned long timeout = 0;
6070 timeout = n->dev->gro_flush_timeout;
6072 /* When the NAPI instance uses a timeout and keeps postponing
6073 * it, we need to bound somehow the time packets are kept in
6076 napi_gro_flush(n, !!timeout);
6078 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6079 HRTIMER_MODE_REL_PINNED);
6081 if (unlikely(!list_empty(&n->poll_list))) {
6082 /* If n->poll_list is not empty, we need to mask irqs */
6083 local_irq_save(flags);
6084 list_del_init(&n->poll_list);
6085 local_irq_restore(flags);
6089 val = READ_ONCE(n->state);
6091 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6093 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6095 /* If STATE_MISSED was set, leave STATE_SCHED set,
6096 * because we will call napi->poll() one more time.
6097 * This C code was suggested by Alexander Duyck to help gcc.
6099 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6101 } while (cmpxchg(&n->state, val, new) != val);
6103 if (unlikely(val & NAPIF_STATE_MISSED)) {
6110 EXPORT_SYMBOL(napi_complete_done);
6112 /* must be called under rcu_read_lock(), as we dont take a reference */
6113 static struct napi_struct *napi_by_id(unsigned int napi_id)
6115 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6116 struct napi_struct *napi;
6118 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6119 if (napi->napi_id == napi_id)
6125 #if defined(CONFIG_NET_RX_BUSY_POLL)
6127 #define BUSY_POLL_BUDGET 8
6129 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6133 /* Busy polling means there is a high chance device driver hard irq
6134 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6135 * set in napi_schedule_prep().
6136 * Since we are about to call napi->poll() once more, we can safely
6137 * clear NAPI_STATE_MISSED.
6139 * Note: x86 could use a single "lock and ..." instruction
6140 * to perform these two clear_bit()
6142 clear_bit(NAPI_STATE_MISSED, &napi->state);
6143 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6147 /* All we really want here is to re-enable device interrupts.
6148 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6150 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6151 /* We can't gro_normal_list() here, because napi->poll() might have
6152 * rearmed the napi (napi_complete_done()) in which case it could
6153 * already be running on another CPU.
6155 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6156 netpoll_poll_unlock(have_poll_lock);
6157 if (rc == BUSY_POLL_BUDGET) {
6158 /* As the whole budget was spent, we still own the napi so can
6159 * safely handle the rx_list.
6161 gro_normal_list(napi);
6162 __napi_schedule(napi);
6167 void napi_busy_loop(unsigned int napi_id,
6168 bool (*loop_end)(void *, unsigned long),
6171 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6172 int (*napi_poll)(struct napi_struct *napi, int budget);
6173 void *have_poll_lock = NULL;
6174 struct napi_struct *napi;
6181 napi = napi_by_id(napi_id);
6191 unsigned long val = READ_ONCE(napi->state);
6193 /* If multiple threads are competing for this napi,
6194 * we avoid dirtying napi->state as much as we can.
6196 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6197 NAPIF_STATE_IN_BUSY_POLL))
6199 if (cmpxchg(&napi->state, val,
6200 val | NAPIF_STATE_IN_BUSY_POLL |
6201 NAPIF_STATE_SCHED) != val)
6203 have_poll_lock = netpoll_poll_lock(napi);
6204 napi_poll = napi->poll;
6206 work = napi_poll(napi, BUSY_POLL_BUDGET);
6207 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6208 gro_normal_list(napi);
6211 __NET_ADD_STATS(dev_net(napi->dev),
6212 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6215 if (!loop_end || loop_end(loop_end_arg, start_time))
6218 if (unlikely(need_resched())) {
6220 busy_poll_stop(napi, have_poll_lock);
6224 if (loop_end(loop_end_arg, start_time))
6231 busy_poll_stop(napi, have_poll_lock);
6236 EXPORT_SYMBOL(napi_busy_loop);
6238 #endif /* CONFIG_NET_RX_BUSY_POLL */
6240 static void napi_hash_add(struct napi_struct *napi)
6242 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
6243 test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
6246 spin_lock(&napi_hash_lock);
6248 /* 0..NR_CPUS range is reserved for sender_cpu use */
6250 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6251 napi_gen_id = MIN_NAPI_ID;
6252 } while (napi_by_id(napi_gen_id));
6253 napi->napi_id = napi_gen_id;
6255 hlist_add_head_rcu(&napi->napi_hash_node,
6256 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6258 spin_unlock(&napi_hash_lock);
6261 /* Warning : caller is responsible to make sure rcu grace period
6262 * is respected before freeing memory containing @napi
6264 bool napi_hash_del(struct napi_struct *napi)
6266 bool rcu_sync_needed = false;
6268 spin_lock(&napi_hash_lock);
6270 if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
6271 rcu_sync_needed = true;
6272 hlist_del_rcu(&napi->napi_hash_node);
6274 spin_unlock(&napi_hash_lock);
6275 return rcu_sync_needed;
6277 EXPORT_SYMBOL_GPL(napi_hash_del);
6279 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6281 struct napi_struct *napi;
6283 napi = container_of(timer, struct napi_struct, timer);
6285 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6286 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6288 if (napi->gro_bitmask && !napi_disable_pending(napi) &&
6289 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6290 __napi_schedule_irqoff(napi);
6292 return HRTIMER_NORESTART;
6295 static void init_gro_hash(struct napi_struct *napi)
6299 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6300 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6301 napi->gro_hash[i].count = 0;
6303 napi->gro_bitmask = 0;
6306 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6307 int (*poll)(struct napi_struct *, int), int weight)
6309 INIT_LIST_HEAD(&napi->poll_list);
6310 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6311 napi->timer.function = napi_watchdog;
6312 init_gro_hash(napi);
6314 INIT_LIST_HEAD(&napi->rx_list);
6317 if (weight > NAPI_POLL_WEIGHT)
6318 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6320 napi->weight = weight;
6321 list_add(&napi->dev_list, &dev->napi_list);
6323 #ifdef CONFIG_NETPOLL
6324 napi->poll_owner = -1;
6326 set_bit(NAPI_STATE_SCHED, &napi->state);
6327 napi_hash_add(napi);
6329 EXPORT_SYMBOL(netif_napi_add);
6331 void napi_disable(struct napi_struct *n)
6334 set_bit(NAPI_STATE_DISABLE, &n->state);
6336 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6338 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6341 hrtimer_cancel(&n->timer);
6343 clear_bit(NAPI_STATE_DISABLE, &n->state);
6345 EXPORT_SYMBOL(napi_disable);
6347 static void flush_gro_hash(struct napi_struct *napi)
6351 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6352 struct sk_buff *skb, *n;
6354 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6356 napi->gro_hash[i].count = 0;
6360 /* Must be called in process context */
6361 void netif_napi_del(struct napi_struct *napi)
6364 if (napi_hash_del(napi))
6366 list_del_init(&napi->dev_list);
6367 napi_free_frags(napi);
6369 flush_gro_hash(napi);
6370 napi->gro_bitmask = 0;
6372 EXPORT_SYMBOL(netif_napi_del);
6374 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6379 list_del_init(&n->poll_list);
6381 have = netpoll_poll_lock(n);
6385 /* This NAPI_STATE_SCHED test is for avoiding a race
6386 * with netpoll's poll_napi(). Only the entity which
6387 * obtains the lock and sees NAPI_STATE_SCHED set will
6388 * actually make the ->poll() call. Therefore we avoid
6389 * accidentally calling ->poll() when NAPI is not scheduled.
6392 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6393 work = n->poll(n, weight);
6394 trace_napi_poll(n, work, weight);
6397 WARN_ON_ONCE(work > weight);
6399 if (likely(work < weight))
6402 /* Drivers must not modify the NAPI state if they
6403 * consume the entire weight. In such cases this code
6404 * still "owns" the NAPI instance and therefore can
6405 * move the instance around on the list at-will.
6407 if (unlikely(napi_disable_pending(n))) {
6414 if (n->gro_bitmask) {
6415 /* flush too old packets
6416 * If HZ < 1000, flush all packets.
6418 napi_gro_flush(n, HZ >= 1000);
6421 /* Some drivers may have called napi_schedule
6422 * prior to exhausting their budget.
6424 if (unlikely(!list_empty(&n->poll_list))) {
6425 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6426 n->dev ? n->dev->name : "backlog");
6430 list_add_tail(&n->poll_list, repoll);
6433 netpoll_poll_unlock(have);
6438 static __latent_entropy void net_rx_action(struct softirq_action *h)
6440 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6441 unsigned long time_limit = jiffies +
6442 usecs_to_jiffies(netdev_budget_usecs);
6443 int budget = netdev_budget;
6447 local_irq_disable();
6448 list_splice_init(&sd->poll_list, &list);
6452 struct napi_struct *n;
6454 if (list_empty(&list)) {
6455 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6460 n = list_first_entry(&list, struct napi_struct, poll_list);
6461 budget -= napi_poll(n, &repoll);
6463 /* If softirq window is exhausted then punt.
6464 * Allow this to run for 2 jiffies since which will allow
6465 * an average latency of 1.5/HZ.
6467 if (unlikely(budget <= 0 ||
6468 time_after_eq(jiffies, time_limit))) {
6474 local_irq_disable();
6476 list_splice_tail_init(&sd->poll_list, &list);
6477 list_splice_tail(&repoll, &list);
6478 list_splice(&list, &sd->poll_list);
6479 if (!list_empty(&sd->poll_list))
6480 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6482 net_rps_action_and_irq_enable(sd);
6484 __kfree_skb_flush();
6487 struct netdev_adjacent {
6488 struct net_device *dev;
6490 /* upper master flag, there can only be one master device per list */
6493 /* counter for the number of times this device was added to us */
6496 /* private field for the users */
6499 struct list_head list;
6500 struct rcu_head rcu;
6503 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6504 struct list_head *adj_list)
6506 struct netdev_adjacent *adj;
6508 list_for_each_entry(adj, adj_list, list) {
6509 if (adj->dev == adj_dev)
6515 static int __netdev_has_upper_dev(struct net_device *upper_dev, void *data)
6517 struct net_device *dev = data;
6519 return upper_dev == dev;
6523 * netdev_has_upper_dev - Check if device is linked to an upper device
6525 * @upper_dev: upper device to check
6527 * Find out if a device is linked to specified upper device and return true
6528 * in case it is. Note that this checks only immediate upper device,
6529 * not through a complete stack of devices. The caller must hold the RTNL lock.
6531 bool netdev_has_upper_dev(struct net_device *dev,
6532 struct net_device *upper_dev)
6536 return netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
6539 EXPORT_SYMBOL(netdev_has_upper_dev);
6542 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6544 * @upper_dev: upper device to check
6546 * Find out if a device is linked to specified upper device and return true
6547 * in case it is. Note that this checks the entire upper device chain.
6548 * The caller must hold rcu lock.
6551 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6552 struct net_device *upper_dev)
6554 return !!netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
6557 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6560 * netdev_has_any_upper_dev - Check if device is linked to some device
6563 * Find out if a device is linked to an upper device and return true in case
6564 * it is. The caller must hold the RTNL lock.
6566 bool netdev_has_any_upper_dev(struct net_device *dev)
6570 return !list_empty(&dev->adj_list.upper);
6572 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6575 * netdev_master_upper_dev_get - Get master upper device
6578 * Find a master upper device and return pointer to it or NULL in case
6579 * it's not there. The caller must hold the RTNL lock.
6581 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6583 struct netdev_adjacent *upper;
6587 if (list_empty(&dev->adj_list.upper))
6590 upper = list_first_entry(&dev->adj_list.upper,
6591 struct netdev_adjacent, list);
6592 if (likely(upper->master))
6596 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6599 * netdev_has_any_lower_dev - Check if device is linked to some device
6602 * Find out if a device is linked to a lower device and return true in case
6603 * it is. The caller must hold the RTNL lock.
6605 static bool netdev_has_any_lower_dev(struct net_device *dev)
6609 return !list_empty(&dev->adj_list.lower);
6612 void *netdev_adjacent_get_private(struct list_head *adj_list)
6614 struct netdev_adjacent *adj;
6616 adj = list_entry(adj_list, struct netdev_adjacent, list);
6618 return adj->private;
6620 EXPORT_SYMBOL(netdev_adjacent_get_private);
6623 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6625 * @iter: list_head ** of the current position
6627 * Gets the next device from the dev's upper list, starting from iter
6628 * position. The caller must hold RCU read lock.
6630 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6631 struct list_head **iter)
6633 struct netdev_adjacent *upper;
6635 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6637 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6639 if (&upper->list == &dev->adj_list.upper)
6642 *iter = &upper->list;
6646 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6648 static struct net_device *netdev_next_upper_dev(struct net_device *dev,
6649 struct list_head **iter)
6651 struct netdev_adjacent *upper;
6653 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6655 if (&upper->list == &dev->adj_list.upper)
6658 *iter = &upper->list;
6663 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6664 struct list_head **iter)
6666 struct netdev_adjacent *upper;
6668 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6670 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6672 if (&upper->list == &dev->adj_list.upper)
6675 *iter = &upper->list;
6680 static int netdev_walk_all_upper_dev(struct net_device *dev,
6681 int (*fn)(struct net_device *dev,
6685 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6686 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6690 iter = &dev->adj_list.upper;
6694 ret = fn(now, data);
6701 udev = netdev_next_upper_dev(now, &iter);
6706 niter = &udev->adj_list.upper;
6707 dev_stack[cur] = now;
6708 iter_stack[cur++] = iter;
6715 next = dev_stack[--cur];
6716 niter = iter_stack[cur];
6726 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6727 int (*fn)(struct net_device *dev,
6731 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6732 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6736 iter = &dev->adj_list.upper;
6740 ret = fn(now, data);
6747 udev = netdev_next_upper_dev_rcu(now, &iter);
6752 niter = &udev->adj_list.upper;
6753 dev_stack[cur] = now;
6754 iter_stack[cur++] = iter;
6761 next = dev_stack[--cur];
6762 niter = iter_stack[cur];
6771 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6774 * netdev_lower_get_next_private - Get the next ->private from the
6775 * lower neighbour list
6777 * @iter: list_head ** of the current position
6779 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6780 * list, starting from iter position. The caller must hold either hold the
6781 * RTNL lock or its own locking that guarantees that the neighbour lower
6782 * list will remain unchanged.
6784 void *netdev_lower_get_next_private(struct net_device *dev,
6785 struct list_head **iter)
6787 struct netdev_adjacent *lower;
6789 lower = list_entry(*iter, struct netdev_adjacent, list);
6791 if (&lower->list == &dev->adj_list.lower)
6794 *iter = lower->list.next;
6796 return lower->private;
6798 EXPORT_SYMBOL(netdev_lower_get_next_private);
6801 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6802 * lower neighbour list, RCU
6805 * @iter: list_head ** of the current position
6807 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6808 * list, starting from iter position. The caller must hold RCU read lock.
6810 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6811 struct list_head **iter)
6813 struct netdev_adjacent *lower;
6815 WARN_ON_ONCE(!rcu_read_lock_held());
6817 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6819 if (&lower->list == &dev->adj_list.lower)
6822 *iter = &lower->list;
6824 return lower->private;
6826 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6829 * netdev_lower_get_next - Get the next device from the lower neighbour
6832 * @iter: list_head ** of the current position
6834 * Gets the next netdev_adjacent from the dev's lower neighbour
6835 * list, starting from iter position. The caller must hold RTNL lock or
6836 * its own locking that guarantees that the neighbour lower
6837 * list will remain unchanged.
6839 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6841 struct netdev_adjacent *lower;
6843 lower = list_entry(*iter, struct netdev_adjacent, list);
6845 if (&lower->list == &dev->adj_list.lower)
6848 *iter = lower->list.next;
6852 EXPORT_SYMBOL(netdev_lower_get_next);
6854 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
6855 struct list_head **iter)
6857 struct netdev_adjacent *lower;
6859 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
6861 if (&lower->list == &dev->adj_list.lower)
6864 *iter = &lower->list;
6869 int netdev_walk_all_lower_dev(struct net_device *dev,
6870 int (*fn)(struct net_device *dev,
6874 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6875 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6879 iter = &dev->adj_list.lower;
6883 ret = fn(now, data);
6890 ldev = netdev_next_lower_dev(now, &iter);
6895 niter = &ldev->adj_list.lower;
6896 dev_stack[cur] = now;
6897 iter_stack[cur++] = iter;
6904 next = dev_stack[--cur];
6905 niter = iter_stack[cur];
6914 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
6916 static struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
6917 struct list_head **iter)
6919 struct netdev_adjacent *lower;
6921 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6922 if (&lower->list == &dev->adj_list.lower)
6925 *iter = &lower->list;
6930 static u8 __netdev_upper_depth(struct net_device *dev)
6932 struct net_device *udev;
6933 struct list_head *iter;
6936 for (iter = &dev->adj_list.upper,
6937 udev = netdev_next_upper_dev(dev, &iter);
6939 udev = netdev_next_upper_dev(dev, &iter)) {
6940 if (max_depth < udev->upper_level)
6941 max_depth = udev->upper_level;
6947 static u8 __netdev_lower_depth(struct net_device *dev)
6949 struct net_device *ldev;
6950 struct list_head *iter;
6953 for (iter = &dev->adj_list.lower,
6954 ldev = netdev_next_lower_dev(dev, &iter);
6956 ldev = netdev_next_lower_dev(dev, &iter)) {
6957 if (max_depth < ldev->lower_level)
6958 max_depth = ldev->lower_level;
6964 static int __netdev_update_upper_level(struct net_device *dev, void *data)
6966 dev->upper_level = __netdev_upper_depth(dev) + 1;
6970 static int __netdev_update_lower_level(struct net_device *dev, void *data)
6972 dev->lower_level = __netdev_lower_depth(dev) + 1;
6976 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
6977 int (*fn)(struct net_device *dev,
6981 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6982 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6986 iter = &dev->adj_list.lower;
6990 ret = fn(now, data);
6997 ldev = netdev_next_lower_dev_rcu(now, &iter);
7002 niter = &ldev->adj_list.lower;
7003 dev_stack[cur] = now;
7004 iter_stack[cur++] = iter;
7011 next = dev_stack[--cur];
7012 niter = iter_stack[cur];
7021 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7024 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7025 * lower neighbour list, RCU
7029 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7030 * list. The caller must hold RCU read lock.
7032 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7034 struct netdev_adjacent *lower;
7036 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7037 struct netdev_adjacent, list);
7039 return lower->private;
7042 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7045 * netdev_master_upper_dev_get_rcu - Get master upper device
7048 * Find a master upper device and return pointer to it or NULL in case
7049 * it's not there. The caller must hold the RCU read lock.
7051 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7053 struct netdev_adjacent *upper;
7055 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7056 struct netdev_adjacent, list);
7057 if (upper && likely(upper->master))
7061 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7063 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7064 struct net_device *adj_dev,
7065 struct list_head *dev_list)
7067 char linkname[IFNAMSIZ+7];
7069 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7070 "upper_%s" : "lower_%s", adj_dev->name);
7071 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7074 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7076 struct list_head *dev_list)
7078 char linkname[IFNAMSIZ+7];
7080 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7081 "upper_%s" : "lower_%s", name);
7082 sysfs_remove_link(&(dev->dev.kobj), linkname);
7085 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7086 struct net_device *adj_dev,
7087 struct list_head *dev_list)
7089 return (dev_list == &dev->adj_list.upper ||
7090 dev_list == &dev->adj_list.lower) &&
7091 net_eq(dev_net(dev), dev_net(adj_dev));
7094 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7095 struct net_device *adj_dev,
7096 struct list_head *dev_list,
7097 void *private, bool master)
7099 struct netdev_adjacent *adj;
7102 adj = __netdev_find_adj(adj_dev, dev_list);
7106 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7107 dev->name, adj_dev->name, adj->ref_nr);
7112 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7117 adj->master = master;
7119 adj->private = private;
7122 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7123 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7125 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7126 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7131 /* Ensure that master link is always the first item in list. */
7133 ret = sysfs_create_link(&(dev->dev.kobj),
7134 &(adj_dev->dev.kobj), "master");
7136 goto remove_symlinks;
7138 list_add_rcu(&adj->list, dev_list);
7140 list_add_tail_rcu(&adj->list, dev_list);
7146 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7147 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7155 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7156 struct net_device *adj_dev,
7158 struct list_head *dev_list)
7160 struct netdev_adjacent *adj;
7162 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7163 dev->name, adj_dev->name, ref_nr);
7165 adj = __netdev_find_adj(adj_dev, dev_list);
7168 pr_err("Adjacency does not exist for device %s from %s\n",
7169 dev->name, adj_dev->name);
7174 if (adj->ref_nr > ref_nr) {
7175 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7176 dev->name, adj_dev->name, ref_nr,
7177 adj->ref_nr - ref_nr);
7178 adj->ref_nr -= ref_nr;
7183 sysfs_remove_link(&(dev->dev.kobj), "master");
7185 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7186 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7188 list_del_rcu(&adj->list);
7189 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7190 adj_dev->name, dev->name, adj_dev->name);
7192 kfree_rcu(adj, rcu);
7195 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7196 struct net_device *upper_dev,
7197 struct list_head *up_list,
7198 struct list_head *down_list,
7199 void *private, bool master)
7203 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7208 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7211 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7218 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7219 struct net_device *upper_dev,
7221 struct list_head *up_list,
7222 struct list_head *down_list)
7224 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7225 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7228 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7229 struct net_device *upper_dev,
7230 void *private, bool master)
7232 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7233 &dev->adj_list.upper,
7234 &upper_dev->adj_list.lower,
7238 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7239 struct net_device *upper_dev)
7241 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7242 &dev->adj_list.upper,
7243 &upper_dev->adj_list.lower);
7246 static int __netdev_upper_dev_link(struct net_device *dev,
7247 struct net_device *upper_dev, bool master,
7248 void *upper_priv, void *upper_info,
7249 struct netlink_ext_ack *extack)
7251 struct netdev_notifier_changeupper_info changeupper_info = {
7256 .upper_dev = upper_dev,
7259 .upper_info = upper_info,
7261 struct net_device *master_dev;
7266 if (dev == upper_dev)
7269 /* To prevent loops, check if dev is not upper device to upper_dev. */
7270 if (netdev_has_upper_dev(upper_dev, dev))
7273 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7277 if (netdev_has_upper_dev(dev, upper_dev))
7280 master_dev = netdev_master_upper_dev_get(dev);
7282 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7285 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7286 &changeupper_info.info);
7287 ret = notifier_to_errno(ret);
7291 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7296 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7297 &changeupper_info.info);
7298 ret = notifier_to_errno(ret);
7302 __netdev_update_upper_level(dev, NULL);
7303 netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7305 __netdev_update_lower_level(upper_dev, NULL);
7306 netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, NULL);
7311 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7317 * netdev_upper_dev_link - Add a link to the upper device
7319 * @upper_dev: new upper device
7320 * @extack: netlink extended ack
7322 * Adds a link to device which is upper to this one. The caller must hold
7323 * the RTNL lock. On a failure a negative errno code is returned.
7324 * On success the reference counts are adjusted and the function
7327 int netdev_upper_dev_link(struct net_device *dev,
7328 struct net_device *upper_dev,
7329 struct netlink_ext_ack *extack)
7331 return __netdev_upper_dev_link(dev, upper_dev, false,
7332 NULL, NULL, extack);
7334 EXPORT_SYMBOL(netdev_upper_dev_link);
7337 * netdev_master_upper_dev_link - Add a master link to the upper device
7339 * @upper_dev: new upper device
7340 * @upper_priv: upper device private
7341 * @upper_info: upper info to be passed down via notifier
7342 * @extack: netlink extended ack
7344 * Adds a link to device which is upper to this one. In this case, only
7345 * one master upper device can be linked, although other non-master devices
7346 * might be linked as well. The caller must hold the RTNL lock.
7347 * On a failure a negative errno code is returned. On success the reference
7348 * counts are adjusted and the function returns zero.
7350 int netdev_master_upper_dev_link(struct net_device *dev,
7351 struct net_device *upper_dev,
7352 void *upper_priv, void *upper_info,
7353 struct netlink_ext_ack *extack)
7355 return __netdev_upper_dev_link(dev, upper_dev, true,
7356 upper_priv, upper_info, extack);
7358 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7361 * netdev_upper_dev_unlink - Removes a link to upper device
7363 * @upper_dev: new upper device
7365 * Removes a link to device which is upper to this one. The caller must hold
7368 void netdev_upper_dev_unlink(struct net_device *dev,
7369 struct net_device *upper_dev)
7371 struct netdev_notifier_changeupper_info changeupper_info = {
7375 .upper_dev = upper_dev,
7381 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7383 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7384 &changeupper_info.info);
7386 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7388 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7389 &changeupper_info.info);
7391 __netdev_update_upper_level(dev, NULL);
7392 netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7394 __netdev_update_lower_level(upper_dev, NULL);
7395 netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level, NULL);
7397 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7400 * netdev_bonding_info_change - Dispatch event about slave change
7402 * @bonding_info: info to dispatch
7404 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7405 * The caller must hold the RTNL lock.
7407 void netdev_bonding_info_change(struct net_device *dev,
7408 struct netdev_bonding_info *bonding_info)
7410 struct netdev_notifier_bonding_info info = {
7414 memcpy(&info.bonding_info, bonding_info,
7415 sizeof(struct netdev_bonding_info));
7416 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7419 EXPORT_SYMBOL(netdev_bonding_info_change);
7421 static void netdev_adjacent_add_links(struct net_device *dev)
7423 struct netdev_adjacent *iter;
7425 struct net *net = dev_net(dev);
7427 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7428 if (!net_eq(net, dev_net(iter->dev)))
7430 netdev_adjacent_sysfs_add(iter->dev, dev,
7431 &iter->dev->adj_list.lower);
7432 netdev_adjacent_sysfs_add(dev, iter->dev,
7433 &dev->adj_list.upper);
7436 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7437 if (!net_eq(net, dev_net(iter->dev)))
7439 netdev_adjacent_sysfs_add(iter->dev, dev,
7440 &iter->dev->adj_list.upper);
7441 netdev_adjacent_sysfs_add(dev, iter->dev,
7442 &dev->adj_list.lower);
7446 static void netdev_adjacent_del_links(struct net_device *dev)
7448 struct netdev_adjacent *iter;
7450 struct net *net = dev_net(dev);
7452 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7453 if (!net_eq(net, dev_net(iter->dev)))
7455 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7456 &iter->dev->adj_list.lower);
7457 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7458 &dev->adj_list.upper);
7461 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7462 if (!net_eq(net, dev_net(iter->dev)))
7464 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7465 &iter->dev->adj_list.upper);
7466 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7467 &dev->adj_list.lower);
7471 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
7473 struct netdev_adjacent *iter;
7475 struct net *net = dev_net(dev);
7477 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7478 if (!net_eq(net, dev_net(iter->dev)))
7480 netdev_adjacent_sysfs_del(iter->dev, oldname,
7481 &iter->dev->adj_list.lower);
7482 netdev_adjacent_sysfs_add(iter->dev, dev,
7483 &iter->dev->adj_list.lower);
7486 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7487 if (!net_eq(net, dev_net(iter->dev)))
7489 netdev_adjacent_sysfs_del(iter->dev, oldname,
7490 &iter->dev->adj_list.upper);
7491 netdev_adjacent_sysfs_add(iter->dev, dev,
7492 &iter->dev->adj_list.upper);
7496 void *netdev_lower_dev_get_private(struct net_device *dev,
7497 struct net_device *lower_dev)
7499 struct netdev_adjacent *lower;
7503 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
7507 return lower->private;
7509 EXPORT_SYMBOL(netdev_lower_dev_get_private);
7512 int dev_get_nest_level(struct net_device *dev)
7514 struct net_device *lower = NULL;
7515 struct list_head *iter;
7521 netdev_for_each_lower_dev(dev, lower, iter) {
7522 nest = dev_get_nest_level(lower);
7523 if (max_nest < nest)
7527 return max_nest + 1;
7529 EXPORT_SYMBOL(dev_get_nest_level);
7532 * netdev_lower_change - Dispatch event about lower device state change
7533 * @lower_dev: device
7534 * @lower_state_info: state to dispatch
7536 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
7537 * The caller must hold the RTNL lock.
7539 void netdev_lower_state_changed(struct net_device *lower_dev,
7540 void *lower_state_info)
7542 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
7543 .info.dev = lower_dev,
7547 changelowerstate_info.lower_state_info = lower_state_info;
7548 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
7549 &changelowerstate_info.info);
7551 EXPORT_SYMBOL(netdev_lower_state_changed);
7553 static void dev_change_rx_flags(struct net_device *dev, int flags)
7555 const struct net_device_ops *ops = dev->netdev_ops;
7557 if (ops->ndo_change_rx_flags)
7558 ops->ndo_change_rx_flags(dev, flags);
7561 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
7563 unsigned int old_flags = dev->flags;
7569 dev->flags |= IFF_PROMISC;
7570 dev->promiscuity += inc;
7571 if (dev->promiscuity == 0) {
7574 * If inc causes overflow, untouch promisc and return error.
7577 dev->flags &= ~IFF_PROMISC;
7579 dev->promiscuity -= inc;
7580 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
7585 if (dev->flags != old_flags) {
7586 pr_info("device %s %s promiscuous mode\n",
7588 dev->flags & IFF_PROMISC ? "entered" : "left");
7589 if (audit_enabled) {
7590 current_uid_gid(&uid, &gid);
7591 audit_log(audit_context(), GFP_ATOMIC,
7592 AUDIT_ANOM_PROMISCUOUS,
7593 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
7594 dev->name, (dev->flags & IFF_PROMISC),
7595 (old_flags & IFF_PROMISC),
7596 from_kuid(&init_user_ns, audit_get_loginuid(current)),
7597 from_kuid(&init_user_ns, uid),
7598 from_kgid(&init_user_ns, gid),
7599 audit_get_sessionid(current));
7602 dev_change_rx_flags(dev, IFF_PROMISC);
7605 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
7610 * dev_set_promiscuity - update promiscuity count on a device
7614 * Add or remove promiscuity from a device. While the count in the device
7615 * remains above zero the interface remains promiscuous. Once it hits zero
7616 * the device reverts back to normal filtering operation. A negative inc
7617 * value is used to drop promiscuity on the device.
7618 * Return 0 if successful or a negative errno code on error.
7620 int dev_set_promiscuity(struct net_device *dev, int inc)
7622 unsigned int old_flags = dev->flags;
7625 err = __dev_set_promiscuity(dev, inc, true);
7628 if (dev->flags != old_flags)
7629 dev_set_rx_mode(dev);
7632 EXPORT_SYMBOL(dev_set_promiscuity);
7634 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
7636 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
7640 dev->flags |= IFF_ALLMULTI;
7641 dev->allmulti += inc;
7642 if (dev->allmulti == 0) {
7645 * If inc causes overflow, untouch allmulti and return error.
7648 dev->flags &= ~IFF_ALLMULTI;
7650 dev->allmulti -= inc;
7651 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
7656 if (dev->flags ^ old_flags) {
7657 dev_change_rx_flags(dev, IFF_ALLMULTI);
7658 dev_set_rx_mode(dev);
7660 __dev_notify_flags(dev, old_flags,
7661 dev->gflags ^ old_gflags);
7667 * dev_set_allmulti - update allmulti count on a device
7671 * Add or remove reception of all multicast frames to a device. While the
7672 * count in the device remains above zero the interface remains listening
7673 * to all interfaces. Once it hits zero the device reverts back to normal
7674 * filtering operation. A negative @inc value is used to drop the counter
7675 * when releasing a resource needing all multicasts.
7676 * Return 0 if successful or a negative errno code on error.
7679 int dev_set_allmulti(struct net_device *dev, int inc)
7681 return __dev_set_allmulti(dev, inc, true);
7683 EXPORT_SYMBOL(dev_set_allmulti);
7686 * Upload unicast and multicast address lists to device and
7687 * configure RX filtering. When the device doesn't support unicast
7688 * filtering it is put in promiscuous mode while unicast addresses
7691 void __dev_set_rx_mode(struct net_device *dev)
7693 const struct net_device_ops *ops = dev->netdev_ops;
7695 /* dev_open will call this function so the list will stay sane. */
7696 if (!(dev->flags&IFF_UP))
7699 if (!netif_device_present(dev))
7702 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
7703 /* Unicast addresses changes may only happen under the rtnl,
7704 * therefore calling __dev_set_promiscuity here is safe.
7706 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
7707 __dev_set_promiscuity(dev, 1, false);
7708 dev->uc_promisc = true;
7709 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
7710 __dev_set_promiscuity(dev, -1, false);
7711 dev->uc_promisc = false;
7715 if (ops->ndo_set_rx_mode)
7716 ops->ndo_set_rx_mode(dev);
7719 void dev_set_rx_mode(struct net_device *dev)
7721 netif_addr_lock_bh(dev);
7722 __dev_set_rx_mode(dev);
7723 netif_addr_unlock_bh(dev);
7727 * dev_get_flags - get flags reported to userspace
7730 * Get the combination of flag bits exported through APIs to userspace.
7732 unsigned int dev_get_flags(const struct net_device *dev)
7736 flags = (dev->flags & ~(IFF_PROMISC |
7741 (dev->gflags & (IFF_PROMISC |
7744 if (netif_running(dev)) {
7745 if (netif_oper_up(dev))
7746 flags |= IFF_RUNNING;
7747 if (netif_carrier_ok(dev))
7748 flags |= IFF_LOWER_UP;
7749 if (netif_dormant(dev))
7750 flags |= IFF_DORMANT;
7755 EXPORT_SYMBOL(dev_get_flags);
7757 int __dev_change_flags(struct net_device *dev, unsigned int flags,
7758 struct netlink_ext_ack *extack)
7760 unsigned int old_flags = dev->flags;
7766 * Set the flags on our device.
7769 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
7770 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
7772 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
7776 * Load in the correct multicast list now the flags have changed.
7779 if ((old_flags ^ flags) & IFF_MULTICAST)
7780 dev_change_rx_flags(dev, IFF_MULTICAST);
7782 dev_set_rx_mode(dev);
7785 * Have we downed the interface. We handle IFF_UP ourselves
7786 * according to user attempts to set it, rather than blindly
7791 if ((old_flags ^ flags) & IFF_UP) {
7792 if (old_flags & IFF_UP)
7795 ret = __dev_open(dev, extack);
7798 if ((flags ^ dev->gflags) & IFF_PROMISC) {
7799 int inc = (flags & IFF_PROMISC) ? 1 : -1;
7800 unsigned int old_flags = dev->flags;
7802 dev->gflags ^= IFF_PROMISC;
7804 if (__dev_set_promiscuity(dev, inc, false) >= 0)
7805 if (dev->flags != old_flags)
7806 dev_set_rx_mode(dev);
7809 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
7810 * is important. Some (broken) drivers set IFF_PROMISC, when
7811 * IFF_ALLMULTI is requested not asking us and not reporting.
7813 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
7814 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
7816 dev->gflags ^= IFF_ALLMULTI;
7817 __dev_set_allmulti(dev, inc, false);
7823 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
7824 unsigned int gchanges)
7826 unsigned int changes = dev->flags ^ old_flags;
7829 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
7831 if (changes & IFF_UP) {
7832 if (dev->flags & IFF_UP)
7833 call_netdevice_notifiers(NETDEV_UP, dev);
7835 call_netdevice_notifiers(NETDEV_DOWN, dev);
7838 if (dev->flags & IFF_UP &&
7839 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
7840 struct netdev_notifier_change_info change_info = {
7844 .flags_changed = changes,
7847 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
7852 * dev_change_flags - change device settings
7854 * @flags: device state flags
7855 * @extack: netlink extended ack
7857 * Change settings on device based state flags. The flags are
7858 * in the userspace exported format.
7860 int dev_change_flags(struct net_device *dev, unsigned int flags,
7861 struct netlink_ext_ack *extack)
7864 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
7866 ret = __dev_change_flags(dev, flags, extack);
7870 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
7871 __dev_notify_flags(dev, old_flags, changes);
7874 EXPORT_SYMBOL(dev_change_flags);
7876 int __dev_set_mtu(struct net_device *dev, int new_mtu)
7878 const struct net_device_ops *ops = dev->netdev_ops;
7880 if (ops->ndo_change_mtu)
7881 return ops->ndo_change_mtu(dev, new_mtu);
7886 EXPORT_SYMBOL(__dev_set_mtu);
7889 * dev_set_mtu_ext - Change maximum transfer unit
7891 * @new_mtu: new transfer unit
7892 * @extack: netlink extended ack
7894 * Change the maximum transfer size of the network device.
7896 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
7897 struct netlink_ext_ack *extack)
7901 if (new_mtu == dev->mtu)
7904 /* MTU must be positive, and in range */
7905 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
7906 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
7910 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
7911 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
7915 if (!netif_device_present(dev))
7918 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
7919 err = notifier_to_errno(err);
7923 orig_mtu = dev->mtu;
7924 err = __dev_set_mtu(dev, new_mtu);
7927 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7929 err = notifier_to_errno(err);
7931 /* setting mtu back and notifying everyone again,
7932 * so that they have a chance to revert changes.
7934 __dev_set_mtu(dev, orig_mtu);
7935 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7942 int dev_set_mtu(struct net_device *dev, int new_mtu)
7944 struct netlink_ext_ack extack;
7947 memset(&extack, 0, sizeof(extack));
7948 err = dev_set_mtu_ext(dev, new_mtu, &extack);
7949 if (err && extack._msg)
7950 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
7953 EXPORT_SYMBOL(dev_set_mtu);
7956 * dev_change_tx_queue_len - Change TX queue length of a netdevice
7958 * @new_len: new tx queue length
7960 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
7962 unsigned int orig_len = dev->tx_queue_len;
7965 if (new_len != (unsigned int)new_len)
7968 if (new_len != orig_len) {
7969 dev->tx_queue_len = new_len;
7970 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
7971 res = notifier_to_errno(res);
7974 res = dev_qdisc_change_tx_queue_len(dev);
7982 netdev_err(dev, "refused to change device tx_queue_len\n");
7983 dev->tx_queue_len = orig_len;
7988 * dev_set_group - Change group this device belongs to
7990 * @new_group: group this device should belong to
7992 void dev_set_group(struct net_device *dev, int new_group)
7994 dev->group = new_group;
7996 EXPORT_SYMBOL(dev_set_group);
7999 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8001 * @addr: new address
8002 * @extack: netlink extended ack
8004 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8005 struct netlink_ext_ack *extack)
8007 struct netdev_notifier_pre_changeaddr_info info = {
8009 .info.extack = extack,
8014 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8015 return notifier_to_errno(rc);
8017 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8020 * dev_set_mac_address - Change Media Access Control Address
8023 * @extack: netlink extended ack
8025 * Change the hardware (MAC) address of the device
8027 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8028 struct netlink_ext_ack *extack)
8030 const struct net_device_ops *ops = dev->netdev_ops;
8033 if (!ops->ndo_set_mac_address)
8035 if (sa->sa_family != dev->type)
8037 if (!netif_device_present(dev))
8039 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8042 err = ops->ndo_set_mac_address(dev, sa);
8045 dev->addr_assign_type = NET_ADDR_SET;
8046 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8047 add_device_randomness(dev->dev_addr, dev->addr_len);
8050 EXPORT_SYMBOL(dev_set_mac_address);
8053 * dev_change_carrier - Change device carrier
8055 * @new_carrier: new value
8057 * Change device carrier
8059 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8061 const struct net_device_ops *ops = dev->netdev_ops;
8063 if (!ops->ndo_change_carrier)
8065 if (!netif_device_present(dev))
8067 return ops->ndo_change_carrier(dev, new_carrier);
8069 EXPORT_SYMBOL(dev_change_carrier);
8072 * dev_get_phys_port_id - Get device physical port ID
8076 * Get device physical port ID
8078 int dev_get_phys_port_id(struct net_device *dev,
8079 struct netdev_phys_item_id *ppid)
8081 const struct net_device_ops *ops = dev->netdev_ops;
8083 if (!ops->ndo_get_phys_port_id)
8085 return ops->ndo_get_phys_port_id(dev, ppid);
8087 EXPORT_SYMBOL(dev_get_phys_port_id);
8090 * dev_get_phys_port_name - Get device physical port name
8093 * @len: limit of bytes to copy to name
8095 * Get device physical port name
8097 int dev_get_phys_port_name(struct net_device *dev,
8098 char *name, size_t len)
8100 const struct net_device_ops *ops = dev->netdev_ops;
8103 if (ops->ndo_get_phys_port_name) {
8104 err = ops->ndo_get_phys_port_name(dev, name, len);
8105 if (err != -EOPNOTSUPP)
8108 return devlink_compat_phys_port_name_get(dev, name, len);
8110 EXPORT_SYMBOL(dev_get_phys_port_name);
8113 * dev_get_port_parent_id - Get the device's port parent identifier
8114 * @dev: network device
8115 * @ppid: pointer to a storage for the port's parent identifier
8116 * @recurse: allow/disallow recursion to lower devices
8118 * Get the devices's port parent identifier
8120 int dev_get_port_parent_id(struct net_device *dev,
8121 struct netdev_phys_item_id *ppid,
8124 const struct net_device_ops *ops = dev->netdev_ops;
8125 struct netdev_phys_item_id first = { };
8126 struct net_device *lower_dev;
8127 struct list_head *iter;
8130 if (ops->ndo_get_port_parent_id) {
8131 err = ops->ndo_get_port_parent_id(dev, ppid);
8132 if (err != -EOPNOTSUPP)
8136 err = devlink_compat_switch_id_get(dev, ppid);
8137 if (!err || err != -EOPNOTSUPP)
8143 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8144 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8149 else if (memcmp(&first, ppid, sizeof(*ppid)))
8155 EXPORT_SYMBOL(dev_get_port_parent_id);
8158 * netdev_port_same_parent_id - Indicate if two network devices have
8159 * the same port parent identifier
8160 * @a: first network device
8161 * @b: second network device
8163 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8165 struct netdev_phys_item_id a_id = { };
8166 struct netdev_phys_item_id b_id = { };
8168 if (dev_get_port_parent_id(a, &a_id, true) ||
8169 dev_get_port_parent_id(b, &b_id, true))
8172 return netdev_phys_item_id_same(&a_id, &b_id);
8174 EXPORT_SYMBOL(netdev_port_same_parent_id);
8177 * dev_change_proto_down - update protocol port state information
8179 * @proto_down: new value
8181 * This info can be used by switch drivers to set the phys state of the
8184 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8186 const struct net_device_ops *ops = dev->netdev_ops;
8188 if (!ops->ndo_change_proto_down)
8190 if (!netif_device_present(dev))
8192 return ops->ndo_change_proto_down(dev, proto_down);
8194 EXPORT_SYMBOL(dev_change_proto_down);
8197 * dev_change_proto_down_generic - generic implementation for
8198 * ndo_change_proto_down that sets carrier according to
8202 * @proto_down: new value
8204 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8207 netif_carrier_off(dev);
8209 netif_carrier_on(dev);
8210 dev->proto_down = proto_down;
8213 EXPORT_SYMBOL(dev_change_proto_down_generic);
8215 u32 __dev_xdp_query(struct net_device *dev, bpf_op_t bpf_op,
8216 enum bpf_netdev_command cmd)
8218 struct netdev_bpf xdp;
8223 memset(&xdp, 0, sizeof(xdp));
8226 /* Query must always succeed. */
8227 WARN_ON(bpf_op(dev, &xdp) < 0 && cmd == XDP_QUERY_PROG);
8232 static int dev_xdp_install(struct net_device *dev, bpf_op_t bpf_op,
8233 struct netlink_ext_ack *extack, u32 flags,
8234 struct bpf_prog *prog)
8236 struct netdev_bpf xdp;
8238 memset(&xdp, 0, sizeof(xdp));
8239 if (flags & XDP_FLAGS_HW_MODE)
8240 xdp.command = XDP_SETUP_PROG_HW;
8242 xdp.command = XDP_SETUP_PROG;
8243 xdp.extack = extack;
8247 return bpf_op(dev, &xdp);
8250 static void dev_xdp_uninstall(struct net_device *dev)
8252 struct netdev_bpf xdp;
8255 /* Remove generic XDP */
8256 WARN_ON(dev_xdp_install(dev, generic_xdp_install, NULL, 0, NULL));
8258 /* Remove from the driver */
8259 ndo_bpf = dev->netdev_ops->ndo_bpf;
8263 memset(&xdp, 0, sizeof(xdp));
8264 xdp.command = XDP_QUERY_PROG;
8265 WARN_ON(ndo_bpf(dev, &xdp));
8267 WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
8270 /* Remove HW offload */
8271 memset(&xdp, 0, sizeof(xdp));
8272 xdp.command = XDP_QUERY_PROG_HW;
8273 if (!ndo_bpf(dev, &xdp) && xdp.prog_id)
8274 WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
8279 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
8281 * @extack: netlink extended ack
8282 * @fd: new program fd or negative value to clear
8283 * @flags: xdp-related flags
8285 * Set or clear a bpf program for a device
8287 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
8290 const struct net_device_ops *ops = dev->netdev_ops;
8291 enum bpf_netdev_command query;
8292 struct bpf_prog *prog = NULL;
8293 bpf_op_t bpf_op, bpf_chk;
8299 offload = flags & XDP_FLAGS_HW_MODE;
8300 query = offload ? XDP_QUERY_PROG_HW : XDP_QUERY_PROG;
8302 bpf_op = bpf_chk = ops->ndo_bpf;
8303 if (!bpf_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE))) {
8304 NL_SET_ERR_MSG(extack, "underlying driver does not support XDP in native mode");
8307 if (!bpf_op || (flags & XDP_FLAGS_SKB_MODE))
8308 bpf_op = generic_xdp_install;
8309 if (bpf_op == bpf_chk)
8310 bpf_chk = generic_xdp_install;
8315 if (!offload && __dev_xdp_query(dev, bpf_chk, XDP_QUERY_PROG)) {
8316 NL_SET_ERR_MSG(extack, "native and generic XDP can't be active at the same time");
8320 prog_id = __dev_xdp_query(dev, bpf_op, query);
8321 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && prog_id) {
8322 NL_SET_ERR_MSG(extack, "XDP program already attached");
8326 prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
8327 bpf_op == ops->ndo_bpf);
8329 return PTR_ERR(prog);
8331 if (!offload && bpf_prog_is_dev_bound(prog->aux)) {
8332 NL_SET_ERR_MSG(extack, "using device-bound program without HW_MODE flag is not supported");
8337 if (prog->aux->id == prog_id) {
8342 if (!__dev_xdp_query(dev, bpf_op, query))
8346 err = dev_xdp_install(dev, bpf_op, extack, flags, prog);
8347 if (err < 0 && prog)
8354 * dev_new_index - allocate an ifindex
8355 * @net: the applicable net namespace
8357 * Returns a suitable unique value for a new device interface
8358 * number. The caller must hold the rtnl semaphore or the
8359 * dev_base_lock to be sure it remains unique.
8361 static int dev_new_index(struct net *net)
8363 int ifindex = net->ifindex;
8368 if (!__dev_get_by_index(net, ifindex))
8369 return net->ifindex = ifindex;
8373 /* Delayed registration/unregisteration */
8374 static LIST_HEAD(net_todo_list);
8375 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
8377 static void net_set_todo(struct net_device *dev)
8379 list_add_tail(&dev->todo_list, &net_todo_list);
8380 dev_net(dev)->dev_unreg_count++;
8383 static void rollback_registered_many(struct list_head *head)
8385 struct net_device *dev, *tmp;
8386 LIST_HEAD(close_head);
8388 BUG_ON(dev_boot_phase);
8391 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
8392 /* Some devices call without registering
8393 * for initialization unwind. Remove those
8394 * devices and proceed with the remaining.
8396 if (dev->reg_state == NETREG_UNINITIALIZED) {
8397 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
8401 list_del(&dev->unreg_list);
8404 dev->dismantle = true;
8405 BUG_ON(dev->reg_state != NETREG_REGISTERED);
8408 /* If device is running, close it first. */
8409 list_for_each_entry(dev, head, unreg_list)
8410 list_add_tail(&dev->close_list, &close_head);
8411 dev_close_many(&close_head, true);
8413 list_for_each_entry(dev, head, unreg_list) {
8414 /* And unlink it from device chain. */
8415 unlist_netdevice(dev);
8417 dev->reg_state = NETREG_UNREGISTERING;
8419 flush_all_backlogs();
8423 list_for_each_entry(dev, head, unreg_list) {
8424 struct sk_buff *skb = NULL;
8426 /* Shutdown queueing discipline. */
8429 dev_xdp_uninstall(dev);
8431 /* Notify protocols, that we are about to destroy
8432 * this device. They should clean all the things.
8434 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
8436 if (!dev->rtnl_link_ops ||
8437 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
8438 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
8439 GFP_KERNEL, NULL, 0);
8442 * Flush the unicast and multicast chains
8447 if (dev->netdev_ops->ndo_uninit)
8448 dev->netdev_ops->ndo_uninit(dev);
8451 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
8453 /* Notifier chain MUST detach us all upper devices. */
8454 WARN_ON(netdev_has_any_upper_dev(dev));
8455 WARN_ON(netdev_has_any_lower_dev(dev));
8457 /* Remove entries from kobject tree */
8458 netdev_unregister_kobject(dev);
8460 /* Remove XPS queueing entries */
8461 netif_reset_xps_queues_gt(dev, 0);
8467 list_for_each_entry(dev, head, unreg_list)
8471 static void rollback_registered(struct net_device *dev)
8475 list_add(&dev->unreg_list, &single);
8476 rollback_registered_many(&single);
8480 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
8481 struct net_device *upper, netdev_features_t features)
8483 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
8484 netdev_features_t feature;
8487 for_each_netdev_feature(upper_disables, feature_bit) {
8488 feature = __NETIF_F_BIT(feature_bit);
8489 if (!(upper->wanted_features & feature)
8490 && (features & feature)) {
8491 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
8492 &feature, upper->name);
8493 features &= ~feature;
8500 static void netdev_sync_lower_features(struct net_device *upper,
8501 struct net_device *lower, netdev_features_t features)
8503 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
8504 netdev_features_t feature;
8507 for_each_netdev_feature(upper_disables, feature_bit) {
8508 feature = __NETIF_F_BIT(feature_bit);
8509 if (!(features & feature) && (lower->features & feature)) {
8510 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
8511 &feature, lower->name);
8512 lower->wanted_features &= ~feature;
8513 netdev_update_features(lower);
8515 if (unlikely(lower->features & feature))
8516 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
8517 &feature, lower->name);
8522 static netdev_features_t netdev_fix_features(struct net_device *dev,
8523 netdev_features_t features)
8525 /* Fix illegal checksum combinations */
8526 if ((features & NETIF_F_HW_CSUM) &&
8527 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
8528 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
8529 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
8532 /* TSO requires that SG is present as well. */
8533 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
8534 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
8535 features &= ~NETIF_F_ALL_TSO;
8538 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
8539 !(features & NETIF_F_IP_CSUM)) {
8540 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
8541 features &= ~NETIF_F_TSO;
8542 features &= ~NETIF_F_TSO_ECN;
8545 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
8546 !(features & NETIF_F_IPV6_CSUM)) {
8547 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
8548 features &= ~NETIF_F_TSO6;
8551 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
8552 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
8553 features &= ~NETIF_F_TSO_MANGLEID;
8555 /* TSO ECN requires that TSO is present as well. */
8556 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
8557 features &= ~NETIF_F_TSO_ECN;
8559 /* Software GSO depends on SG. */
8560 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
8561 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
8562 features &= ~NETIF_F_GSO;
8565 /* GSO partial features require GSO partial be set */
8566 if ((features & dev->gso_partial_features) &&
8567 !(features & NETIF_F_GSO_PARTIAL)) {
8569 "Dropping partially supported GSO features since no GSO partial.\n");
8570 features &= ~dev->gso_partial_features;
8573 if (!(features & NETIF_F_RXCSUM)) {
8574 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
8575 * successfully merged by hardware must also have the
8576 * checksum verified by hardware. If the user does not
8577 * want to enable RXCSUM, logically, we should disable GRO_HW.
8579 if (features & NETIF_F_GRO_HW) {
8580 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
8581 features &= ~NETIF_F_GRO_HW;
8585 /* LRO/HW-GRO features cannot be combined with RX-FCS */
8586 if (features & NETIF_F_RXFCS) {
8587 if (features & NETIF_F_LRO) {
8588 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
8589 features &= ~NETIF_F_LRO;
8592 if (features & NETIF_F_GRO_HW) {
8593 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
8594 features &= ~NETIF_F_GRO_HW;
8601 int __netdev_update_features(struct net_device *dev)
8603 struct net_device *upper, *lower;
8604 netdev_features_t features;
8605 struct list_head *iter;
8610 features = netdev_get_wanted_features(dev);
8612 if (dev->netdev_ops->ndo_fix_features)
8613 features = dev->netdev_ops->ndo_fix_features(dev, features);
8615 /* driver might be less strict about feature dependencies */
8616 features = netdev_fix_features(dev, features);
8618 /* some features can't be enabled if they're off an an upper device */
8619 netdev_for_each_upper_dev_rcu(dev, upper, iter)
8620 features = netdev_sync_upper_features(dev, upper, features);
8622 if (dev->features == features)
8625 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
8626 &dev->features, &features);
8628 if (dev->netdev_ops->ndo_set_features)
8629 err = dev->netdev_ops->ndo_set_features(dev, features);
8633 if (unlikely(err < 0)) {
8635 "set_features() failed (%d); wanted %pNF, left %pNF\n",
8636 err, &features, &dev->features);
8637 /* return non-0 since some features might have changed and
8638 * it's better to fire a spurious notification than miss it
8644 /* some features must be disabled on lower devices when disabled
8645 * on an upper device (think: bonding master or bridge)
8647 netdev_for_each_lower_dev(dev, lower, iter)
8648 netdev_sync_lower_features(dev, lower, features);
8651 netdev_features_t diff = features ^ dev->features;
8653 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
8654 /* udp_tunnel_{get,drop}_rx_info both need
8655 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
8656 * device, or they won't do anything.
8657 * Thus we need to update dev->features
8658 * *before* calling udp_tunnel_get_rx_info,
8659 * but *after* calling udp_tunnel_drop_rx_info.
8661 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
8662 dev->features = features;
8663 udp_tunnel_get_rx_info(dev);
8665 udp_tunnel_drop_rx_info(dev);
8669 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
8670 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
8671 dev->features = features;
8672 err |= vlan_get_rx_ctag_filter_info(dev);
8674 vlan_drop_rx_ctag_filter_info(dev);
8678 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
8679 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
8680 dev->features = features;
8681 err |= vlan_get_rx_stag_filter_info(dev);
8683 vlan_drop_rx_stag_filter_info(dev);
8687 dev->features = features;
8690 return err < 0 ? 0 : 1;
8694 * netdev_update_features - recalculate device features
8695 * @dev: the device to check
8697 * Recalculate dev->features set and send notifications if it
8698 * has changed. Should be called after driver or hardware dependent
8699 * conditions might have changed that influence the features.
8701 void netdev_update_features(struct net_device *dev)
8703 if (__netdev_update_features(dev))
8704 netdev_features_change(dev);
8706 EXPORT_SYMBOL(netdev_update_features);
8709 * netdev_change_features - recalculate device features
8710 * @dev: the device to check
8712 * Recalculate dev->features set and send notifications even
8713 * if they have not changed. Should be called instead of
8714 * netdev_update_features() if also dev->vlan_features might
8715 * have changed to allow the changes to be propagated to stacked
8718 void netdev_change_features(struct net_device *dev)
8720 __netdev_update_features(dev);
8721 netdev_features_change(dev);
8723 EXPORT_SYMBOL(netdev_change_features);
8726 * netif_stacked_transfer_operstate - transfer operstate
8727 * @rootdev: the root or lower level device to transfer state from
8728 * @dev: the device to transfer operstate to
8730 * Transfer operational state from root to device. This is normally
8731 * called when a stacking relationship exists between the root
8732 * device and the device(a leaf device).
8734 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
8735 struct net_device *dev)
8737 if (rootdev->operstate == IF_OPER_DORMANT)
8738 netif_dormant_on(dev);
8740 netif_dormant_off(dev);
8742 if (netif_carrier_ok(rootdev))
8743 netif_carrier_on(dev);
8745 netif_carrier_off(dev);
8747 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
8749 static int netif_alloc_rx_queues(struct net_device *dev)
8751 unsigned int i, count = dev->num_rx_queues;
8752 struct netdev_rx_queue *rx;
8753 size_t sz = count * sizeof(*rx);
8758 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8764 for (i = 0; i < count; i++) {
8767 /* XDP RX-queue setup */
8768 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
8775 /* Rollback successful reg's and free other resources */
8777 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
8783 static void netif_free_rx_queues(struct net_device *dev)
8785 unsigned int i, count = dev->num_rx_queues;
8787 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
8791 for (i = 0; i < count; i++)
8792 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
8797 static void netdev_init_one_queue(struct net_device *dev,
8798 struct netdev_queue *queue, void *_unused)
8800 /* Initialize queue lock */
8801 spin_lock_init(&queue->_xmit_lock);
8802 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
8803 queue->xmit_lock_owner = -1;
8804 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
8807 dql_init(&queue->dql, HZ);
8811 static void netif_free_tx_queues(struct net_device *dev)
8816 static int netif_alloc_netdev_queues(struct net_device *dev)
8818 unsigned int count = dev->num_tx_queues;
8819 struct netdev_queue *tx;
8820 size_t sz = count * sizeof(*tx);
8822 if (count < 1 || count > 0xffff)
8825 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8831 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
8832 spin_lock_init(&dev->tx_global_lock);
8837 void netif_tx_stop_all_queues(struct net_device *dev)
8841 for (i = 0; i < dev->num_tx_queues; i++) {
8842 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
8844 netif_tx_stop_queue(txq);
8847 EXPORT_SYMBOL(netif_tx_stop_all_queues);
8850 * register_netdevice - register a network device
8851 * @dev: device to register
8853 * Take a completed network device structure and add it to the kernel
8854 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
8855 * chain. 0 is returned on success. A negative errno code is returned
8856 * on a failure to set up the device, or if the name is a duplicate.
8858 * Callers must hold the rtnl semaphore. You may want
8859 * register_netdev() instead of this.
8862 * The locking appears insufficient to guarantee two parallel registers
8863 * will not get the same name.
8866 int register_netdevice(struct net_device *dev)
8869 struct net *net = dev_net(dev);
8871 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
8872 NETDEV_FEATURE_COUNT);
8873 BUG_ON(dev_boot_phase);
8878 /* When net_device's are persistent, this will be fatal. */
8879 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
8882 spin_lock_init(&dev->addr_list_lock);
8883 netdev_set_addr_lockdep_class(dev);
8885 ret = dev_get_valid_name(net, dev, dev->name);
8889 /* Init, if this function is available */
8890 if (dev->netdev_ops->ndo_init) {
8891 ret = dev->netdev_ops->ndo_init(dev);
8899 if (((dev->hw_features | dev->features) &
8900 NETIF_F_HW_VLAN_CTAG_FILTER) &&
8901 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
8902 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
8903 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
8910 dev->ifindex = dev_new_index(net);
8911 else if (__dev_get_by_index(net, dev->ifindex))
8914 /* Transfer changeable features to wanted_features and enable
8915 * software offloads (GSO and GRO).
8917 dev->hw_features |= NETIF_F_SOFT_FEATURES;
8918 dev->features |= NETIF_F_SOFT_FEATURES;
8920 if (dev->netdev_ops->ndo_udp_tunnel_add) {
8921 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
8922 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
8925 dev->wanted_features = dev->features & dev->hw_features;
8927 if (!(dev->flags & IFF_LOOPBACK))
8928 dev->hw_features |= NETIF_F_NOCACHE_COPY;
8930 /* If IPv4 TCP segmentation offload is supported we should also
8931 * allow the device to enable segmenting the frame with the option
8932 * of ignoring a static IP ID value. This doesn't enable the
8933 * feature itself but allows the user to enable it later.
8935 if (dev->hw_features & NETIF_F_TSO)
8936 dev->hw_features |= NETIF_F_TSO_MANGLEID;
8937 if (dev->vlan_features & NETIF_F_TSO)
8938 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
8939 if (dev->mpls_features & NETIF_F_TSO)
8940 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
8941 if (dev->hw_enc_features & NETIF_F_TSO)
8942 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
8944 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
8946 dev->vlan_features |= NETIF_F_HIGHDMA;
8948 /* Make NETIF_F_SG inheritable to tunnel devices.
8950 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
8952 /* Make NETIF_F_SG inheritable to MPLS.
8954 dev->mpls_features |= NETIF_F_SG;
8956 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
8957 ret = notifier_to_errno(ret);
8961 ret = netdev_register_kobject(dev);
8964 dev->reg_state = NETREG_REGISTERED;
8966 __netdev_update_features(dev);
8969 * Default initial state at registry is that the
8970 * device is present.
8973 set_bit(__LINK_STATE_PRESENT, &dev->state);
8975 linkwatch_init_dev(dev);
8977 dev_init_scheduler(dev);
8979 list_netdevice(dev);
8980 add_device_randomness(dev->dev_addr, dev->addr_len);
8982 /* If the device has permanent device address, driver should
8983 * set dev_addr and also addr_assign_type should be set to
8984 * NET_ADDR_PERM (default value).
8986 if (dev->addr_assign_type == NET_ADDR_PERM)
8987 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
8989 /* Notify protocols, that a new device appeared. */
8990 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
8991 ret = notifier_to_errno(ret);
8993 rollback_registered(dev);
8996 dev->reg_state = NETREG_UNREGISTERED;
8999 * Prevent userspace races by waiting until the network
9000 * device is fully setup before sending notifications.
9002 if (!dev->rtnl_link_ops ||
9003 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9004 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9010 if (dev->netdev_ops->ndo_uninit)
9011 dev->netdev_ops->ndo_uninit(dev);
9012 if (dev->priv_destructor)
9013 dev->priv_destructor(dev);
9016 EXPORT_SYMBOL(register_netdevice);
9019 * init_dummy_netdev - init a dummy network device for NAPI
9020 * @dev: device to init
9022 * This takes a network device structure and initialize the minimum
9023 * amount of fields so it can be used to schedule NAPI polls without
9024 * registering a full blown interface. This is to be used by drivers
9025 * that need to tie several hardware interfaces to a single NAPI
9026 * poll scheduler due to HW limitations.
9028 int init_dummy_netdev(struct net_device *dev)
9030 /* Clear everything. Note we don't initialize spinlocks
9031 * are they aren't supposed to be taken by any of the
9032 * NAPI code and this dummy netdev is supposed to be
9033 * only ever used for NAPI polls
9035 memset(dev, 0, sizeof(struct net_device));
9037 /* make sure we BUG if trying to hit standard
9038 * register/unregister code path
9040 dev->reg_state = NETREG_DUMMY;
9042 /* NAPI wants this */
9043 INIT_LIST_HEAD(&dev->napi_list);
9045 /* a dummy interface is started by default */
9046 set_bit(__LINK_STATE_PRESENT, &dev->state);
9047 set_bit(__LINK_STATE_START, &dev->state);
9049 /* napi_busy_loop stats accounting wants this */
9050 dev_net_set(dev, &init_net);
9052 /* Note : We dont allocate pcpu_refcnt for dummy devices,
9053 * because users of this 'device' dont need to change
9059 EXPORT_SYMBOL_GPL(init_dummy_netdev);
9063 * register_netdev - register a network device
9064 * @dev: device to register
9066 * Take a completed network device structure and add it to the kernel
9067 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9068 * chain. 0 is returned on success. A negative errno code is returned
9069 * on a failure to set up the device, or if the name is a duplicate.
9071 * This is a wrapper around register_netdevice that takes the rtnl semaphore
9072 * and expands the device name if you passed a format string to
9075 int register_netdev(struct net_device *dev)
9079 if (rtnl_lock_killable())
9081 err = register_netdevice(dev);
9085 EXPORT_SYMBOL(register_netdev);
9087 int netdev_refcnt_read(const struct net_device *dev)
9091 for_each_possible_cpu(i)
9092 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
9095 EXPORT_SYMBOL(netdev_refcnt_read);
9098 * netdev_wait_allrefs - wait until all references are gone.
9099 * @dev: target net_device
9101 * This is called when unregistering network devices.
9103 * Any protocol or device that holds a reference should register
9104 * for netdevice notification, and cleanup and put back the
9105 * reference if they receive an UNREGISTER event.
9106 * We can get stuck here if buggy protocols don't correctly
9109 static void netdev_wait_allrefs(struct net_device *dev)
9111 unsigned long rebroadcast_time, warning_time;
9114 linkwatch_forget_dev(dev);
9116 rebroadcast_time = warning_time = jiffies;
9117 refcnt = netdev_refcnt_read(dev);
9119 while (refcnt != 0) {
9120 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
9123 /* Rebroadcast unregister notification */
9124 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9130 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
9132 /* We must not have linkwatch events
9133 * pending on unregister. If this
9134 * happens, we simply run the queue
9135 * unscheduled, resulting in a noop
9138 linkwatch_run_queue();
9143 rebroadcast_time = jiffies;
9148 refcnt = netdev_refcnt_read(dev);
9150 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
9151 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
9153 warning_time = jiffies;
9162 * register_netdevice(x1);
9163 * register_netdevice(x2);
9165 * unregister_netdevice(y1);
9166 * unregister_netdevice(y2);
9172 * We are invoked by rtnl_unlock().
9173 * This allows us to deal with problems:
9174 * 1) We can delete sysfs objects which invoke hotplug
9175 * without deadlocking with linkwatch via keventd.
9176 * 2) Since we run with the RTNL semaphore not held, we can sleep
9177 * safely in order to wait for the netdev refcnt to drop to zero.
9179 * We must not return until all unregister events added during
9180 * the interval the lock was held have been completed.
9182 void netdev_run_todo(void)
9184 struct list_head list;
9186 /* Snapshot list, allow later requests */
9187 list_replace_init(&net_todo_list, &list);
9192 /* Wait for rcu callbacks to finish before next phase */
9193 if (!list_empty(&list))
9196 while (!list_empty(&list)) {
9197 struct net_device *dev
9198 = list_first_entry(&list, struct net_device, todo_list);
9199 list_del(&dev->todo_list);
9201 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
9202 pr_err("network todo '%s' but state %d\n",
9203 dev->name, dev->reg_state);
9208 dev->reg_state = NETREG_UNREGISTERED;
9210 netdev_wait_allrefs(dev);
9213 BUG_ON(netdev_refcnt_read(dev));
9214 BUG_ON(!list_empty(&dev->ptype_all));
9215 BUG_ON(!list_empty(&dev->ptype_specific));
9216 WARN_ON(rcu_access_pointer(dev->ip_ptr));
9217 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
9218 #if IS_ENABLED(CONFIG_DECNET)
9219 WARN_ON(dev->dn_ptr);
9221 if (dev->priv_destructor)
9222 dev->priv_destructor(dev);
9223 if (dev->needs_free_netdev)
9226 /* Report a network device has been unregistered */
9228 dev_net(dev)->dev_unreg_count--;
9230 wake_up(&netdev_unregistering_wq);
9232 /* Free network device */
9233 kobject_put(&dev->dev.kobj);
9237 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
9238 * all the same fields in the same order as net_device_stats, with only
9239 * the type differing, but rtnl_link_stats64 may have additional fields
9240 * at the end for newer counters.
9242 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
9243 const struct net_device_stats *netdev_stats)
9245 #if BITS_PER_LONG == 64
9246 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
9247 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
9248 /* zero out counters that only exist in rtnl_link_stats64 */
9249 memset((char *)stats64 + sizeof(*netdev_stats), 0,
9250 sizeof(*stats64) - sizeof(*netdev_stats));
9252 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
9253 const unsigned long *src = (const unsigned long *)netdev_stats;
9254 u64 *dst = (u64 *)stats64;
9256 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
9257 for (i = 0; i < n; i++)
9259 /* zero out counters that only exist in rtnl_link_stats64 */
9260 memset((char *)stats64 + n * sizeof(u64), 0,
9261 sizeof(*stats64) - n * sizeof(u64));
9264 EXPORT_SYMBOL(netdev_stats_to_stats64);
9267 * dev_get_stats - get network device statistics
9268 * @dev: device to get statistics from
9269 * @storage: place to store stats
9271 * Get network statistics from device. Return @storage.
9272 * The device driver may provide its own method by setting
9273 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
9274 * otherwise the internal statistics structure is used.
9276 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
9277 struct rtnl_link_stats64 *storage)
9279 const struct net_device_ops *ops = dev->netdev_ops;
9281 if (ops->ndo_get_stats64) {
9282 memset(storage, 0, sizeof(*storage));
9283 ops->ndo_get_stats64(dev, storage);
9284 } else if (ops->ndo_get_stats) {
9285 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
9287 netdev_stats_to_stats64(storage, &dev->stats);
9289 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
9290 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
9291 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
9294 EXPORT_SYMBOL(dev_get_stats);
9296 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
9298 struct netdev_queue *queue = dev_ingress_queue(dev);
9300 #ifdef CONFIG_NET_CLS_ACT
9303 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
9306 netdev_init_one_queue(dev, queue, NULL);
9307 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
9308 queue->qdisc_sleeping = &noop_qdisc;
9309 rcu_assign_pointer(dev->ingress_queue, queue);
9314 static const struct ethtool_ops default_ethtool_ops;
9316 void netdev_set_default_ethtool_ops(struct net_device *dev,
9317 const struct ethtool_ops *ops)
9319 if (dev->ethtool_ops == &default_ethtool_ops)
9320 dev->ethtool_ops = ops;
9322 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
9324 void netdev_freemem(struct net_device *dev)
9326 char *addr = (char *)dev - dev->padded;
9332 * alloc_netdev_mqs - allocate network device
9333 * @sizeof_priv: size of private data to allocate space for
9334 * @name: device name format string
9335 * @name_assign_type: origin of device name
9336 * @setup: callback to initialize device
9337 * @txqs: the number of TX subqueues to allocate
9338 * @rxqs: the number of RX subqueues to allocate
9340 * Allocates a struct net_device with private data area for driver use
9341 * and performs basic initialization. Also allocates subqueue structs
9342 * for each queue on the device.
9344 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
9345 unsigned char name_assign_type,
9346 void (*setup)(struct net_device *),
9347 unsigned int txqs, unsigned int rxqs)
9349 struct net_device *dev;
9350 unsigned int alloc_size;
9351 struct net_device *p;
9353 BUG_ON(strlen(name) >= sizeof(dev->name));
9356 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
9361 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
9365 alloc_size = sizeof(struct net_device);
9367 /* ensure 32-byte alignment of private area */
9368 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
9369 alloc_size += sizeof_priv;
9371 /* ensure 32-byte alignment of whole construct */
9372 alloc_size += NETDEV_ALIGN - 1;
9374 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9378 dev = PTR_ALIGN(p, NETDEV_ALIGN);
9379 dev->padded = (char *)dev - (char *)p;
9381 dev->pcpu_refcnt = alloc_percpu(int);
9382 if (!dev->pcpu_refcnt)
9385 if (dev_addr_init(dev))
9391 dev_net_set(dev, &init_net);
9393 dev->gso_max_size = GSO_MAX_SIZE;
9394 dev->gso_max_segs = GSO_MAX_SEGS;
9395 dev->upper_level = 1;
9396 dev->lower_level = 1;
9398 INIT_LIST_HEAD(&dev->napi_list);
9399 INIT_LIST_HEAD(&dev->unreg_list);
9400 INIT_LIST_HEAD(&dev->close_list);
9401 INIT_LIST_HEAD(&dev->link_watch_list);
9402 INIT_LIST_HEAD(&dev->adj_list.upper);
9403 INIT_LIST_HEAD(&dev->adj_list.lower);
9404 INIT_LIST_HEAD(&dev->ptype_all);
9405 INIT_LIST_HEAD(&dev->ptype_specific);
9406 #ifdef CONFIG_NET_SCHED
9407 hash_init(dev->qdisc_hash);
9409 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
9412 if (!dev->tx_queue_len) {
9413 dev->priv_flags |= IFF_NO_QUEUE;
9414 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
9417 dev->num_tx_queues = txqs;
9418 dev->real_num_tx_queues = txqs;
9419 if (netif_alloc_netdev_queues(dev))
9422 dev->num_rx_queues = rxqs;
9423 dev->real_num_rx_queues = rxqs;
9424 if (netif_alloc_rx_queues(dev))
9427 strcpy(dev->name, name);
9428 dev->name_assign_type = name_assign_type;
9429 dev->group = INIT_NETDEV_GROUP;
9430 if (!dev->ethtool_ops)
9431 dev->ethtool_ops = &default_ethtool_ops;
9433 nf_hook_ingress_init(dev);
9442 free_percpu(dev->pcpu_refcnt);
9444 netdev_freemem(dev);
9447 EXPORT_SYMBOL(alloc_netdev_mqs);
9450 * free_netdev - free network device
9453 * This function does the last stage of destroying an allocated device
9454 * interface. The reference to the device object is released. If this
9455 * is the last reference then it will be freed.Must be called in process
9458 void free_netdev(struct net_device *dev)
9460 struct napi_struct *p, *n;
9463 netif_free_tx_queues(dev);
9464 netif_free_rx_queues(dev);
9466 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
9468 /* Flush device addresses */
9469 dev_addr_flush(dev);
9471 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
9474 free_percpu(dev->pcpu_refcnt);
9475 dev->pcpu_refcnt = NULL;
9477 /* Compatibility with error handling in drivers */
9478 if (dev->reg_state == NETREG_UNINITIALIZED) {
9479 netdev_freemem(dev);
9483 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
9484 dev->reg_state = NETREG_RELEASED;
9486 /* will free via device release */
9487 put_device(&dev->dev);
9489 EXPORT_SYMBOL(free_netdev);
9492 * synchronize_net - Synchronize with packet receive processing
9494 * Wait for packets currently being received to be done.
9495 * Does not block later packets from starting.
9497 void synchronize_net(void)
9500 if (rtnl_is_locked())
9501 synchronize_rcu_expedited();
9505 EXPORT_SYMBOL(synchronize_net);
9508 * unregister_netdevice_queue - remove device from the kernel
9512 * This function shuts down a device interface and removes it
9513 * from the kernel tables.
9514 * If head not NULL, device is queued to be unregistered later.
9516 * Callers must hold the rtnl semaphore. You may want
9517 * unregister_netdev() instead of this.
9520 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
9525 list_move_tail(&dev->unreg_list, head);
9527 rollback_registered(dev);
9528 /* Finish processing unregister after unlock */
9532 EXPORT_SYMBOL(unregister_netdevice_queue);
9535 * unregister_netdevice_many - unregister many devices
9536 * @head: list of devices
9538 * Note: As most callers use a stack allocated list_head,
9539 * we force a list_del() to make sure stack wont be corrupted later.
9541 void unregister_netdevice_many(struct list_head *head)
9543 struct net_device *dev;
9545 if (!list_empty(head)) {
9546 rollback_registered_many(head);
9547 list_for_each_entry(dev, head, unreg_list)
9552 EXPORT_SYMBOL(unregister_netdevice_many);
9555 * unregister_netdev - remove device from the kernel
9558 * This function shuts down a device interface and removes it
9559 * from the kernel tables.
9561 * This is just a wrapper for unregister_netdevice that takes
9562 * the rtnl semaphore. In general you want to use this and not
9563 * unregister_netdevice.
9565 void unregister_netdev(struct net_device *dev)
9568 unregister_netdevice(dev);
9571 EXPORT_SYMBOL(unregister_netdev);
9574 * dev_change_net_namespace - move device to different nethost namespace
9576 * @net: network namespace
9577 * @pat: If not NULL name pattern to try if the current device name
9578 * is already taken in the destination network namespace.
9580 * This function shuts down a device interface and moves it
9581 * to a new network namespace. On success 0 is returned, on
9582 * a failure a netagive errno code is returned.
9584 * Callers must hold the rtnl semaphore.
9587 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
9589 int err, new_nsid, new_ifindex;
9593 /* Don't allow namespace local devices to be moved. */
9595 if (dev->features & NETIF_F_NETNS_LOCAL)
9598 /* Ensure the device has been registrered */
9599 if (dev->reg_state != NETREG_REGISTERED)
9602 /* Get out if there is nothing todo */
9604 if (net_eq(dev_net(dev), net))
9607 /* Pick the destination device name, and ensure
9608 * we can use it in the destination network namespace.
9611 if (__dev_get_by_name(net, dev->name)) {
9612 /* We get here if we can't use the current device name */
9615 err = dev_get_valid_name(net, dev, pat);
9621 * And now a mini version of register_netdevice unregister_netdevice.
9624 /* If device is running close it first. */
9627 /* And unlink it from device chain */
9628 unlist_netdevice(dev);
9632 /* Shutdown queueing discipline. */
9635 /* Notify protocols, that we are about to destroy
9636 * this device. They should clean all the things.
9638 * Note that dev->reg_state stays at NETREG_REGISTERED.
9639 * This is wanted because this way 8021q and macvlan know
9640 * the device is just moving and can keep their slaves up.
9642 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9645 new_nsid = peernet2id_alloc(dev_net(dev), net);
9646 /* If there is an ifindex conflict assign a new one */
9647 if (__dev_get_by_index(net, dev->ifindex))
9648 new_ifindex = dev_new_index(net);
9650 new_ifindex = dev->ifindex;
9652 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
9656 * Flush the unicast and multicast chains
9661 /* Send a netdev-removed uevent to the old namespace */
9662 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
9663 netdev_adjacent_del_links(dev);
9665 /* Actually switch the network namespace */
9666 dev_net_set(dev, net);
9667 dev->ifindex = new_ifindex;
9669 /* Send a netdev-add uevent to the new namespace */
9670 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
9671 netdev_adjacent_add_links(dev);
9673 /* Fixup kobjects */
9674 err = device_rename(&dev->dev, dev->name);
9677 /* Add the device back in the hashes */
9678 list_netdevice(dev);
9680 /* Notify protocols, that a new device appeared. */
9681 call_netdevice_notifiers(NETDEV_REGISTER, dev);
9684 * Prevent userspace races by waiting until the network
9685 * device is fully setup before sending notifications.
9687 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9694 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
9696 static int dev_cpu_dead(unsigned int oldcpu)
9698 struct sk_buff **list_skb;
9699 struct sk_buff *skb;
9701 struct softnet_data *sd, *oldsd, *remsd = NULL;
9703 local_irq_disable();
9704 cpu = smp_processor_id();
9705 sd = &per_cpu(softnet_data, cpu);
9706 oldsd = &per_cpu(softnet_data, oldcpu);
9708 /* Find end of our completion_queue. */
9709 list_skb = &sd->completion_queue;
9711 list_skb = &(*list_skb)->next;
9712 /* Append completion queue from offline CPU. */
9713 *list_skb = oldsd->completion_queue;
9714 oldsd->completion_queue = NULL;
9716 /* Append output queue from offline CPU. */
9717 if (oldsd->output_queue) {
9718 *sd->output_queue_tailp = oldsd->output_queue;
9719 sd->output_queue_tailp = oldsd->output_queue_tailp;
9720 oldsd->output_queue = NULL;
9721 oldsd->output_queue_tailp = &oldsd->output_queue;
9723 /* Append NAPI poll list from offline CPU, with one exception :
9724 * process_backlog() must be called by cpu owning percpu backlog.
9725 * We properly handle process_queue & input_pkt_queue later.
9727 while (!list_empty(&oldsd->poll_list)) {
9728 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
9732 list_del_init(&napi->poll_list);
9733 if (napi->poll == process_backlog)
9736 ____napi_schedule(sd, napi);
9739 raise_softirq_irqoff(NET_TX_SOFTIRQ);
9743 remsd = oldsd->rps_ipi_list;
9744 oldsd->rps_ipi_list = NULL;
9746 /* send out pending IPI's on offline CPU */
9747 net_rps_send_ipi(remsd);
9749 /* Process offline CPU's input_pkt_queue */
9750 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
9752 input_queue_head_incr(oldsd);
9754 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
9756 input_queue_head_incr(oldsd);
9763 * netdev_increment_features - increment feature set by one
9764 * @all: current feature set
9765 * @one: new feature set
9766 * @mask: mask feature set
9768 * Computes a new feature set after adding a device with feature set
9769 * @one to the master device with current feature set @all. Will not
9770 * enable anything that is off in @mask. Returns the new feature set.
9772 netdev_features_t netdev_increment_features(netdev_features_t all,
9773 netdev_features_t one, netdev_features_t mask)
9775 if (mask & NETIF_F_HW_CSUM)
9776 mask |= NETIF_F_CSUM_MASK;
9777 mask |= NETIF_F_VLAN_CHALLENGED;
9779 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
9780 all &= one | ~NETIF_F_ALL_FOR_ALL;
9782 /* If one device supports hw checksumming, set for all. */
9783 if (all & NETIF_F_HW_CSUM)
9784 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
9788 EXPORT_SYMBOL(netdev_increment_features);
9790 static struct hlist_head * __net_init netdev_create_hash(void)
9793 struct hlist_head *hash;
9795 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
9797 for (i = 0; i < NETDEV_HASHENTRIES; i++)
9798 INIT_HLIST_HEAD(&hash[i]);
9803 /* Initialize per network namespace state */
9804 static int __net_init netdev_init(struct net *net)
9806 BUILD_BUG_ON(GRO_HASH_BUCKETS >
9807 8 * FIELD_SIZEOF(struct napi_struct, gro_bitmask));
9809 if (net != &init_net)
9810 INIT_LIST_HEAD(&net->dev_base_head);
9812 net->dev_name_head = netdev_create_hash();
9813 if (net->dev_name_head == NULL)
9816 net->dev_index_head = netdev_create_hash();
9817 if (net->dev_index_head == NULL)
9823 kfree(net->dev_name_head);
9829 * netdev_drivername - network driver for the device
9830 * @dev: network device
9832 * Determine network driver for device.
9834 const char *netdev_drivername(const struct net_device *dev)
9836 const struct device_driver *driver;
9837 const struct device *parent;
9838 const char *empty = "";
9840 parent = dev->dev.parent;
9844 driver = parent->driver;
9845 if (driver && driver->name)
9846 return driver->name;
9850 static void __netdev_printk(const char *level, const struct net_device *dev,
9851 struct va_format *vaf)
9853 if (dev && dev->dev.parent) {
9854 dev_printk_emit(level[1] - '0',
9857 dev_driver_string(dev->dev.parent),
9858 dev_name(dev->dev.parent),
9859 netdev_name(dev), netdev_reg_state(dev),
9862 printk("%s%s%s: %pV",
9863 level, netdev_name(dev), netdev_reg_state(dev), vaf);
9865 printk("%s(NULL net_device): %pV", level, vaf);
9869 void netdev_printk(const char *level, const struct net_device *dev,
9870 const char *format, ...)
9872 struct va_format vaf;
9875 va_start(args, format);
9880 __netdev_printk(level, dev, &vaf);
9884 EXPORT_SYMBOL(netdev_printk);
9886 #define define_netdev_printk_level(func, level) \
9887 void func(const struct net_device *dev, const char *fmt, ...) \
9889 struct va_format vaf; \
9892 va_start(args, fmt); \
9897 __netdev_printk(level, dev, &vaf); \
9901 EXPORT_SYMBOL(func);
9903 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
9904 define_netdev_printk_level(netdev_alert, KERN_ALERT);
9905 define_netdev_printk_level(netdev_crit, KERN_CRIT);
9906 define_netdev_printk_level(netdev_err, KERN_ERR);
9907 define_netdev_printk_level(netdev_warn, KERN_WARNING);
9908 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
9909 define_netdev_printk_level(netdev_info, KERN_INFO);
9911 static void __net_exit netdev_exit(struct net *net)
9913 kfree(net->dev_name_head);
9914 kfree(net->dev_index_head);
9915 if (net != &init_net)
9916 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
9919 static struct pernet_operations __net_initdata netdev_net_ops = {
9920 .init = netdev_init,
9921 .exit = netdev_exit,
9924 static void __net_exit default_device_exit(struct net *net)
9926 struct net_device *dev, *aux;
9928 * Push all migratable network devices back to the
9929 * initial network namespace
9932 for_each_netdev_safe(net, dev, aux) {
9934 char fb_name[IFNAMSIZ];
9936 /* Ignore unmoveable devices (i.e. loopback) */
9937 if (dev->features & NETIF_F_NETNS_LOCAL)
9940 /* Leave virtual devices for the generic cleanup */
9941 if (dev->rtnl_link_ops)
9944 /* Push remaining network devices to init_net */
9945 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
9946 if (__dev_get_by_name(&init_net, fb_name))
9947 snprintf(fb_name, IFNAMSIZ, "dev%%d");
9948 err = dev_change_net_namespace(dev, &init_net, fb_name);
9950 pr_emerg("%s: failed to move %s to init_net: %d\n",
9951 __func__, dev->name, err);
9958 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
9960 /* Return with the rtnl_lock held when there are no network
9961 * devices unregistering in any network namespace in net_list.
9965 DEFINE_WAIT_FUNC(wait, woken_wake_function);
9967 add_wait_queue(&netdev_unregistering_wq, &wait);
9969 unregistering = false;
9971 list_for_each_entry(net, net_list, exit_list) {
9972 if (net->dev_unreg_count > 0) {
9973 unregistering = true;
9981 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
9983 remove_wait_queue(&netdev_unregistering_wq, &wait);
9986 static void __net_exit default_device_exit_batch(struct list_head *net_list)
9988 /* At exit all network devices most be removed from a network
9989 * namespace. Do this in the reverse order of registration.
9990 * Do this across as many network namespaces as possible to
9991 * improve batching efficiency.
9993 struct net_device *dev;
9995 LIST_HEAD(dev_kill_list);
9997 /* To prevent network device cleanup code from dereferencing
9998 * loopback devices or network devices that have been freed
9999 * wait here for all pending unregistrations to complete,
10000 * before unregistring the loopback device and allowing the
10001 * network namespace be freed.
10003 * The netdev todo list containing all network devices
10004 * unregistrations that happen in default_device_exit_batch
10005 * will run in the rtnl_unlock() at the end of
10006 * default_device_exit_batch.
10008 rtnl_lock_unregistering(net_list);
10009 list_for_each_entry(net, net_list, exit_list) {
10010 for_each_netdev_reverse(net, dev) {
10011 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
10012 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
10014 unregister_netdevice_queue(dev, &dev_kill_list);
10017 unregister_netdevice_many(&dev_kill_list);
10021 static struct pernet_operations __net_initdata default_device_ops = {
10022 .exit = default_device_exit,
10023 .exit_batch = default_device_exit_batch,
10027 * Initialize the DEV module. At boot time this walks the device list and
10028 * unhooks any devices that fail to initialise (normally hardware not
10029 * present) and leaves us with a valid list of present and active devices.
10034 * This is called single threaded during boot, so no need
10035 * to take the rtnl semaphore.
10037 static int __init net_dev_init(void)
10039 int i, rc = -ENOMEM;
10041 BUG_ON(!dev_boot_phase);
10043 if (dev_proc_init())
10046 if (netdev_kobject_init())
10049 INIT_LIST_HEAD(&ptype_all);
10050 for (i = 0; i < PTYPE_HASH_SIZE; i++)
10051 INIT_LIST_HEAD(&ptype_base[i]);
10053 INIT_LIST_HEAD(&offload_base);
10055 if (register_pernet_subsys(&netdev_net_ops))
10059 * Initialise the packet receive queues.
10062 for_each_possible_cpu(i) {
10063 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
10064 struct softnet_data *sd = &per_cpu(softnet_data, i);
10066 INIT_WORK(flush, flush_backlog);
10068 skb_queue_head_init(&sd->input_pkt_queue);
10069 skb_queue_head_init(&sd->process_queue);
10070 #ifdef CONFIG_XFRM_OFFLOAD
10071 skb_queue_head_init(&sd->xfrm_backlog);
10073 INIT_LIST_HEAD(&sd->poll_list);
10074 sd->output_queue_tailp = &sd->output_queue;
10076 sd->csd.func = rps_trigger_softirq;
10081 init_gro_hash(&sd->backlog);
10082 sd->backlog.poll = process_backlog;
10083 sd->backlog.weight = weight_p;
10086 dev_boot_phase = 0;
10088 /* The loopback device is special if any other network devices
10089 * is present in a network namespace the loopback device must
10090 * be present. Since we now dynamically allocate and free the
10091 * loopback device ensure this invariant is maintained by
10092 * keeping the loopback device as the first device on the
10093 * list of network devices. Ensuring the loopback devices
10094 * is the first device that appears and the last network device
10097 if (register_pernet_device(&loopback_net_ops))
10100 if (register_pernet_device(&default_device_ops))
10103 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
10104 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
10106 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
10107 NULL, dev_cpu_dead);
10114 subsys_initcall(net_dev_init);