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
150 /* This should be increased if a protocol with a bigger head is added. */
151 #define GRO_MAX_HEAD (MAX_HEADER + 128)
153 static DEFINE_SPINLOCK(ptype_lock);
154 static DEFINE_SPINLOCK(offload_lock);
155 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
156 struct list_head ptype_all __read_mostly; /* Taps */
157 static struct list_head offload_base __read_mostly;
159 static int netif_rx_internal(struct sk_buff *skb);
160 static int call_netdevice_notifiers_info(unsigned long val,
161 struct netdev_notifier_info *info);
162 static int call_netdevice_notifiers_extack(unsigned long val,
163 struct net_device *dev,
164 struct netlink_ext_ack *extack);
165 static struct napi_struct *napi_by_id(unsigned int napi_id);
168 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
171 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
173 * Writers must hold the rtnl semaphore while they loop through the
174 * dev_base_head list, and hold dev_base_lock for writing when they do the
175 * actual updates. This allows pure readers to access the list even
176 * while a writer is preparing to update it.
178 * To put it another way, dev_base_lock is held for writing only to
179 * protect against pure readers; the rtnl semaphore provides the
180 * protection against other writers.
182 * See, for example usages, register_netdevice() and
183 * unregister_netdevice(), which must be called with the rtnl
186 DEFINE_RWLOCK(dev_base_lock);
187 EXPORT_SYMBOL(dev_base_lock);
189 static DEFINE_MUTEX(ifalias_mutex);
191 /* protects napi_hash addition/deletion and napi_gen_id */
192 static DEFINE_SPINLOCK(napi_hash_lock);
194 static unsigned int napi_gen_id = NR_CPUS;
195 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
197 static seqcount_t devnet_rename_seq;
199 static inline void dev_base_seq_inc(struct net *net)
201 while (++net->dev_base_seq == 0)
205 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
207 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
209 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
212 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
214 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
217 static inline void rps_lock(struct softnet_data *sd)
220 spin_lock(&sd->input_pkt_queue.lock);
224 static inline void rps_unlock(struct softnet_data *sd)
227 spin_unlock(&sd->input_pkt_queue.lock);
231 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
234 struct netdev_name_node *name_node;
236 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
239 INIT_HLIST_NODE(&name_node->hlist);
240 name_node->dev = dev;
241 name_node->name = name;
245 static struct netdev_name_node *
246 netdev_name_node_head_alloc(struct net_device *dev)
248 struct netdev_name_node *name_node;
250 name_node = netdev_name_node_alloc(dev, dev->name);
253 INIT_LIST_HEAD(&name_node->list);
257 static void netdev_name_node_free(struct netdev_name_node *name_node)
262 static void netdev_name_node_add(struct net *net,
263 struct netdev_name_node *name_node)
265 hlist_add_head_rcu(&name_node->hlist,
266 dev_name_hash(net, name_node->name));
269 static void netdev_name_node_del(struct netdev_name_node *name_node)
271 hlist_del_rcu(&name_node->hlist);
274 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
277 struct hlist_head *head = dev_name_hash(net, name);
278 struct netdev_name_node *name_node;
280 hlist_for_each_entry(name_node, head, hlist)
281 if (!strcmp(name_node->name, name))
286 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
289 struct hlist_head *head = dev_name_hash(net, name);
290 struct netdev_name_node *name_node;
292 hlist_for_each_entry_rcu(name_node, head, hlist)
293 if (!strcmp(name_node->name, name))
298 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
300 struct netdev_name_node *name_node;
301 struct net *net = dev_net(dev);
303 name_node = netdev_name_node_lookup(net, name);
306 name_node = netdev_name_node_alloc(dev, name);
309 netdev_name_node_add(net, name_node);
310 /* The node that holds dev->name acts as a head of per-device list. */
311 list_add_tail(&name_node->list, &dev->name_node->list);
315 EXPORT_SYMBOL(netdev_name_node_alt_create);
317 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
319 list_del(&name_node->list);
320 netdev_name_node_del(name_node);
321 kfree(name_node->name);
322 netdev_name_node_free(name_node);
325 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
327 struct netdev_name_node *name_node;
328 struct net *net = dev_net(dev);
330 name_node = netdev_name_node_lookup(net, name);
333 __netdev_name_node_alt_destroy(name_node);
337 EXPORT_SYMBOL(netdev_name_node_alt_destroy);
339 static void netdev_name_node_alt_flush(struct net_device *dev)
341 struct netdev_name_node *name_node, *tmp;
343 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
344 __netdev_name_node_alt_destroy(name_node);
347 /* Device list insertion */
348 static void list_netdevice(struct net_device *dev)
350 struct net *net = dev_net(dev);
354 write_lock_bh(&dev_base_lock);
355 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
356 netdev_name_node_add(net, dev->name_node);
357 hlist_add_head_rcu(&dev->index_hlist,
358 dev_index_hash(net, dev->ifindex));
359 write_unlock_bh(&dev_base_lock);
361 dev_base_seq_inc(net);
364 /* Device list removal
365 * caller must respect a RCU grace period before freeing/reusing dev
367 static void unlist_netdevice(struct net_device *dev)
371 /* Unlink dev from the device chain */
372 write_lock_bh(&dev_base_lock);
373 list_del_rcu(&dev->dev_list);
374 netdev_name_node_del(dev->name_node);
375 hlist_del_rcu(&dev->index_hlist);
376 write_unlock_bh(&dev_base_lock);
378 dev_base_seq_inc(dev_net(dev));
385 static RAW_NOTIFIER_HEAD(netdev_chain);
388 * Device drivers call our routines to queue packets here. We empty the
389 * queue in the local softnet handler.
392 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
393 EXPORT_PER_CPU_SYMBOL(softnet_data);
395 #ifdef CONFIG_LOCKDEP
397 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
398 * according to dev->type
400 static const unsigned short netdev_lock_type[] = {
401 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
402 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
403 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
404 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
405 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
406 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
407 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
408 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
409 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
410 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
411 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
412 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
413 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
414 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
415 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
417 static const char *const netdev_lock_name[] = {
418 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
419 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
420 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
421 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
422 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
423 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
424 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
425 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
426 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
427 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
428 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
429 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
430 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
431 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
432 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
434 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
435 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
437 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
441 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
442 if (netdev_lock_type[i] == dev_type)
444 /* the last key is used by default */
445 return ARRAY_SIZE(netdev_lock_type) - 1;
448 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
449 unsigned short dev_type)
453 i = netdev_lock_pos(dev_type);
454 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
455 netdev_lock_name[i]);
458 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
462 i = netdev_lock_pos(dev->type);
463 lockdep_set_class_and_name(&dev->addr_list_lock,
464 &netdev_addr_lock_key[i],
465 netdev_lock_name[i]);
468 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
469 unsigned short dev_type)
472 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
477 /*******************************************************************************
479 * Protocol management and registration routines
481 *******************************************************************************/
485 * Add a protocol ID to the list. Now that the input handler is
486 * smarter we can dispense with all the messy stuff that used to be
489 * BEWARE!!! Protocol handlers, mangling input packets,
490 * MUST BE last in hash buckets and checking protocol handlers
491 * MUST start from promiscuous ptype_all chain in net_bh.
492 * It is true now, do not change it.
493 * Explanation follows: if protocol handler, mangling packet, will
494 * be the first on list, it is not able to sense, that packet
495 * is cloned and should be copied-on-write, so that it will
496 * change it and subsequent readers will get broken packet.
500 static inline struct list_head *ptype_head(const struct packet_type *pt)
502 if (pt->type == htons(ETH_P_ALL))
503 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
505 return pt->dev ? &pt->dev->ptype_specific :
506 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
510 * dev_add_pack - add packet handler
511 * @pt: packet type declaration
513 * Add a protocol handler to the networking stack. The passed &packet_type
514 * is linked into kernel lists and may not be freed until it has been
515 * removed from the kernel lists.
517 * This call does not sleep therefore it can not
518 * guarantee all CPU's that are in middle of receiving packets
519 * will see the new packet type (until the next received packet).
522 void dev_add_pack(struct packet_type *pt)
524 struct list_head *head = ptype_head(pt);
526 spin_lock(&ptype_lock);
527 list_add_rcu(&pt->list, head);
528 spin_unlock(&ptype_lock);
530 EXPORT_SYMBOL(dev_add_pack);
533 * __dev_remove_pack - remove packet handler
534 * @pt: packet type declaration
536 * Remove a protocol handler that was previously added to the kernel
537 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
538 * from the kernel lists and can be freed or reused once this function
541 * The packet type might still be in use by receivers
542 * and must not be freed until after all the CPU's have gone
543 * through a quiescent state.
545 void __dev_remove_pack(struct packet_type *pt)
547 struct list_head *head = ptype_head(pt);
548 struct packet_type *pt1;
550 spin_lock(&ptype_lock);
552 list_for_each_entry(pt1, head, list) {
554 list_del_rcu(&pt->list);
559 pr_warn("dev_remove_pack: %p not found\n", pt);
561 spin_unlock(&ptype_lock);
563 EXPORT_SYMBOL(__dev_remove_pack);
566 * dev_remove_pack - remove packet handler
567 * @pt: packet type declaration
569 * Remove a protocol handler that was previously added to the kernel
570 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
571 * from the kernel lists and can be freed or reused once this function
574 * This call sleeps to guarantee that no CPU is looking at the packet
577 void dev_remove_pack(struct packet_type *pt)
579 __dev_remove_pack(pt);
583 EXPORT_SYMBOL(dev_remove_pack);
587 * dev_add_offload - register offload handlers
588 * @po: protocol offload declaration
590 * Add protocol offload handlers to the networking stack. The passed
591 * &proto_offload is linked into kernel lists and may not be freed until
592 * it has been removed from the kernel lists.
594 * This call does not sleep therefore it can not
595 * guarantee all CPU's that are in middle of receiving packets
596 * will see the new offload handlers (until the next received packet).
598 void dev_add_offload(struct packet_offload *po)
600 struct packet_offload *elem;
602 spin_lock(&offload_lock);
603 list_for_each_entry(elem, &offload_base, list) {
604 if (po->priority < elem->priority)
607 list_add_rcu(&po->list, elem->list.prev);
608 spin_unlock(&offload_lock);
610 EXPORT_SYMBOL(dev_add_offload);
613 * __dev_remove_offload - remove offload handler
614 * @po: packet offload declaration
616 * Remove a protocol offload handler that was previously added to the
617 * kernel offload handlers by dev_add_offload(). The passed &offload_type
618 * is removed from the kernel lists and can be freed or reused once this
621 * The packet type might still be in use by receivers
622 * and must not be freed until after all the CPU's have gone
623 * through a quiescent state.
625 static void __dev_remove_offload(struct packet_offload *po)
627 struct list_head *head = &offload_base;
628 struct packet_offload *po1;
630 spin_lock(&offload_lock);
632 list_for_each_entry(po1, head, list) {
634 list_del_rcu(&po->list);
639 pr_warn("dev_remove_offload: %p not found\n", po);
641 spin_unlock(&offload_lock);
645 * dev_remove_offload - remove packet offload handler
646 * @po: packet offload declaration
648 * Remove a packet offload handler that was previously added to the kernel
649 * offload handlers by dev_add_offload(). The passed &offload_type is
650 * removed from the kernel lists and can be freed or reused once this
653 * This call sleeps to guarantee that no CPU is looking at the packet
656 void dev_remove_offload(struct packet_offload *po)
658 __dev_remove_offload(po);
662 EXPORT_SYMBOL(dev_remove_offload);
664 /******************************************************************************
666 * Device Boot-time Settings Routines
668 ******************************************************************************/
670 /* Boot time configuration table */
671 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
674 * netdev_boot_setup_add - add new setup entry
675 * @name: name of the device
676 * @map: configured settings for the device
678 * Adds new setup entry to the dev_boot_setup list. The function
679 * returns 0 on error and 1 on success. This is a generic routine to
682 static int netdev_boot_setup_add(char *name, struct ifmap *map)
684 struct netdev_boot_setup *s;
688 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
689 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
690 memset(s[i].name, 0, sizeof(s[i].name));
691 strlcpy(s[i].name, name, IFNAMSIZ);
692 memcpy(&s[i].map, map, sizeof(s[i].map));
697 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
701 * netdev_boot_setup_check - check boot time settings
702 * @dev: the netdevice
704 * Check boot time settings for the device.
705 * The found settings are set for the device to be used
706 * later in the device probing.
707 * Returns 0 if no settings found, 1 if they are.
709 int netdev_boot_setup_check(struct net_device *dev)
711 struct netdev_boot_setup *s = dev_boot_setup;
714 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
715 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
716 !strcmp(dev->name, s[i].name)) {
717 dev->irq = s[i].map.irq;
718 dev->base_addr = s[i].map.base_addr;
719 dev->mem_start = s[i].map.mem_start;
720 dev->mem_end = s[i].map.mem_end;
726 EXPORT_SYMBOL(netdev_boot_setup_check);
730 * netdev_boot_base - get address from boot time settings
731 * @prefix: prefix for network device
732 * @unit: id for network device
734 * Check boot time settings for the base address of device.
735 * The found settings are set for the device to be used
736 * later in the device probing.
737 * Returns 0 if no settings found.
739 unsigned long netdev_boot_base(const char *prefix, int unit)
741 const struct netdev_boot_setup *s = dev_boot_setup;
745 sprintf(name, "%s%d", prefix, unit);
748 * If device already registered then return base of 1
749 * to indicate not to probe for this interface
751 if (__dev_get_by_name(&init_net, name))
754 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
755 if (!strcmp(name, s[i].name))
756 return s[i].map.base_addr;
761 * Saves at boot time configured settings for any netdevice.
763 int __init netdev_boot_setup(char *str)
768 str = get_options(str, ARRAY_SIZE(ints), ints);
773 memset(&map, 0, sizeof(map));
777 map.base_addr = ints[2];
779 map.mem_start = ints[3];
781 map.mem_end = ints[4];
783 /* Add new entry to the list */
784 return netdev_boot_setup_add(str, &map);
787 __setup("netdev=", netdev_boot_setup);
789 /*******************************************************************************
791 * Device Interface Subroutines
793 *******************************************************************************/
796 * dev_get_iflink - get 'iflink' value of a interface
797 * @dev: targeted interface
799 * Indicates the ifindex the interface is linked to.
800 * Physical interfaces have the same 'ifindex' and 'iflink' values.
803 int dev_get_iflink(const struct net_device *dev)
805 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
806 return dev->netdev_ops->ndo_get_iflink(dev);
810 EXPORT_SYMBOL(dev_get_iflink);
813 * dev_fill_metadata_dst - Retrieve tunnel egress information.
814 * @dev: targeted interface
817 * For better visibility of tunnel traffic OVS needs to retrieve
818 * egress tunnel information for a packet. Following API allows
819 * user to get this info.
821 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
823 struct ip_tunnel_info *info;
825 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
828 info = skb_tunnel_info_unclone(skb);
831 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
834 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
836 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
839 * __dev_get_by_name - find a device by its name
840 * @net: the applicable net namespace
841 * @name: name to find
843 * Find an interface by name. Must be called under RTNL semaphore
844 * or @dev_base_lock. If the name is found a pointer to the device
845 * is returned. If the name is not found then %NULL is returned. The
846 * reference counters are not incremented so the caller must be
847 * careful with locks.
850 struct net_device *__dev_get_by_name(struct net *net, const char *name)
852 struct netdev_name_node *node_name;
854 node_name = netdev_name_node_lookup(net, name);
855 return node_name ? node_name->dev : NULL;
857 EXPORT_SYMBOL(__dev_get_by_name);
860 * dev_get_by_name_rcu - find a device by its name
861 * @net: the applicable net namespace
862 * @name: name to find
864 * Find an interface by name.
865 * If the name is found a pointer to the device is returned.
866 * If the name is not found then %NULL is returned.
867 * The reference counters are not incremented so the caller must be
868 * careful with locks. The caller must hold RCU lock.
871 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
873 struct netdev_name_node *node_name;
875 node_name = netdev_name_node_lookup_rcu(net, name);
876 return node_name ? node_name->dev : NULL;
878 EXPORT_SYMBOL(dev_get_by_name_rcu);
881 * dev_get_by_name - find a device by its name
882 * @net: the applicable net namespace
883 * @name: name to find
885 * Find an interface by name. This can be called from any
886 * context and does its own locking. The returned handle has
887 * the usage count incremented and the caller must use dev_put() to
888 * release it when it is no longer needed. %NULL is returned if no
889 * matching device is found.
892 struct net_device *dev_get_by_name(struct net *net, const char *name)
894 struct net_device *dev;
897 dev = dev_get_by_name_rcu(net, name);
903 EXPORT_SYMBOL(dev_get_by_name);
906 * __dev_get_by_index - find a device by its ifindex
907 * @net: the applicable net namespace
908 * @ifindex: index of device
910 * Search for an interface by index. Returns %NULL if the device
911 * is not found or a pointer to the device. The device has not
912 * had its reference counter increased so the caller must be careful
913 * about locking. The caller must hold either the RTNL semaphore
917 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
919 struct net_device *dev;
920 struct hlist_head *head = dev_index_hash(net, ifindex);
922 hlist_for_each_entry(dev, head, index_hlist)
923 if (dev->ifindex == ifindex)
928 EXPORT_SYMBOL(__dev_get_by_index);
931 * dev_get_by_index_rcu - find a device by its ifindex
932 * @net: the applicable net namespace
933 * @ifindex: index of device
935 * Search for an interface by index. Returns %NULL if the device
936 * is not found or a pointer to the device. The device has not
937 * had its reference counter increased so the caller must be careful
938 * about locking. The caller must hold RCU lock.
941 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
943 struct net_device *dev;
944 struct hlist_head *head = dev_index_hash(net, ifindex);
946 hlist_for_each_entry_rcu(dev, head, index_hlist)
947 if (dev->ifindex == ifindex)
952 EXPORT_SYMBOL(dev_get_by_index_rcu);
956 * dev_get_by_index - find a device by its ifindex
957 * @net: the applicable net namespace
958 * @ifindex: index of device
960 * Search for an interface by index. Returns NULL if the device
961 * is not found or a pointer to the device. The device returned has
962 * had a reference added and the pointer is safe until the user calls
963 * dev_put to indicate they have finished with it.
966 struct net_device *dev_get_by_index(struct net *net, int ifindex)
968 struct net_device *dev;
971 dev = dev_get_by_index_rcu(net, ifindex);
977 EXPORT_SYMBOL(dev_get_by_index);
980 * dev_get_by_napi_id - find a device by napi_id
981 * @napi_id: ID of the NAPI struct
983 * Search for an interface by NAPI ID. Returns %NULL if the device
984 * is not found or a pointer to the device. The device has not had
985 * its reference counter increased so the caller must be careful
986 * about locking. The caller must hold RCU lock.
989 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
991 struct napi_struct *napi;
993 WARN_ON_ONCE(!rcu_read_lock_held());
995 if (napi_id < MIN_NAPI_ID)
998 napi = napi_by_id(napi_id);
1000 return napi ? napi->dev : NULL;
1002 EXPORT_SYMBOL(dev_get_by_napi_id);
1005 * netdev_get_name - get a netdevice name, knowing its ifindex.
1006 * @net: network namespace
1007 * @name: a pointer to the buffer where the name will be stored.
1008 * @ifindex: the ifindex of the interface to get the name from.
1010 * The use of raw_seqcount_begin() and cond_resched() before
1011 * retrying is required as we want to give the writers a chance
1012 * to complete when CONFIG_PREEMPT is not set.
1014 int netdev_get_name(struct net *net, char *name, int ifindex)
1016 struct net_device *dev;
1020 seq = raw_seqcount_begin(&devnet_rename_seq);
1022 dev = dev_get_by_index_rcu(net, ifindex);
1028 strcpy(name, dev->name);
1030 if (read_seqcount_retry(&devnet_rename_seq, seq)) {
1039 * dev_getbyhwaddr_rcu - find a device by its hardware address
1040 * @net: the applicable net namespace
1041 * @type: media type of device
1042 * @ha: hardware address
1044 * Search for an interface by MAC address. Returns NULL if the device
1045 * is not found or a pointer to the device.
1046 * The caller must hold RCU or RTNL.
1047 * The returned device has not had its ref count increased
1048 * and the caller must therefore be careful about locking
1052 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
1055 struct net_device *dev;
1057 for_each_netdev_rcu(net, dev)
1058 if (dev->type == type &&
1059 !memcmp(dev->dev_addr, ha, dev->addr_len))
1064 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
1066 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
1068 struct net_device *dev;
1071 for_each_netdev(net, dev)
1072 if (dev->type == type)
1077 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
1079 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1081 struct net_device *dev, *ret = NULL;
1084 for_each_netdev_rcu(net, dev)
1085 if (dev->type == type) {
1093 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1096 * __dev_get_by_flags - find any device with given flags
1097 * @net: the applicable net namespace
1098 * @if_flags: IFF_* values
1099 * @mask: bitmask of bits in if_flags to check
1101 * Search for any interface with the given flags. Returns NULL if a device
1102 * is not found or a pointer to the device. Must be called inside
1103 * rtnl_lock(), and result refcount is unchanged.
1106 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1107 unsigned short mask)
1109 struct net_device *dev, *ret;
1114 for_each_netdev(net, dev) {
1115 if (((dev->flags ^ if_flags) & mask) == 0) {
1122 EXPORT_SYMBOL(__dev_get_by_flags);
1125 * dev_valid_name - check if name is okay for network device
1126 * @name: name string
1128 * Network device names need to be valid file names to
1129 * to allow sysfs to work. We also disallow any kind of
1132 bool dev_valid_name(const char *name)
1136 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1138 if (!strcmp(name, ".") || !strcmp(name, ".."))
1142 if (*name == '/' || *name == ':' || isspace(*name))
1148 EXPORT_SYMBOL(dev_valid_name);
1151 * __dev_alloc_name - allocate a name for a device
1152 * @net: network namespace to allocate the device name in
1153 * @name: name format string
1154 * @buf: scratch buffer and result name string
1156 * Passed a format string - eg "lt%d" it will try and find a suitable
1157 * id. It scans list of devices to build up a free map, then chooses
1158 * the first empty slot. The caller must hold the dev_base or rtnl lock
1159 * while allocating the name and adding the device in order to avoid
1161 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1162 * Returns the number of the unit assigned or a negative errno code.
1165 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1169 const int max_netdevices = 8*PAGE_SIZE;
1170 unsigned long *inuse;
1171 struct net_device *d;
1173 if (!dev_valid_name(name))
1176 p = strchr(name, '%');
1179 * Verify the string as this thing may have come from
1180 * the user. There must be either one "%d" and no other "%"
1183 if (p[1] != 'd' || strchr(p + 2, '%'))
1186 /* Use one page as a bit array of possible slots */
1187 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1191 for_each_netdev(net, d) {
1192 if (!sscanf(d->name, name, &i))
1194 if (i < 0 || i >= max_netdevices)
1197 /* avoid cases where sscanf is not exact inverse of printf */
1198 snprintf(buf, IFNAMSIZ, name, i);
1199 if (!strncmp(buf, d->name, IFNAMSIZ))
1203 i = find_first_zero_bit(inuse, max_netdevices);
1204 free_page((unsigned long) inuse);
1207 snprintf(buf, IFNAMSIZ, name, i);
1208 if (!__dev_get_by_name(net, buf))
1211 /* It is possible to run out of possible slots
1212 * when the name is long and there isn't enough space left
1213 * for the digits, or if all bits are used.
1218 static int dev_alloc_name_ns(struct net *net,
1219 struct net_device *dev,
1226 ret = __dev_alloc_name(net, name, buf);
1228 strlcpy(dev->name, buf, IFNAMSIZ);
1233 * dev_alloc_name - allocate a name for a device
1235 * @name: name format string
1237 * Passed a format string - eg "lt%d" it will try and find a suitable
1238 * id. It scans list of devices to build up a free map, then chooses
1239 * the first empty slot. The caller must hold the dev_base or rtnl lock
1240 * while allocating the name and adding the device in order to avoid
1242 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1243 * Returns the number of the unit assigned or a negative errno code.
1246 int dev_alloc_name(struct net_device *dev, const char *name)
1248 return dev_alloc_name_ns(dev_net(dev), dev, name);
1250 EXPORT_SYMBOL(dev_alloc_name);
1252 int dev_get_valid_name(struct net *net, struct net_device *dev,
1257 if (!dev_valid_name(name))
1260 if (strchr(name, '%'))
1261 return dev_alloc_name_ns(net, dev, name);
1262 else if (__dev_get_by_name(net, name))
1264 else if (dev->name != name)
1265 strlcpy(dev->name, name, IFNAMSIZ);
1269 EXPORT_SYMBOL(dev_get_valid_name);
1272 * dev_change_name - change name of a device
1274 * @newname: name (or format string) must be at least IFNAMSIZ
1276 * Change name of a device, can pass format strings "eth%d".
1279 int dev_change_name(struct net_device *dev, const char *newname)
1281 unsigned char old_assign_type;
1282 char oldname[IFNAMSIZ];
1288 BUG_ON(!dev_net(dev));
1292 /* Some auto-enslaved devices e.g. failover slaves are
1293 * special, as userspace might rename the device after
1294 * the interface had been brought up and running since
1295 * the point kernel initiated auto-enslavement. Allow
1296 * live name change even when these slave devices are
1299 * Typically, users of these auto-enslaving devices
1300 * don't actually care about slave name change, as
1301 * they are supposed to operate on master interface
1304 if (dev->flags & IFF_UP &&
1305 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1308 write_seqcount_begin(&devnet_rename_seq);
1310 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1311 write_seqcount_end(&devnet_rename_seq);
1315 memcpy(oldname, dev->name, IFNAMSIZ);
1317 err = dev_get_valid_name(net, dev, newname);
1319 write_seqcount_end(&devnet_rename_seq);
1323 if (oldname[0] && !strchr(oldname, '%'))
1324 netdev_info(dev, "renamed from %s\n", oldname);
1326 old_assign_type = dev->name_assign_type;
1327 dev->name_assign_type = NET_NAME_RENAMED;
1330 ret = device_rename(&dev->dev, dev->name);
1332 memcpy(dev->name, oldname, IFNAMSIZ);
1333 dev->name_assign_type = old_assign_type;
1334 write_seqcount_end(&devnet_rename_seq);
1338 write_seqcount_end(&devnet_rename_seq);
1340 netdev_adjacent_rename_links(dev, oldname);
1342 write_lock_bh(&dev_base_lock);
1343 netdev_name_node_del(dev->name_node);
1344 write_unlock_bh(&dev_base_lock);
1348 write_lock_bh(&dev_base_lock);
1349 netdev_name_node_add(net, dev->name_node);
1350 write_unlock_bh(&dev_base_lock);
1352 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1353 ret = notifier_to_errno(ret);
1356 /* err >= 0 after dev_alloc_name() or stores the first errno */
1359 write_seqcount_begin(&devnet_rename_seq);
1360 memcpy(dev->name, oldname, IFNAMSIZ);
1361 memcpy(oldname, newname, IFNAMSIZ);
1362 dev->name_assign_type = old_assign_type;
1363 old_assign_type = NET_NAME_RENAMED;
1366 pr_err("%s: name change rollback failed: %d\n",
1375 * dev_set_alias - change ifalias of a device
1377 * @alias: name up to IFALIASZ
1378 * @len: limit of bytes to copy from info
1380 * Set ifalias for a device,
1382 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1384 struct dev_ifalias *new_alias = NULL;
1386 if (len >= IFALIASZ)
1390 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1394 memcpy(new_alias->ifalias, alias, len);
1395 new_alias->ifalias[len] = 0;
1398 mutex_lock(&ifalias_mutex);
1399 rcu_swap_protected(dev->ifalias, new_alias,
1400 mutex_is_locked(&ifalias_mutex));
1401 mutex_unlock(&ifalias_mutex);
1404 kfree_rcu(new_alias, rcuhead);
1408 EXPORT_SYMBOL(dev_set_alias);
1411 * dev_get_alias - get ifalias of a device
1413 * @name: buffer to store name of ifalias
1414 * @len: size of buffer
1416 * get ifalias for a device. Caller must make sure dev cannot go
1417 * away, e.g. rcu read lock or own a reference count to device.
1419 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1421 const struct dev_ifalias *alias;
1425 alias = rcu_dereference(dev->ifalias);
1427 ret = snprintf(name, len, "%s", alias->ifalias);
1434 * netdev_features_change - device changes features
1435 * @dev: device to cause notification
1437 * Called to indicate a device has changed features.
1439 void netdev_features_change(struct net_device *dev)
1441 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1443 EXPORT_SYMBOL(netdev_features_change);
1446 * netdev_state_change - device changes state
1447 * @dev: device to cause notification
1449 * Called to indicate a device has changed state. This function calls
1450 * the notifier chains for netdev_chain and sends a NEWLINK message
1451 * to the routing socket.
1453 void netdev_state_change(struct net_device *dev)
1455 if (dev->flags & IFF_UP) {
1456 struct netdev_notifier_change_info change_info = {
1460 call_netdevice_notifiers_info(NETDEV_CHANGE,
1462 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1465 EXPORT_SYMBOL(netdev_state_change);
1468 * netdev_notify_peers - notify network peers about existence of @dev
1469 * @dev: network device
1471 * Generate traffic such that interested network peers are aware of
1472 * @dev, such as by generating a gratuitous ARP. This may be used when
1473 * a device wants to inform the rest of the network about some sort of
1474 * reconfiguration such as a failover event or virtual machine
1477 void netdev_notify_peers(struct net_device *dev)
1480 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1481 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1484 EXPORT_SYMBOL(netdev_notify_peers);
1486 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1488 const struct net_device_ops *ops = dev->netdev_ops;
1493 if (!netif_device_present(dev))
1496 /* Block netpoll from trying to do any rx path servicing.
1497 * If we don't do this there is a chance ndo_poll_controller
1498 * or ndo_poll may be running while we open the device
1500 netpoll_poll_disable(dev);
1502 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1503 ret = notifier_to_errno(ret);
1507 set_bit(__LINK_STATE_START, &dev->state);
1509 if (ops->ndo_validate_addr)
1510 ret = ops->ndo_validate_addr(dev);
1512 if (!ret && ops->ndo_open)
1513 ret = ops->ndo_open(dev);
1515 netpoll_poll_enable(dev);
1518 clear_bit(__LINK_STATE_START, &dev->state);
1520 dev->flags |= IFF_UP;
1521 dev_set_rx_mode(dev);
1523 add_device_randomness(dev->dev_addr, dev->addr_len);
1530 * dev_open - prepare an interface for use.
1531 * @dev: device to open
1532 * @extack: netlink extended ack
1534 * Takes a device from down to up state. The device's private open
1535 * function is invoked and then the multicast lists are loaded. Finally
1536 * the device is moved into the up state and a %NETDEV_UP message is
1537 * sent to the netdev notifier chain.
1539 * Calling this function on an active interface is a nop. On a failure
1540 * a negative errno code is returned.
1542 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1546 if (dev->flags & IFF_UP)
1549 ret = __dev_open(dev, extack);
1553 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1554 call_netdevice_notifiers(NETDEV_UP, dev);
1558 EXPORT_SYMBOL(dev_open);
1560 static void __dev_close_many(struct list_head *head)
1562 struct net_device *dev;
1567 list_for_each_entry(dev, head, close_list) {
1568 /* Temporarily disable netpoll until the interface is down */
1569 netpoll_poll_disable(dev);
1571 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1573 clear_bit(__LINK_STATE_START, &dev->state);
1575 /* Synchronize to scheduled poll. We cannot touch poll list, it
1576 * can be even on different cpu. So just clear netif_running().
1578 * dev->stop() will invoke napi_disable() on all of it's
1579 * napi_struct instances on this device.
1581 smp_mb__after_atomic(); /* Commit netif_running(). */
1584 dev_deactivate_many(head);
1586 list_for_each_entry(dev, head, close_list) {
1587 const struct net_device_ops *ops = dev->netdev_ops;
1590 * Call the device specific close. This cannot fail.
1591 * Only if device is UP
1593 * We allow it to be called even after a DETACH hot-plug
1599 dev->flags &= ~IFF_UP;
1600 netpoll_poll_enable(dev);
1604 static void __dev_close(struct net_device *dev)
1608 list_add(&dev->close_list, &single);
1609 __dev_close_many(&single);
1613 void dev_close_many(struct list_head *head, bool unlink)
1615 struct net_device *dev, *tmp;
1617 /* Remove the devices that don't need to be closed */
1618 list_for_each_entry_safe(dev, tmp, head, close_list)
1619 if (!(dev->flags & IFF_UP))
1620 list_del_init(&dev->close_list);
1622 __dev_close_many(head);
1624 list_for_each_entry_safe(dev, tmp, head, close_list) {
1625 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1626 call_netdevice_notifiers(NETDEV_DOWN, dev);
1628 list_del_init(&dev->close_list);
1631 EXPORT_SYMBOL(dev_close_many);
1634 * dev_close - shutdown an interface.
1635 * @dev: device to shutdown
1637 * This function moves an active device into down state. A
1638 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1639 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1642 void dev_close(struct net_device *dev)
1644 if (dev->flags & IFF_UP) {
1647 list_add(&dev->close_list, &single);
1648 dev_close_many(&single, true);
1652 EXPORT_SYMBOL(dev_close);
1656 * dev_disable_lro - disable Large Receive Offload on a device
1659 * Disable Large Receive Offload (LRO) on a net device. Must be
1660 * called under RTNL. This is needed if received packets may be
1661 * forwarded to another interface.
1663 void dev_disable_lro(struct net_device *dev)
1665 struct net_device *lower_dev;
1666 struct list_head *iter;
1668 dev->wanted_features &= ~NETIF_F_LRO;
1669 netdev_update_features(dev);
1671 if (unlikely(dev->features & NETIF_F_LRO))
1672 netdev_WARN(dev, "failed to disable LRO!\n");
1674 netdev_for_each_lower_dev(dev, lower_dev, iter)
1675 dev_disable_lro(lower_dev);
1677 EXPORT_SYMBOL(dev_disable_lro);
1680 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1683 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1684 * called under RTNL. This is needed if Generic XDP is installed on
1687 static void dev_disable_gro_hw(struct net_device *dev)
1689 dev->wanted_features &= ~NETIF_F_GRO_HW;
1690 netdev_update_features(dev);
1692 if (unlikely(dev->features & NETIF_F_GRO_HW))
1693 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1696 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1699 case NETDEV_##val: \
1700 return "NETDEV_" __stringify(val);
1702 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1703 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1704 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1705 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1706 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1707 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1708 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1709 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1710 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1714 return "UNKNOWN_NETDEV_EVENT";
1716 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1718 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1719 struct net_device *dev)
1721 struct netdev_notifier_info info = {
1725 return nb->notifier_call(nb, val, &info);
1728 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1729 struct net_device *dev)
1733 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1734 err = notifier_to_errno(err);
1738 if (!(dev->flags & IFF_UP))
1741 call_netdevice_notifier(nb, NETDEV_UP, dev);
1745 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1746 struct net_device *dev)
1748 if (dev->flags & IFF_UP) {
1749 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1751 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1753 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1756 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1759 struct net_device *dev;
1762 for_each_netdev(net, dev) {
1763 err = call_netdevice_register_notifiers(nb, dev);
1770 for_each_netdev_continue_reverse(net, dev)
1771 call_netdevice_unregister_notifiers(nb, dev);
1775 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1778 struct net_device *dev;
1780 for_each_netdev(net, dev)
1781 call_netdevice_unregister_notifiers(nb, dev);
1784 static int dev_boot_phase = 1;
1787 * register_netdevice_notifier - register a network notifier block
1790 * Register a notifier to be called when network device events occur.
1791 * The notifier passed is linked into the kernel structures and must
1792 * not be reused until it has been unregistered. A negative errno code
1793 * is returned on a failure.
1795 * When registered all registration and up events are replayed
1796 * to the new notifier to allow device to have a race free
1797 * view of the network device list.
1800 int register_netdevice_notifier(struct notifier_block *nb)
1805 /* Close race with setup_net() and cleanup_net() */
1806 down_write(&pernet_ops_rwsem);
1808 err = raw_notifier_chain_register(&netdev_chain, nb);
1814 err = call_netdevice_register_net_notifiers(nb, net);
1821 up_write(&pernet_ops_rwsem);
1825 for_each_net_continue_reverse(net)
1826 call_netdevice_unregister_net_notifiers(nb, net);
1828 raw_notifier_chain_unregister(&netdev_chain, nb);
1831 EXPORT_SYMBOL(register_netdevice_notifier);
1834 * unregister_netdevice_notifier - unregister a network notifier block
1837 * Unregister a notifier previously registered by
1838 * register_netdevice_notifier(). The notifier is unlinked into the
1839 * kernel structures and may then be reused. A negative errno code
1840 * is returned on a failure.
1842 * After unregistering unregister and down device events are synthesized
1843 * for all devices on the device list to the removed notifier to remove
1844 * the need for special case cleanup code.
1847 int unregister_netdevice_notifier(struct notifier_block *nb)
1849 struct net_device *dev;
1853 /* Close race with setup_net() and cleanup_net() */
1854 down_write(&pernet_ops_rwsem);
1856 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1861 for_each_netdev(net, dev) {
1862 if (dev->flags & IFF_UP) {
1863 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1865 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1867 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1872 up_write(&pernet_ops_rwsem);
1875 EXPORT_SYMBOL(unregister_netdevice_notifier);
1878 * register_netdevice_notifier_net - register a per-netns network notifier block
1879 * @net: network namespace
1882 * Register a notifier to be called when network device events occur.
1883 * The notifier passed is linked into the kernel structures and must
1884 * not be reused until it has been unregistered. A negative errno code
1885 * is returned on a failure.
1887 * When registered all registration and up events are replayed
1888 * to the new notifier to allow device to have a race free
1889 * view of the network device list.
1892 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1897 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1903 err = call_netdevice_register_net_notifiers(nb, net);
1905 goto chain_unregister;
1912 raw_notifier_chain_unregister(&netdev_chain, nb);
1915 EXPORT_SYMBOL(register_netdevice_notifier_net);
1918 * unregister_netdevice_notifier_net - unregister a per-netns
1919 * network notifier block
1920 * @net: network namespace
1923 * Unregister a notifier previously registered by
1924 * register_netdevice_notifier(). The notifier is unlinked into the
1925 * kernel structures and may then be reused. A negative errno code
1926 * is returned on a failure.
1928 * After unregistering unregister and down device events are synthesized
1929 * for all devices on the device list to the removed notifier to remove
1930 * the need for special case cleanup code.
1933 int unregister_netdevice_notifier_net(struct net *net,
1934 struct notifier_block *nb)
1939 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1943 call_netdevice_unregister_net_notifiers(nb, net);
1949 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1952 * call_netdevice_notifiers_info - call all network notifier blocks
1953 * @val: value passed unmodified to notifier function
1954 * @info: notifier information data
1956 * Call all network notifier blocks. Parameters and return value
1957 * are as for raw_notifier_call_chain().
1960 static int call_netdevice_notifiers_info(unsigned long val,
1961 struct netdev_notifier_info *info)
1963 struct net *net = dev_net(info->dev);
1968 /* Run per-netns notifier block chain first, then run the global one.
1969 * Hopefully, one day, the global one is going to be removed after
1970 * all notifier block registrators get converted to be per-netns.
1972 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1973 if (ret & NOTIFY_STOP_MASK)
1975 return raw_notifier_call_chain(&netdev_chain, val, info);
1978 static int call_netdevice_notifiers_extack(unsigned long val,
1979 struct net_device *dev,
1980 struct netlink_ext_ack *extack)
1982 struct netdev_notifier_info info = {
1987 return call_netdevice_notifiers_info(val, &info);
1991 * call_netdevice_notifiers - call all network notifier blocks
1992 * @val: value passed unmodified to notifier function
1993 * @dev: net_device pointer passed unmodified to notifier function
1995 * Call all network notifier blocks. Parameters and return value
1996 * are as for raw_notifier_call_chain().
1999 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2001 return call_netdevice_notifiers_extack(val, dev, NULL);
2003 EXPORT_SYMBOL(call_netdevice_notifiers);
2006 * call_netdevice_notifiers_mtu - call all network notifier blocks
2007 * @val: value passed unmodified to notifier function
2008 * @dev: net_device pointer passed unmodified to notifier function
2009 * @arg: additional u32 argument passed to the notifier function
2011 * Call all network notifier blocks. Parameters and return value
2012 * are as for raw_notifier_call_chain().
2014 static int call_netdevice_notifiers_mtu(unsigned long val,
2015 struct net_device *dev, u32 arg)
2017 struct netdev_notifier_info_ext info = {
2022 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2024 return call_netdevice_notifiers_info(val, &info.info);
2027 #ifdef CONFIG_NET_INGRESS
2028 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2030 void net_inc_ingress_queue(void)
2032 static_branch_inc(&ingress_needed_key);
2034 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2036 void net_dec_ingress_queue(void)
2038 static_branch_dec(&ingress_needed_key);
2040 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2043 #ifdef CONFIG_NET_EGRESS
2044 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2046 void net_inc_egress_queue(void)
2048 static_branch_inc(&egress_needed_key);
2050 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2052 void net_dec_egress_queue(void)
2054 static_branch_dec(&egress_needed_key);
2056 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2059 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2060 #ifdef CONFIG_JUMP_LABEL
2061 static atomic_t netstamp_needed_deferred;
2062 static atomic_t netstamp_wanted;
2063 static void netstamp_clear(struct work_struct *work)
2065 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2068 wanted = atomic_add_return(deferred, &netstamp_wanted);
2070 static_branch_enable(&netstamp_needed_key);
2072 static_branch_disable(&netstamp_needed_key);
2074 static DECLARE_WORK(netstamp_work, netstamp_clear);
2077 void net_enable_timestamp(void)
2079 #ifdef CONFIG_JUMP_LABEL
2083 wanted = atomic_read(&netstamp_wanted);
2086 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2089 atomic_inc(&netstamp_needed_deferred);
2090 schedule_work(&netstamp_work);
2092 static_branch_inc(&netstamp_needed_key);
2095 EXPORT_SYMBOL(net_enable_timestamp);
2097 void net_disable_timestamp(void)
2099 #ifdef CONFIG_JUMP_LABEL
2103 wanted = atomic_read(&netstamp_wanted);
2106 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2109 atomic_dec(&netstamp_needed_deferred);
2110 schedule_work(&netstamp_work);
2112 static_branch_dec(&netstamp_needed_key);
2115 EXPORT_SYMBOL(net_disable_timestamp);
2117 static inline void net_timestamp_set(struct sk_buff *skb)
2120 if (static_branch_unlikely(&netstamp_needed_key))
2121 __net_timestamp(skb);
2124 #define net_timestamp_check(COND, SKB) \
2125 if (static_branch_unlikely(&netstamp_needed_key)) { \
2126 if ((COND) && !(SKB)->tstamp) \
2127 __net_timestamp(SKB); \
2130 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2134 if (!(dev->flags & IFF_UP))
2137 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
2138 if (skb->len <= len)
2141 /* if TSO is enabled, we don't care about the length as the packet
2142 * could be forwarded without being segmented before
2144 if (skb_is_gso(skb))
2149 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2151 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2153 int ret = ____dev_forward_skb(dev, skb);
2156 skb->protocol = eth_type_trans(skb, dev);
2157 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2162 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2165 * dev_forward_skb - loopback an skb to another netif
2167 * @dev: destination network device
2168 * @skb: buffer to forward
2171 * NET_RX_SUCCESS (no congestion)
2172 * NET_RX_DROP (packet was dropped, but freed)
2174 * dev_forward_skb can be used for injecting an skb from the
2175 * start_xmit function of one device into the receive queue
2176 * of another device.
2178 * The receiving device may be in another namespace, so
2179 * we have to clear all information in the skb that could
2180 * impact namespace isolation.
2182 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2184 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2186 EXPORT_SYMBOL_GPL(dev_forward_skb);
2188 static inline int deliver_skb(struct sk_buff *skb,
2189 struct packet_type *pt_prev,
2190 struct net_device *orig_dev)
2192 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2194 refcount_inc(&skb->users);
2195 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2198 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2199 struct packet_type **pt,
2200 struct net_device *orig_dev,
2202 struct list_head *ptype_list)
2204 struct packet_type *ptype, *pt_prev = *pt;
2206 list_for_each_entry_rcu(ptype, ptype_list, list) {
2207 if (ptype->type != type)
2210 deliver_skb(skb, pt_prev, orig_dev);
2216 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2218 if (!ptype->af_packet_priv || !skb->sk)
2221 if (ptype->id_match)
2222 return ptype->id_match(ptype, skb->sk);
2223 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2230 * dev_nit_active - return true if any network interface taps are in use
2232 * @dev: network device to check for the presence of taps
2234 bool dev_nit_active(struct net_device *dev)
2236 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2238 EXPORT_SYMBOL_GPL(dev_nit_active);
2241 * Support routine. Sends outgoing frames to any network
2242 * taps currently in use.
2245 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2247 struct packet_type *ptype;
2248 struct sk_buff *skb2 = NULL;
2249 struct packet_type *pt_prev = NULL;
2250 struct list_head *ptype_list = &ptype_all;
2254 list_for_each_entry_rcu(ptype, ptype_list, list) {
2255 if (ptype->ignore_outgoing)
2258 /* Never send packets back to the socket
2259 * they originated from - MvS (miquels@drinkel.ow.org)
2261 if (skb_loop_sk(ptype, skb))
2265 deliver_skb(skb2, pt_prev, skb->dev);
2270 /* need to clone skb, done only once */
2271 skb2 = skb_clone(skb, GFP_ATOMIC);
2275 net_timestamp_set(skb2);
2277 /* skb->nh should be correctly
2278 * set by sender, so that the second statement is
2279 * just protection against buggy protocols.
2281 skb_reset_mac_header(skb2);
2283 if (skb_network_header(skb2) < skb2->data ||
2284 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2285 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2286 ntohs(skb2->protocol),
2288 skb_reset_network_header(skb2);
2291 skb2->transport_header = skb2->network_header;
2292 skb2->pkt_type = PACKET_OUTGOING;
2296 if (ptype_list == &ptype_all) {
2297 ptype_list = &dev->ptype_all;
2302 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2303 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2309 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2312 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2313 * @dev: Network device
2314 * @txq: number of queues available
2316 * If real_num_tx_queues is changed the tc mappings may no longer be
2317 * valid. To resolve this verify the tc mapping remains valid and if
2318 * not NULL the mapping. With no priorities mapping to this
2319 * offset/count pair it will no longer be used. In the worst case TC0
2320 * is invalid nothing can be done so disable priority mappings. If is
2321 * expected that drivers will fix this mapping if they can before
2322 * calling netif_set_real_num_tx_queues.
2324 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2327 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2329 /* If TC0 is invalidated disable TC mapping */
2330 if (tc->offset + tc->count > txq) {
2331 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2336 /* Invalidated prio to tc mappings set to TC0 */
2337 for (i = 1; i < TC_BITMASK + 1; i++) {
2338 int q = netdev_get_prio_tc_map(dev, i);
2340 tc = &dev->tc_to_txq[q];
2341 if (tc->offset + tc->count > txq) {
2342 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2344 netdev_set_prio_tc_map(dev, i, 0);
2349 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2352 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2355 /* walk through the TCs and see if it falls into any of them */
2356 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2357 if ((txq - tc->offset) < tc->count)
2361 /* didn't find it, just return -1 to indicate no match */
2367 EXPORT_SYMBOL(netdev_txq_to_tc);
2370 struct static_key xps_needed __read_mostly;
2371 EXPORT_SYMBOL(xps_needed);
2372 struct static_key xps_rxqs_needed __read_mostly;
2373 EXPORT_SYMBOL(xps_rxqs_needed);
2374 static DEFINE_MUTEX(xps_map_mutex);
2375 #define xmap_dereference(P) \
2376 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2378 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2381 struct xps_map *map = NULL;
2385 map = xmap_dereference(dev_maps->attr_map[tci]);
2389 for (pos = map->len; pos--;) {
2390 if (map->queues[pos] != index)
2394 map->queues[pos] = map->queues[--map->len];
2398 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2399 kfree_rcu(map, rcu);
2406 static bool remove_xps_queue_cpu(struct net_device *dev,
2407 struct xps_dev_maps *dev_maps,
2408 int cpu, u16 offset, u16 count)
2410 int num_tc = dev->num_tc ? : 1;
2411 bool active = false;
2414 for (tci = cpu * num_tc; num_tc--; tci++) {
2417 for (i = count, j = offset; i--; j++) {
2418 if (!remove_xps_queue(dev_maps, tci, j))
2428 static void reset_xps_maps(struct net_device *dev,
2429 struct xps_dev_maps *dev_maps,
2433 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2434 RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2436 RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2438 static_key_slow_dec_cpuslocked(&xps_needed);
2439 kfree_rcu(dev_maps, rcu);
2442 static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2443 struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2444 u16 offset, u16 count, bool is_rxqs_map)
2446 bool active = false;
2449 for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2451 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2454 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2457 for (i = offset + (count - 1); count--; i--) {
2458 netdev_queue_numa_node_write(
2459 netdev_get_tx_queue(dev, i),
2465 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2468 const unsigned long *possible_mask = NULL;
2469 struct xps_dev_maps *dev_maps;
2470 unsigned int nr_ids;
2472 if (!static_key_false(&xps_needed))
2476 mutex_lock(&xps_map_mutex);
2478 if (static_key_false(&xps_rxqs_needed)) {
2479 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2481 nr_ids = dev->num_rx_queues;
2482 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2483 offset, count, true);
2487 dev_maps = xmap_dereference(dev->xps_cpus_map);
2491 if (num_possible_cpus() > 1)
2492 possible_mask = cpumask_bits(cpu_possible_mask);
2493 nr_ids = nr_cpu_ids;
2494 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2498 mutex_unlock(&xps_map_mutex);
2502 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2504 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2507 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2508 u16 index, bool is_rxqs_map)
2510 struct xps_map *new_map;
2511 int alloc_len = XPS_MIN_MAP_ALLOC;
2514 for (pos = 0; map && pos < map->len; pos++) {
2515 if (map->queues[pos] != index)
2520 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2522 if (pos < map->alloc_len)
2525 alloc_len = map->alloc_len * 2;
2528 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2532 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2534 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2535 cpu_to_node(attr_index));
2539 for (i = 0; i < pos; i++)
2540 new_map->queues[i] = map->queues[i];
2541 new_map->alloc_len = alloc_len;
2547 /* Must be called under cpus_read_lock */
2548 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2549 u16 index, bool is_rxqs_map)
2551 const unsigned long *online_mask = NULL, *possible_mask = NULL;
2552 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2553 int i, j, tci, numa_node_id = -2;
2554 int maps_sz, num_tc = 1, tc = 0;
2555 struct xps_map *map, *new_map;
2556 bool active = false;
2557 unsigned int nr_ids;
2560 /* Do not allow XPS on subordinate device directly */
2561 num_tc = dev->num_tc;
2565 /* If queue belongs to subordinate dev use its map */
2566 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2568 tc = netdev_txq_to_tc(dev, index);
2573 mutex_lock(&xps_map_mutex);
2575 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2576 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2577 nr_ids = dev->num_rx_queues;
2579 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2580 if (num_possible_cpus() > 1) {
2581 online_mask = cpumask_bits(cpu_online_mask);
2582 possible_mask = cpumask_bits(cpu_possible_mask);
2584 dev_maps = xmap_dereference(dev->xps_cpus_map);
2585 nr_ids = nr_cpu_ids;
2588 if (maps_sz < L1_CACHE_BYTES)
2589 maps_sz = L1_CACHE_BYTES;
2591 /* allocate memory for queue storage */
2592 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2595 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2596 if (!new_dev_maps) {
2597 mutex_unlock(&xps_map_mutex);
2601 tci = j * num_tc + tc;
2602 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2605 map = expand_xps_map(map, j, index, is_rxqs_map);
2609 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2613 goto out_no_new_maps;
2616 /* Increment static keys at most once per type */
2617 static_key_slow_inc_cpuslocked(&xps_needed);
2619 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2622 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2624 /* copy maps belonging to foreign traffic classes */
2625 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2626 /* fill in the new device map from the old device map */
2627 map = xmap_dereference(dev_maps->attr_map[tci]);
2628 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2631 /* We need to explicitly update tci as prevous loop
2632 * could break out early if dev_maps is NULL.
2634 tci = j * num_tc + tc;
2636 if (netif_attr_test_mask(j, mask, nr_ids) &&
2637 netif_attr_test_online(j, online_mask, nr_ids)) {
2638 /* add tx-queue to CPU/rx-queue maps */
2641 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2642 while ((pos < map->len) && (map->queues[pos] != index))
2645 if (pos == map->len)
2646 map->queues[map->len++] = index;
2649 if (numa_node_id == -2)
2650 numa_node_id = cpu_to_node(j);
2651 else if (numa_node_id != cpu_to_node(j))
2655 } else if (dev_maps) {
2656 /* fill in the new device map from the old device map */
2657 map = xmap_dereference(dev_maps->attr_map[tci]);
2658 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2661 /* copy maps belonging to foreign traffic classes */
2662 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2663 /* fill in the new device map from the old device map */
2664 map = xmap_dereference(dev_maps->attr_map[tci]);
2665 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2670 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2672 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2674 /* Cleanup old maps */
2676 goto out_no_old_maps;
2678 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2680 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2681 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2682 map = xmap_dereference(dev_maps->attr_map[tci]);
2683 if (map && map != new_map)
2684 kfree_rcu(map, rcu);
2688 kfree_rcu(dev_maps, rcu);
2691 dev_maps = new_dev_maps;
2696 /* update Tx queue numa node */
2697 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2698 (numa_node_id >= 0) ?
2699 numa_node_id : NUMA_NO_NODE);
2705 /* removes tx-queue from unused CPUs/rx-queues */
2706 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2708 for (i = tc, tci = j * num_tc; i--; tci++)
2709 active |= remove_xps_queue(dev_maps, tci, index);
2710 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2711 !netif_attr_test_online(j, online_mask, nr_ids))
2712 active |= remove_xps_queue(dev_maps, tci, index);
2713 for (i = num_tc - tc, tci++; --i; tci++)
2714 active |= remove_xps_queue(dev_maps, tci, index);
2717 /* free map if not active */
2719 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2722 mutex_unlock(&xps_map_mutex);
2726 /* remove any maps that we added */
2727 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2729 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2730 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2732 xmap_dereference(dev_maps->attr_map[tci]) :
2734 if (new_map && new_map != map)
2739 mutex_unlock(&xps_map_mutex);
2741 kfree(new_dev_maps);
2744 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2746 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2752 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2757 EXPORT_SYMBOL(netif_set_xps_queue);
2760 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2762 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2764 /* Unbind any subordinate channels */
2765 while (txq-- != &dev->_tx[0]) {
2767 netdev_unbind_sb_channel(dev, txq->sb_dev);
2771 void netdev_reset_tc(struct net_device *dev)
2774 netif_reset_xps_queues_gt(dev, 0);
2776 netdev_unbind_all_sb_channels(dev);
2778 /* Reset TC configuration of device */
2780 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2781 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2783 EXPORT_SYMBOL(netdev_reset_tc);
2785 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2787 if (tc >= dev->num_tc)
2791 netif_reset_xps_queues(dev, offset, count);
2793 dev->tc_to_txq[tc].count = count;
2794 dev->tc_to_txq[tc].offset = offset;
2797 EXPORT_SYMBOL(netdev_set_tc_queue);
2799 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2801 if (num_tc > TC_MAX_QUEUE)
2805 netif_reset_xps_queues_gt(dev, 0);
2807 netdev_unbind_all_sb_channels(dev);
2809 dev->num_tc = num_tc;
2812 EXPORT_SYMBOL(netdev_set_num_tc);
2814 void netdev_unbind_sb_channel(struct net_device *dev,
2815 struct net_device *sb_dev)
2817 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2820 netif_reset_xps_queues_gt(sb_dev, 0);
2822 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2823 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2825 while (txq-- != &dev->_tx[0]) {
2826 if (txq->sb_dev == sb_dev)
2830 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2832 int netdev_bind_sb_channel_queue(struct net_device *dev,
2833 struct net_device *sb_dev,
2834 u8 tc, u16 count, u16 offset)
2836 /* Make certain the sb_dev and dev are already configured */
2837 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2840 /* We cannot hand out queues we don't have */
2841 if ((offset + count) > dev->real_num_tx_queues)
2844 /* Record the mapping */
2845 sb_dev->tc_to_txq[tc].count = count;
2846 sb_dev->tc_to_txq[tc].offset = offset;
2848 /* Provide a way for Tx queue to find the tc_to_txq map or
2849 * XPS map for itself.
2852 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2856 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2858 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2860 /* Do not use a multiqueue device to represent a subordinate channel */
2861 if (netif_is_multiqueue(dev))
2864 /* We allow channels 1 - 32767 to be used for subordinate channels.
2865 * Channel 0 is meant to be "native" mode and used only to represent
2866 * the main root device. We allow writing 0 to reset the device back
2867 * to normal mode after being used as a subordinate channel.
2869 if (channel > S16_MAX)
2872 dev->num_tc = -channel;
2876 EXPORT_SYMBOL(netdev_set_sb_channel);
2879 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2880 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2882 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2887 disabling = txq < dev->real_num_tx_queues;
2889 if (txq < 1 || txq > dev->num_tx_queues)
2892 if (dev->reg_state == NETREG_REGISTERED ||
2893 dev->reg_state == NETREG_UNREGISTERING) {
2896 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2902 netif_setup_tc(dev, txq);
2904 dev->real_num_tx_queues = txq;
2908 qdisc_reset_all_tx_gt(dev, txq);
2910 netif_reset_xps_queues_gt(dev, txq);
2914 dev->real_num_tx_queues = txq;
2919 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2923 * netif_set_real_num_rx_queues - set actual number of RX queues used
2924 * @dev: Network device
2925 * @rxq: Actual number of RX queues
2927 * This must be called either with the rtnl_lock held or before
2928 * registration of the net device. Returns 0 on success, or a
2929 * negative error code. If called before registration, it always
2932 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2936 if (rxq < 1 || rxq > dev->num_rx_queues)
2939 if (dev->reg_state == NETREG_REGISTERED) {
2942 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2948 dev->real_num_rx_queues = rxq;
2951 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2955 * netif_get_num_default_rss_queues - default number of RSS queues
2957 * This routine should set an upper limit on the number of RSS queues
2958 * used by default by multiqueue devices.
2960 int netif_get_num_default_rss_queues(void)
2962 return is_kdump_kernel() ?
2963 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
2965 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
2967 static void __netif_reschedule(struct Qdisc *q)
2969 struct softnet_data *sd;
2970 unsigned long flags;
2972 local_irq_save(flags);
2973 sd = this_cpu_ptr(&softnet_data);
2974 q->next_sched = NULL;
2975 *sd->output_queue_tailp = q;
2976 sd->output_queue_tailp = &q->next_sched;
2977 raise_softirq_irqoff(NET_TX_SOFTIRQ);
2978 local_irq_restore(flags);
2981 void __netif_schedule(struct Qdisc *q)
2983 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
2984 __netif_reschedule(q);
2986 EXPORT_SYMBOL(__netif_schedule);
2988 struct dev_kfree_skb_cb {
2989 enum skb_free_reason reason;
2992 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
2994 return (struct dev_kfree_skb_cb *)skb->cb;
2997 void netif_schedule_queue(struct netdev_queue *txq)
3000 if (!netif_xmit_stopped(txq)) {
3001 struct Qdisc *q = rcu_dereference(txq->qdisc);
3003 __netif_schedule(q);
3007 EXPORT_SYMBOL(netif_schedule_queue);
3009 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3011 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3015 q = rcu_dereference(dev_queue->qdisc);
3016 __netif_schedule(q);
3020 EXPORT_SYMBOL(netif_tx_wake_queue);
3022 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3024 unsigned long flags;
3029 if (likely(refcount_read(&skb->users) == 1)) {
3031 refcount_set(&skb->users, 0);
3032 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3035 get_kfree_skb_cb(skb)->reason = reason;
3036 local_irq_save(flags);
3037 skb->next = __this_cpu_read(softnet_data.completion_queue);
3038 __this_cpu_write(softnet_data.completion_queue, skb);
3039 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3040 local_irq_restore(flags);
3042 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3044 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3046 if (in_irq() || irqs_disabled())
3047 __dev_kfree_skb_irq(skb, reason);
3051 EXPORT_SYMBOL(__dev_kfree_skb_any);
3055 * netif_device_detach - mark device as removed
3056 * @dev: network device
3058 * Mark device as removed from system and therefore no longer available.
3060 void netif_device_detach(struct net_device *dev)
3062 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3063 netif_running(dev)) {
3064 netif_tx_stop_all_queues(dev);
3067 EXPORT_SYMBOL(netif_device_detach);
3070 * netif_device_attach - mark device as attached
3071 * @dev: network device
3073 * Mark device as attached from system and restart if needed.
3075 void netif_device_attach(struct net_device *dev)
3077 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3078 netif_running(dev)) {
3079 netif_tx_wake_all_queues(dev);
3080 __netdev_watchdog_up(dev);
3083 EXPORT_SYMBOL(netif_device_attach);
3086 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3087 * to be used as a distribution range.
3089 static u16 skb_tx_hash(const struct net_device *dev,
3090 const struct net_device *sb_dev,
3091 struct sk_buff *skb)
3095 u16 qcount = dev->real_num_tx_queues;
3098 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3100 qoffset = sb_dev->tc_to_txq[tc].offset;
3101 qcount = sb_dev->tc_to_txq[tc].count;
3104 if (skb_rx_queue_recorded(skb)) {
3105 hash = skb_get_rx_queue(skb);
3106 while (unlikely(hash >= qcount))
3108 return hash + qoffset;
3111 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3114 static void skb_warn_bad_offload(const struct sk_buff *skb)
3116 static const netdev_features_t null_features;
3117 struct net_device *dev = skb->dev;
3118 const char *name = "";
3120 if (!net_ratelimit())
3124 if (dev->dev.parent)
3125 name = dev_driver_string(dev->dev.parent);
3127 name = netdev_name(dev);
3129 skb_dump(KERN_WARNING, skb, false);
3130 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3131 name, dev ? &dev->features : &null_features,
3132 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3136 * Invalidate hardware checksum when packet is to be mangled, and
3137 * complete checksum manually on outgoing path.
3139 int skb_checksum_help(struct sk_buff *skb)
3142 int ret = 0, offset;
3144 if (skb->ip_summed == CHECKSUM_COMPLETE)
3145 goto out_set_summed;
3147 if (unlikely(skb_shinfo(skb)->gso_size)) {
3148 skb_warn_bad_offload(skb);
3152 /* Before computing a checksum, we should make sure no frag could
3153 * be modified by an external entity : checksum could be wrong.
3155 if (skb_has_shared_frag(skb)) {
3156 ret = __skb_linearize(skb);
3161 offset = skb_checksum_start_offset(skb);
3162 BUG_ON(offset >= skb_headlen(skb));
3163 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3165 offset += skb->csum_offset;
3166 BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
3168 if (skb_cloned(skb) &&
3169 !skb_clone_writable(skb, offset + sizeof(__sum16))) {
3170 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
3175 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3177 skb->ip_summed = CHECKSUM_NONE;
3181 EXPORT_SYMBOL(skb_checksum_help);
3183 int skb_crc32c_csum_help(struct sk_buff *skb)
3186 int ret = 0, offset, start;
3188 if (skb->ip_summed != CHECKSUM_PARTIAL)
3191 if (unlikely(skb_is_gso(skb)))
3194 /* Before computing a checksum, we should make sure no frag could
3195 * be modified by an external entity : checksum could be wrong.
3197 if (unlikely(skb_has_shared_frag(skb))) {
3198 ret = __skb_linearize(skb);
3202 start = skb_checksum_start_offset(skb);
3203 offset = start + offsetof(struct sctphdr, checksum);
3204 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3208 if (skb_cloned(skb) &&
3209 !skb_clone_writable(skb, offset + sizeof(__le32))) {
3210 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
3214 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3215 skb->len - start, ~(__u32)0,
3217 *(__le32 *)(skb->data + offset) = crc32c_csum;
3218 skb->ip_summed = CHECKSUM_NONE;
3219 skb->csum_not_inet = 0;
3224 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3226 __be16 type = skb->protocol;
3228 /* Tunnel gso handlers can set protocol to ethernet. */
3229 if (type == htons(ETH_P_TEB)) {
3232 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3235 eth = (struct ethhdr *)skb->data;
3236 type = eth->h_proto;
3239 return __vlan_get_protocol(skb, type, depth);
3243 * skb_mac_gso_segment - mac layer segmentation handler.
3244 * @skb: buffer to segment
3245 * @features: features for the output path (see dev->features)
3247 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3248 netdev_features_t features)
3250 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3251 struct packet_offload *ptype;
3252 int vlan_depth = skb->mac_len;
3253 __be16 type = skb_network_protocol(skb, &vlan_depth);
3255 if (unlikely(!type))
3256 return ERR_PTR(-EINVAL);
3258 __skb_pull(skb, vlan_depth);
3261 list_for_each_entry_rcu(ptype, &offload_base, list) {
3262 if (ptype->type == type && ptype->callbacks.gso_segment) {
3263 segs = ptype->callbacks.gso_segment(skb, features);
3269 __skb_push(skb, skb->data - skb_mac_header(skb));
3273 EXPORT_SYMBOL(skb_mac_gso_segment);
3276 /* openvswitch calls this on rx path, so we need a different check.
3278 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3281 return skb->ip_summed != CHECKSUM_PARTIAL &&
3282 skb->ip_summed != CHECKSUM_UNNECESSARY;
3284 return skb->ip_summed == CHECKSUM_NONE;
3288 * __skb_gso_segment - Perform segmentation on skb.
3289 * @skb: buffer to segment
3290 * @features: features for the output path (see dev->features)
3291 * @tx_path: whether it is called in TX path
3293 * This function segments the given skb and returns a list of segments.
3295 * It may return NULL if the skb requires no segmentation. This is
3296 * only possible when GSO is used for verifying header integrity.
3298 * Segmentation preserves SKB_SGO_CB_OFFSET bytes of previous skb cb.
3300 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3301 netdev_features_t features, bool tx_path)
3303 struct sk_buff *segs;
3305 if (unlikely(skb_needs_check(skb, tx_path))) {
3308 /* We're going to init ->check field in TCP or UDP header */
3309 err = skb_cow_head(skb, 0);
3311 return ERR_PTR(err);
3314 /* Only report GSO partial support if it will enable us to
3315 * support segmentation on this frame without needing additional
3318 if (features & NETIF_F_GSO_PARTIAL) {
3319 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3320 struct net_device *dev = skb->dev;
3322 partial_features |= dev->features & dev->gso_partial_features;
3323 if (!skb_gso_ok(skb, features | partial_features))
3324 features &= ~NETIF_F_GSO_PARTIAL;
3327 BUILD_BUG_ON(SKB_SGO_CB_OFFSET +
3328 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3330 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3331 SKB_GSO_CB(skb)->encap_level = 0;
3333 skb_reset_mac_header(skb);
3334 skb_reset_mac_len(skb);
3336 segs = skb_mac_gso_segment(skb, features);
3338 if (unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3339 skb_warn_bad_offload(skb);
3343 EXPORT_SYMBOL(__skb_gso_segment);
3345 /* Take action when hardware reception checksum errors are detected. */
3347 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3349 if (net_ratelimit()) {
3350 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3351 skb_dump(KERN_ERR, skb, true);
3355 EXPORT_SYMBOL(netdev_rx_csum_fault);
3358 /* XXX: check that highmem exists at all on the given machine. */
3359 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3361 #ifdef CONFIG_HIGHMEM
3364 if (!(dev->features & NETIF_F_HIGHDMA)) {
3365 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3366 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3368 if (PageHighMem(skb_frag_page(frag)))
3376 /* If MPLS offload request, verify we are testing hardware MPLS features
3377 * instead of standard features for the netdev.
3379 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3380 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3381 netdev_features_t features,
3384 if (eth_p_mpls(type))
3385 features &= skb->dev->mpls_features;
3390 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3391 netdev_features_t features,
3398 static netdev_features_t harmonize_features(struct sk_buff *skb,
3399 netdev_features_t features)
3404 type = skb_network_protocol(skb, &tmp);
3405 features = net_mpls_features(skb, features, type);
3407 if (skb->ip_summed != CHECKSUM_NONE &&
3408 !can_checksum_protocol(features, type)) {
3409 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3411 if (illegal_highdma(skb->dev, skb))
3412 features &= ~NETIF_F_SG;
3417 netdev_features_t passthru_features_check(struct sk_buff *skb,
3418 struct net_device *dev,
3419 netdev_features_t features)
3423 EXPORT_SYMBOL(passthru_features_check);
3425 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3426 struct net_device *dev,
3427 netdev_features_t features)
3429 return vlan_features_check(skb, features);
3432 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3433 struct net_device *dev,
3434 netdev_features_t features)
3436 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3438 if (gso_segs > dev->gso_max_segs)
3439 return features & ~NETIF_F_GSO_MASK;
3441 /* Support for GSO partial features requires software
3442 * intervention before we can actually process the packets
3443 * so we need to strip support for any partial features now
3444 * and we can pull them back in after we have partially
3445 * segmented the frame.
3447 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3448 features &= ~dev->gso_partial_features;
3450 /* Make sure to clear the IPv4 ID mangling feature if the
3451 * IPv4 header has the potential to be fragmented.
3453 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3454 struct iphdr *iph = skb->encapsulation ?
3455 inner_ip_hdr(skb) : ip_hdr(skb);
3457 if (!(iph->frag_off & htons(IP_DF)))
3458 features &= ~NETIF_F_TSO_MANGLEID;
3464 netdev_features_t netif_skb_features(struct sk_buff *skb)
3466 struct net_device *dev = skb->dev;
3467 netdev_features_t features = dev->features;
3469 if (skb_is_gso(skb))
3470 features = gso_features_check(skb, dev, features);
3472 /* If encapsulation offload request, verify we are testing
3473 * hardware encapsulation features instead of standard
3474 * features for the netdev
3476 if (skb->encapsulation)
3477 features &= dev->hw_enc_features;
3479 if (skb_vlan_tagged(skb))
3480 features = netdev_intersect_features(features,
3481 dev->vlan_features |
3482 NETIF_F_HW_VLAN_CTAG_TX |
3483 NETIF_F_HW_VLAN_STAG_TX);
3485 if (dev->netdev_ops->ndo_features_check)
3486 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3489 features &= dflt_features_check(skb, dev, features);
3491 return harmonize_features(skb, features);
3493 EXPORT_SYMBOL(netif_skb_features);
3495 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3496 struct netdev_queue *txq, bool more)
3501 if (dev_nit_active(dev))
3502 dev_queue_xmit_nit(skb, dev);
3505 trace_net_dev_start_xmit(skb, dev);
3506 rc = netdev_start_xmit(skb, dev, txq, more);
3507 trace_net_dev_xmit(skb, rc, dev, len);
3512 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3513 struct netdev_queue *txq, int *ret)
3515 struct sk_buff *skb = first;
3516 int rc = NETDEV_TX_OK;
3519 struct sk_buff *next = skb->next;
3521 skb_mark_not_on_list(skb);
3522 rc = xmit_one(skb, dev, txq, next != NULL);
3523 if (unlikely(!dev_xmit_complete(rc))) {
3529 if (netif_tx_queue_stopped(txq) && skb) {
3530 rc = NETDEV_TX_BUSY;
3540 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3541 netdev_features_t features)
3543 if (skb_vlan_tag_present(skb) &&
3544 !vlan_hw_offload_capable(features, skb->vlan_proto))
3545 skb = __vlan_hwaccel_push_inside(skb);
3549 int skb_csum_hwoffload_help(struct sk_buff *skb,
3550 const netdev_features_t features)
3552 if (unlikely(skb->csum_not_inet))
3553 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3554 skb_crc32c_csum_help(skb);
3556 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3558 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3560 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3562 netdev_features_t features;
3564 features = netif_skb_features(skb);
3565 skb = validate_xmit_vlan(skb, features);
3569 skb = sk_validate_xmit_skb(skb, dev);
3573 if (netif_needs_gso(skb, features)) {
3574 struct sk_buff *segs;
3576 segs = skb_gso_segment(skb, features);
3584 if (skb_needs_linearize(skb, features) &&
3585 __skb_linearize(skb))
3588 /* If packet is not checksummed and device does not
3589 * support checksumming for this protocol, complete
3590 * checksumming here.
3592 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3593 if (skb->encapsulation)
3594 skb_set_inner_transport_header(skb,
3595 skb_checksum_start_offset(skb));
3597 skb_set_transport_header(skb,
3598 skb_checksum_start_offset(skb));
3599 if (skb_csum_hwoffload_help(skb, features))
3604 skb = validate_xmit_xfrm(skb, features, again);
3611 atomic_long_inc(&dev->tx_dropped);
3615 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3617 struct sk_buff *next, *head = NULL, *tail;
3619 for (; skb != NULL; skb = next) {
3621 skb_mark_not_on_list(skb);
3623 /* in case skb wont be segmented, point to itself */
3626 skb = validate_xmit_skb(skb, dev, again);
3634 /* If skb was segmented, skb->prev points to
3635 * the last segment. If not, it still contains skb.
3641 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3643 static void qdisc_pkt_len_init(struct sk_buff *skb)
3645 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3647 qdisc_skb_cb(skb)->pkt_len = skb->len;
3649 /* To get more precise estimation of bytes sent on wire,
3650 * we add to pkt_len the headers size of all segments
3652 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3653 unsigned int hdr_len;
3654 u16 gso_segs = shinfo->gso_segs;
3656 /* mac layer + network layer */
3657 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3659 /* + transport layer */
3660 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3661 const struct tcphdr *th;
3662 struct tcphdr _tcphdr;
3664 th = skb_header_pointer(skb, skb_transport_offset(skb),
3665 sizeof(_tcphdr), &_tcphdr);
3667 hdr_len += __tcp_hdrlen(th);
3669 struct udphdr _udphdr;
3671 if (skb_header_pointer(skb, skb_transport_offset(skb),
3672 sizeof(_udphdr), &_udphdr))
3673 hdr_len += sizeof(struct udphdr);
3676 if (shinfo->gso_type & SKB_GSO_DODGY)
3677 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3680 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3684 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3685 struct net_device *dev,
3686 struct netdev_queue *txq)
3688 spinlock_t *root_lock = qdisc_lock(q);
3689 struct sk_buff *to_free = NULL;
3693 qdisc_calculate_pkt_len(skb, q);
3695 if (q->flags & TCQ_F_NOLOCK) {
3696 if ((q->flags & TCQ_F_CAN_BYPASS) && q->empty &&
3697 qdisc_run_begin(q)) {
3698 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
3700 __qdisc_drop(skb, &to_free);
3704 qdisc_bstats_cpu_update(q, skb);
3706 rc = NET_XMIT_SUCCESS;
3707 if (sch_direct_xmit(skb, q, dev, txq, NULL, true))
3713 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3717 if (unlikely(to_free))
3718 kfree_skb_list(to_free);
3723 * Heuristic to force contended enqueues to serialize on a
3724 * separate lock before trying to get qdisc main lock.
3725 * This permits qdisc->running owner to get the lock more
3726 * often and dequeue packets faster.
3728 contended = qdisc_is_running(q);
3729 if (unlikely(contended))
3730 spin_lock(&q->busylock);
3732 spin_lock(root_lock);
3733 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3734 __qdisc_drop(skb, &to_free);
3736 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3737 qdisc_run_begin(q)) {
3739 * This is a work-conserving queue; there are no old skbs
3740 * waiting to be sent out; and the qdisc is not running -
3741 * xmit the skb directly.
3744 qdisc_bstats_update(q, skb);
3746 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3747 if (unlikely(contended)) {
3748 spin_unlock(&q->busylock);
3755 rc = NET_XMIT_SUCCESS;
3757 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3758 if (qdisc_run_begin(q)) {
3759 if (unlikely(contended)) {
3760 spin_unlock(&q->busylock);
3767 spin_unlock(root_lock);
3768 if (unlikely(to_free))
3769 kfree_skb_list(to_free);
3770 if (unlikely(contended))
3771 spin_unlock(&q->busylock);
3775 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3776 static void skb_update_prio(struct sk_buff *skb)
3778 const struct netprio_map *map;
3779 const struct sock *sk;
3780 unsigned int prioidx;
3784 map = rcu_dereference_bh(skb->dev->priomap);
3787 sk = skb_to_full_sk(skb);
3791 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3793 if (prioidx < map->priomap_len)
3794 skb->priority = map->priomap[prioidx];
3797 #define skb_update_prio(skb)
3801 * dev_loopback_xmit - loop back @skb
3802 * @net: network namespace this loopback is happening in
3803 * @sk: sk needed to be a netfilter okfn
3804 * @skb: buffer to transmit
3806 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3808 skb_reset_mac_header(skb);
3809 __skb_pull(skb, skb_network_offset(skb));
3810 skb->pkt_type = PACKET_LOOPBACK;
3811 skb->ip_summed = CHECKSUM_UNNECESSARY;
3812 WARN_ON(!skb_dst(skb));
3817 EXPORT_SYMBOL(dev_loopback_xmit);
3819 #ifdef CONFIG_NET_EGRESS
3820 static struct sk_buff *
3821 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3823 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3824 struct tcf_result cl_res;
3829 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3830 mini_qdisc_bstats_cpu_update(miniq, skb);
3832 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3834 case TC_ACT_RECLASSIFY:
3835 skb->tc_index = TC_H_MIN(cl_res.classid);
3838 mini_qdisc_qstats_cpu_drop(miniq);
3839 *ret = NET_XMIT_DROP;
3845 *ret = NET_XMIT_SUCCESS;
3848 case TC_ACT_REDIRECT:
3849 /* No need to push/pop skb's mac_header here on egress! */
3850 skb_do_redirect(skb);
3851 *ret = NET_XMIT_SUCCESS;
3859 #endif /* CONFIG_NET_EGRESS */
3862 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3863 struct xps_dev_maps *dev_maps, unsigned int tci)
3865 struct xps_map *map;
3866 int queue_index = -1;
3870 tci += netdev_get_prio_tc_map(dev, skb->priority);
3873 map = rcu_dereference(dev_maps->attr_map[tci]);
3876 queue_index = map->queues[0];
3878 queue_index = map->queues[reciprocal_scale(
3879 skb_get_hash(skb), map->len)];
3880 if (unlikely(queue_index >= dev->real_num_tx_queues))
3887 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3888 struct sk_buff *skb)
3891 struct xps_dev_maps *dev_maps;
3892 struct sock *sk = skb->sk;
3893 int queue_index = -1;
3895 if (!static_key_false(&xps_needed))
3899 if (!static_key_false(&xps_rxqs_needed))
3902 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3904 int tci = sk_rx_queue_get(sk);
3906 if (tci >= 0 && tci < dev->num_rx_queues)
3907 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3912 if (queue_index < 0) {
3913 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3915 unsigned int tci = skb->sender_cpu - 1;
3917 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3929 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3930 struct net_device *sb_dev)
3934 EXPORT_SYMBOL(dev_pick_tx_zero);
3936 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
3937 struct net_device *sb_dev)
3939 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
3941 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
3943 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
3944 struct net_device *sb_dev)
3946 struct sock *sk = skb->sk;
3947 int queue_index = sk_tx_queue_get(sk);
3949 sb_dev = sb_dev ? : dev;
3951 if (queue_index < 0 || skb->ooo_okay ||
3952 queue_index >= dev->real_num_tx_queues) {
3953 int new_index = get_xps_queue(dev, sb_dev, skb);
3956 new_index = skb_tx_hash(dev, sb_dev, skb);
3958 if (queue_index != new_index && sk &&
3960 rcu_access_pointer(sk->sk_dst_cache))
3961 sk_tx_queue_set(sk, new_index);
3963 queue_index = new_index;
3968 EXPORT_SYMBOL(netdev_pick_tx);
3970 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
3971 struct sk_buff *skb,
3972 struct net_device *sb_dev)
3974 int queue_index = 0;
3977 u32 sender_cpu = skb->sender_cpu - 1;
3979 if (sender_cpu >= (u32)NR_CPUS)
3980 skb->sender_cpu = raw_smp_processor_id() + 1;
3983 if (dev->real_num_tx_queues != 1) {
3984 const struct net_device_ops *ops = dev->netdev_ops;
3986 if (ops->ndo_select_queue)
3987 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
3989 queue_index = netdev_pick_tx(dev, skb, sb_dev);
3991 queue_index = netdev_cap_txqueue(dev, queue_index);
3994 skb_set_queue_mapping(skb, queue_index);
3995 return netdev_get_tx_queue(dev, queue_index);
3999 * __dev_queue_xmit - transmit a buffer
4000 * @skb: buffer to transmit
4001 * @sb_dev: suboordinate device used for L2 forwarding offload
4003 * Queue a buffer for transmission to a network device. The caller must
4004 * have set the device and priority and built the buffer before calling
4005 * this function. The function can be called from an interrupt.
4007 * A negative errno code is returned on a failure. A success does not
4008 * guarantee the frame will be transmitted as it may be dropped due
4009 * to congestion or traffic shaping.
4011 * -----------------------------------------------------------------------------------
4012 * I notice this method can also return errors from the queue disciplines,
4013 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4016 * Regardless of the return value, the skb is consumed, so it is currently
4017 * difficult to retry a send to this method. (You can bump the ref count
4018 * before sending to hold a reference for retry if you are careful.)
4020 * When calling this method, interrupts MUST be enabled. This is because
4021 * the BH enable code must have IRQs enabled so that it will not deadlock.
4024 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4026 struct net_device *dev = skb->dev;
4027 struct netdev_queue *txq;
4032 skb_reset_mac_header(skb);
4034 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4035 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
4037 /* Disable soft irqs for various locks below. Also
4038 * stops preemption for RCU.
4042 skb_update_prio(skb);
4044 qdisc_pkt_len_init(skb);
4045 #ifdef CONFIG_NET_CLS_ACT
4046 skb->tc_at_ingress = 0;
4047 # ifdef CONFIG_NET_EGRESS
4048 if (static_branch_unlikely(&egress_needed_key)) {
4049 skb = sch_handle_egress(skb, &rc, dev);
4055 /* If device/qdisc don't need skb->dst, release it right now while
4056 * its hot in this cpu cache.
4058 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4063 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4064 q = rcu_dereference_bh(txq->qdisc);
4066 trace_net_dev_queue(skb);
4068 rc = __dev_xmit_skb(skb, q, dev, txq);
4072 /* The device has no queue. Common case for software devices:
4073 * loopback, all the sorts of tunnels...
4075 * Really, it is unlikely that netif_tx_lock protection is necessary
4076 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4078 * However, it is possible, that they rely on protection
4081 * Check this and shot the lock. It is not prone from deadlocks.
4082 *Either shot noqueue qdisc, it is even simpler 8)
4084 if (dev->flags & IFF_UP) {
4085 int cpu = smp_processor_id(); /* ok because BHs are off */
4087 if (txq->xmit_lock_owner != cpu) {
4088 if (dev_xmit_recursion())
4089 goto recursion_alert;
4091 skb = validate_xmit_skb(skb, dev, &again);
4095 HARD_TX_LOCK(dev, txq, cpu);
4097 if (!netif_xmit_stopped(txq)) {
4098 dev_xmit_recursion_inc();
4099 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4100 dev_xmit_recursion_dec();
4101 if (dev_xmit_complete(rc)) {
4102 HARD_TX_UNLOCK(dev, txq);
4106 HARD_TX_UNLOCK(dev, txq);
4107 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4110 /* Recursion is detected! It is possible,
4114 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4120 rcu_read_unlock_bh();
4122 atomic_long_inc(&dev->tx_dropped);
4123 kfree_skb_list(skb);
4126 rcu_read_unlock_bh();
4130 int dev_queue_xmit(struct sk_buff *skb)
4132 return __dev_queue_xmit(skb, NULL);
4134 EXPORT_SYMBOL(dev_queue_xmit);
4136 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4138 return __dev_queue_xmit(skb, sb_dev);
4140 EXPORT_SYMBOL(dev_queue_xmit_accel);
4142 int dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4144 struct net_device *dev = skb->dev;
4145 struct sk_buff *orig_skb = skb;
4146 struct netdev_queue *txq;
4147 int ret = NETDEV_TX_BUSY;
4150 if (unlikely(!netif_running(dev) ||
4151 !netif_carrier_ok(dev)))
4154 skb = validate_xmit_skb_list(skb, dev, &again);
4155 if (skb != orig_skb)
4158 skb_set_queue_mapping(skb, queue_id);
4159 txq = skb_get_tx_queue(dev, skb);
4163 HARD_TX_LOCK(dev, txq, smp_processor_id());
4164 if (!netif_xmit_frozen_or_drv_stopped(txq))
4165 ret = netdev_start_xmit(skb, dev, txq, false);
4166 HARD_TX_UNLOCK(dev, txq);
4170 if (!dev_xmit_complete(ret))
4175 atomic_long_inc(&dev->tx_dropped);
4176 kfree_skb_list(skb);
4177 return NET_XMIT_DROP;
4179 EXPORT_SYMBOL(dev_direct_xmit);
4181 /*************************************************************************
4183 *************************************************************************/
4185 int netdev_max_backlog __read_mostly = 1000;
4186 EXPORT_SYMBOL(netdev_max_backlog);
4188 int netdev_tstamp_prequeue __read_mostly = 1;
4189 int netdev_budget __read_mostly = 300;
4190 unsigned int __read_mostly netdev_budget_usecs = 2000;
4191 int weight_p __read_mostly = 64; /* old backlog weight */
4192 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4193 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4194 int dev_rx_weight __read_mostly = 64;
4195 int dev_tx_weight __read_mostly = 64;
4196 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4197 int gro_normal_batch __read_mostly = 8;
4199 /* Called with irq disabled */
4200 static inline void ____napi_schedule(struct softnet_data *sd,
4201 struct napi_struct *napi)
4203 list_add_tail(&napi->poll_list, &sd->poll_list);
4204 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4209 /* One global table that all flow-based protocols share. */
4210 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4211 EXPORT_SYMBOL(rps_sock_flow_table);
4212 u32 rps_cpu_mask __read_mostly;
4213 EXPORT_SYMBOL(rps_cpu_mask);
4215 struct static_key_false rps_needed __read_mostly;
4216 EXPORT_SYMBOL(rps_needed);
4217 struct static_key_false rfs_needed __read_mostly;
4218 EXPORT_SYMBOL(rfs_needed);
4220 static struct rps_dev_flow *
4221 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4222 struct rps_dev_flow *rflow, u16 next_cpu)
4224 if (next_cpu < nr_cpu_ids) {
4225 #ifdef CONFIG_RFS_ACCEL
4226 struct netdev_rx_queue *rxqueue;
4227 struct rps_dev_flow_table *flow_table;
4228 struct rps_dev_flow *old_rflow;
4233 /* Should we steer this flow to a different hardware queue? */
4234 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4235 !(dev->features & NETIF_F_NTUPLE))
4237 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4238 if (rxq_index == skb_get_rx_queue(skb))
4241 rxqueue = dev->_rx + rxq_index;
4242 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4245 flow_id = skb_get_hash(skb) & flow_table->mask;
4246 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4247 rxq_index, flow_id);
4251 rflow = &flow_table->flows[flow_id];
4253 if (old_rflow->filter == rflow->filter)
4254 old_rflow->filter = RPS_NO_FILTER;
4258 per_cpu(softnet_data, next_cpu).input_queue_head;
4261 rflow->cpu = next_cpu;
4266 * get_rps_cpu is called from netif_receive_skb and returns the target
4267 * CPU from the RPS map of the receiving queue for a given skb.
4268 * rcu_read_lock must be held on entry.
4270 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4271 struct rps_dev_flow **rflowp)
4273 const struct rps_sock_flow_table *sock_flow_table;
4274 struct netdev_rx_queue *rxqueue = dev->_rx;
4275 struct rps_dev_flow_table *flow_table;
4276 struct rps_map *map;
4281 if (skb_rx_queue_recorded(skb)) {
4282 u16 index = skb_get_rx_queue(skb);
4284 if (unlikely(index >= dev->real_num_rx_queues)) {
4285 WARN_ONCE(dev->real_num_rx_queues > 1,
4286 "%s received packet on queue %u, but number "
4287 "of RX queues is %u\n",
4288 dev->name, index, dev->real_num_rx_queues);
4294 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4296 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4297 map = rcu_dereference(rxqueue->rps_map);
4298 if (!flow_table && !map)
4301 skb_reset_network_header(skb);
4302 hash = skb_get_hash(skb);
4306 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4307 if (flow_table && sock_flow_table) {
4308 struct rps_dev_flow *rflow;
4312 /* First check into global flow table if there is a match */
4313 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4314 if ((ident ^ hash) & ~rps_cpu_mask)
4317 next_cpu = ident & rps_cpu_mask;
4319 /* OK, now we know there is a match,
4320 * we can look at the local (per receive queue) flow table
4322 rflow = &flow_table->flows[hash & flow_table->mask];
4326 * If the desired CPU (where last recvmsg was done) is
4327 * different from current CPU (one in the rx-queue flow
4328 * table entry), switch if one of the following holds:
4329 * - Current CPU is unset (>= nr_cpu_ids).
4330 * - Current CPU is offline.
4331 * - The current CPU's queue tail has advanced beyond the
4332 * last packet that was enqueued using this table entry.
4333 * This guarantees that all previous packets for the flow
4334 * have been dequeued, thus preserving in order delivery.
4336 if (unlikely(tcpu != next_cpu) &&
4337 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4338 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4339 rflow->last_qtail)) >= 0)) {
4341 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4344 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4354 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4355 if (cpu_online(tcpu)) {
4365 #ifdef CONFIG_RFS_ACCEL
4368 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4369 * @dev: Device on which the filter was set
4370 * @rxq_index: RX queue index
4371 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4372 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4374 * Drivers that implement ndo_rx_flow_steer() should periodically call
4375 * this function for each installed filter and remove the filters for
4376 * which it returns %true.
4378 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4379 u32 flow_id, u16 filter_id)
4381 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4382 struct rps_dev_flow_table *flow_table;
4383 struct rps_dev_flow *rflow;
4388 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4389 if (flow_table && flow_id <= flow_table->mask) {
4390 rflow = &flow_table->flows[flow_id];
4391 cpu = READ_ONCE(rflow->cpu);
4392 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4393 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4394 rflow->last_qtail) <
4395 (int)(10 * flow_table->mask)))
4401 EXPORT_SYMBOL(rps_may_expire_flow);
4403 #endif /* CONFIG_RFS_ACCEL */
4405 /* Called from hardirq (IPI) context */
4406 static void rps_trigger_softirq(void *data)
4408 struct softnet_data *sd = data;
4410 ____napi_schedule(sd, &sd->backlog);
4414 #endif /* CONFIG_RPS */
4417 * Check if this softnet_data structure is another cpu one
4418 * If yes, queue it to our IPI list and return 1
4421 static int rps_ipi_queued(struct softnet_data *sd)
4424 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4427 sd->rps_ipi_next = mysd->rps_ipi_list;
4428 mysd->rps_ipi_list = sd;
4430 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4433 #endif /* CONFIG_RPS */
4437 #ifdef CONFIG_NET_FLOW_LIMIT
4438 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4441 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4443 #ifdef CONFIG_NET_FLOW_LIMIT
4444 struct sd_flow_limit *fl;
4445 struct softnet_data *sd;
4446 unsigned int old_flow, new_flow;
4448 if (qlen < (netdev_max_backlog >> 1))
4451 sd = this_cpu_ptr(&softnet_data);
4454 fl = rcu_dereference(sd->flow_limit);
4456 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4457 old_flow = fl->history[fl->history_head];
4458 fl->history[fl->history_head] = new_flow;
4461 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4463 if (likely(fl->buckets[old_flow]))
4464 fl->buckets[old_flow]--;
4466 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4478 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4479 * queue (may be a remote CPU queue).
4481 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4482 unsigned int *qtail)
4484 struct softnet_data *sd;
4485 unsigned long flags;
4488 sd = &per_cpu(softnet_data, cpu);
4490 local_irq_save(flags);
4493 if (!netif_running(skb->dev))
4495 qlen = skb_queue_len(&sd->input_pkt_queue);
4496 if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
4499 __skb_queue_tail(&sd->input_pkt_queue, skb);
4500 input_queue_tail_incr_save(sd, qtail);
4502 local_irq_restore(flags);
4503 return NET_RX_SUCCESS;
4506 /* Schedule NAPI for backlog device
4507 * We can use non atomic operation since we own the queue lock
4509 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4510 if (!rps_ipi_queued(sd))
4511 ____napi_schedule(sd, &sd->backlog);
4520 local_irq_restore(flags);
4522 atomic_long_inc(&skb->dev->rx_dropped);
4527 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4529 struct net_device *dev = skb->dev;
4530 struct netdev_rx_queue *rxqueue;
4534 if (skb_rx_queue_recorded(skb)) {
4535 u16 index = skb_get_rx_queue(skb);
4537 if (unlikely(index >= dev->real_num_rx_queues)) {
4538 WARN_ONCE(dev->real_num_rx_queues > 1,
4539 "%s received packet on queue %u, but number "
4540 "of RX queues is %u\n",
4541 dev->name, index, dev->real_num_rx_queues);
4543 return rxqueue; /* Return first rxqueue */
4550 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4551 struct xdp_buff *xdp,
4552 struct bpf_prog *xdp_prog)
4554 struct netdev_rx_queue *rxqueue;
4555 void *orig_data, *orig_data_end;
4556 u32 metalen, act = XDP_DROP;
4557 __be16 orig_eth_type;
4563 /* Reinjected packets coming from act_mirred or similar should
4564 * not get XDP generic processing.
4566 if (skb_cloned(skb) || skb_is_tc_redirected(skb))
4569 /* XDP packets must be linear and must have sufficient headroom
4570 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4571 * native XDP provides, thus we need to do it here as well.
4573 if (skb_is_nonlinear(skb) ||
4574 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4575 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4576 int troom = skb->tail + skb->data_len - skb->end;
4578 /* In case we have to go down the path and also linearize,
4579 * then lets do the pskb_expand_head() work just once here.
4581 if (pskb_expand_head(skb,
4582 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4583 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4585 if (skb_linearize(skb))
4589 /* The XDP program wants to see the packet starting at the MAC
4592 mac_len = skb->data - skb_mac_header(skb);
4593 hlen = skb_headlen(skb) + mac_len;
4594 xdp->data = skb->data - mac_len;
4595 xdp->data_meta = xdp->data;
4596 xdp->data_end = xdp->data + hlen;
4597 xdp->data_hard_start = skb->data - skb_headroom(skb);
4598 orig_data_end = xdp->data_end;
4599 orig_data = xdp->data;
4600 eth = (struct ethhdr *)xdp->data;
4601 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4602 orig_eth_type = eth->h_proto;
4604 rxqueue = netif_get_rxqueue(skb);
4605 xdp->rxq = &rxqueue->xdp_rxq;
4607 act = bpf_prog_run_xdp(xdp_prog, xdp);
4609 /* check if bpf_xdp_adjust_head was used */
4610 off = xdp->data - orig_data;
4613 __skb_pull(skb, off);
4615 __skb_push(skb, -off);
4617 skb->mac_header += off;
4618 skb_reset_network_header(skb);
4621 /* check if bpf_xdp_adjust_tail was used. it can only "shrink"
4624 off = orig_data_end - xdp->data_end;
4626 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4631 /* check if XDP changed eth hdr such SKB needs update */
4632 eth = (struct ethhdr *)xdp->data;
4633 if ((orig_eth_type != eth->h_proto) ||
4634 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4635 __skb_push(skb, ETH_HLEN);
4636 skb->protocol = eth_type_trans(skb, skb->dev);
4642 __skb_push(skb, mac_len);
4645 metalen = xdp->data - xdp->data_meta;
4647 skb_metadata_set(skb, metalen);
4650 bpf_warn_invalid_xdp_action(act);
4653 trace_xdp_exception(skb->dev, xdp_prog, act);
4664 /* When doing generic XDP we have to bypass the qdisc layer and the
4665 * network taps in order to match in-driver-XDP behavior.
4667 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4669 struct net_device *dev = skb->dev;
4670 struct netdev_queue *txq;
4671 bool free_skb = true;
4674 txq = netdev_core_pick_tx(dev, skb, NULL);
4675 cpu = smp_processor_id();
4676 HARD_TX_LOCK(dev, txq, cpu);
4677 if (!netif_xmit_stopped(txq)) {
4678 rc = netdev_start_xmit(skb, dev, txq, 0);
4679 if (dev_xmit_complete(rc))
4682 HARD_TX_UNLOCK(dev, txq);
4684 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4688 EXPORT_SYMBOL_GPL(generic_xdp_tx);
4690 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4692 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4695 struct xdp_buff xdp;
4699 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4700 if (act != XDP_PASS) {
4703 err = xdp_do_generic_redirect(skb->dev, skb,
4709 generic_xdp_tx(skb, xdp_prog);
4720 EXPORT_SYMBOL_GPL(do_xdp_generic);
4722 static int netif_rx_internal(struct sk_buff *skb)
4726 net_timestamp_check(netdev_tstamp_prequeue, skb);
4728 trace_netif_rx(skb);
4731 if (static_branch_unlikely(&rps_needed)) {
4732 struct rps_dev_flow voidflow, *rflow = &voidflow;
4738 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4740 cpu = smp_processor_id();
4742 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4751 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4758 * netif_rx - post buffer to the network code
4759 * @skb: buffer to post
4761 * This function receives a packet from a device driver and queues it for
4762 * the upper (protocol) levels to process. It always succeeds. The buffer
4763 * may be dropped during processing for congestion control or by the
4767 * NET_RX_SUCCESS (no congestion)
4768 * NET_RX_DROP (packet was dropped)
4772 int netif_rx(struct sk_buff *skb)
4776 trace_netif_rx_entry(skb);
4778 ret = netif_rx_internal(skb);
4779 trace_netif_rx_exit(ret);
4783 EXPORT_SYMBOL(netif_rx);
4785 int netif_rx_ni(struct sk_buff *skb)
4789 trace_netif_rx_ni_entry(skb);
4792 err = netif_rx_internal(skb);
4793 if (local_softirq_pending())
4796 trace_netif_rx_ni_exit(err);
4800 EXPORT_SYMBOL(netif_rx_ni);
4802 static __latent_entropy void net_tx_action(struct softirq_action *h)
4804 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4806 if (sd->completion_queue) {
4807 struct sk_buff *clist;
4809 local_irq_disable();
4810 clist = sd->completion_queue;
4811 sd->completion_queue = NULL;
4815 struct sk_buff *skb = clist;
4817 clist = clist->next;
4819 WARN_ON(refcount_read(&skb->users));
4820 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4821 trace_consume_skb(skb);
4823 trace_kfree_skb(skb, net_tx_action);
4825 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4828 __kfree_skb_defer(skb);
4831 __kfree_skb_flush();
4834 if (sd->output_queue) {
4837 local_irq_disable();
4838 head = sd->output_queue;
4839 sd->output_queue = NULL;
4840 sd->output_queue_tailp = &sd->output_queue;
4844 struct Qdisc *q = head;
4845 spinlock_t *root_lock = NULL;
4847 head = head->next_sched;
4849 if (!(q->flags & TCQ_F_NOLOCK)) {
4850 root_lock = qdisc_lock(q);
4851 spin_lock(root_lock);
4853 /* We need to make sure head->next_sched is read
4854 * before clearing __QDISC_STATE_SCHED
4856 smp_mb__before_atomic();
4857 clear_bit(__QDISC_STATE_SCHED, &q->state);
4860 spin_unlock(root_lock);
4864 xfrm_dev_backlog(sd);
4867 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4868 /* This hook is defined here for ATM LANE */
4869 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4870 unsigned char *addr) __read_mostly;
4871 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4874 static inline struct sk_buff *
4875 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4876 struct net_device *orig_dev)
4878 #ifdef CONFIG_NET_CLS_ACT
4879 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4880 struct tcf_result cl_res;
4882 /* If there's at least one ingress present somewhere (so
4883 * we get here via enabled static key), remaining devices
4884 * that are not configured with an ingress qdisc will bail
4891 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4895 qdisc_skb_cb(skb)->pkt_len = skb->len;
4896 skb->tc_at_ingress = 1;
4897 mini_qdisc_bstats_cpu_update(miniq, skb);
4899 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
4901 case TC_ACT_RECLASSIFY:
4902 skb->tc_index = TC_H_MIN(cl_res.classid);
4905 mini_qdisc_qstats_cpu_drop(miniq);
4913 case TC_ACT_REDIRECT:
4914 /* skb_mac_header check was done by cls/act_bpf, so
4915 * we can safely push the L2 header back before
4916 * redirecting to another netdev
4918 __skb_push(skb, skb->mac_len);
4919 skb_do_redirect(skb);
4921 case TC_ACT_CONSUMED:
4926 #endif /* CONFIG_NET_CLS_ACT */
4931 * netdev_is_rx_handler_busy - check if receive handler is registered
4932 * @dev: device to check
4934 * Check if a receive handler is already registered for a given device.
4935 * Return true if there one.
4937 * The caller must hold the rtnl_mutex.
4939 bool netdev_is_rx_handler_busy(struct net_device *dev)
4942 return dev && rtnl_dereference(dev->rx_handler);
4944 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
4947 * netdev_rx_handler_register - register receive handler
4948 * @dev: device to register a handler for
4949 * @rx_handler: receive handler to register
4950 * @rx_handler_data: data pointer that is used by rx handler
4952 * Register a receive handler for a device. This handler will then be
4953 * called from __netif_receive_skb. A negative errno code is returned
4956 * The caller must hold the rtnl_mutex.
4958 * For a general description of rx_handler, see enum rx_handler_result.
4960 int netdev_rx_handler_register(struct net_device *dev,
4961 rx_handler_func_t *rx_handler,
4962 void *rx_handler_data)
4964 if (netdev_is_rx_handler_busy(dev))
4967 if (dev->priv_flags & IFF_NO_RX_HANDLER)
4970 /* Note: rx_handler_data must be set before rx_handler */
4971 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
4972 rcu_assign_pointer(dev->rx_handler, rx_handler);
4976 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
4979 * netdev_rx_handler_unregister - unregister receive handler
4980 * @dev: device to unregister a handler from
4982 * Unregister a receive handler from a device.
4984 * The caller must hold the rtnl_mutex.
4986 void netdev_rx_handler_unregister(struct net_device *dev)
4990 RCU_INIT_POINTER(dev->rx_handler, NULL);
4991 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
4992 * section has a guarantee to see a non NULL rx_handler_data
4996 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
4998 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5001 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5002 * the special handling of PFMEMALLOC skbs.
5004 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5006 switch (skb->protocol) {
5007 case htons(ETH_P_ARP):
5008 case htons(ETH_P_IP):
5009 case htons(ETH_P_IPV6):
5010 case htons(ETH_P_8021Q):
5011 case htons(ETH_P_8021AD):
5018 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5019 int *ret, struct net_device *orig_dev)
5021 #ifdef CONFIG_NETFILTER_INGRESS
5022 if (nf_hook_ingress_active(skb)) {
5026 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5031 ingress_retval = nf_hook_ingress(skb);
5033 return ingress_retval;
5035 #endif /* CONFIG_NETFILTER_INGRESS */
5039 static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc,
5040 struct packet_type **ppt_prev)
5042 struct packet_type *ptype, *pt_prev;
5043 rx_handler_func_t *rx_handler;
5044 struct net_device *orig_dev;
5045 bool deliver_exact = false;
5046 int ret = NET_RX_DROP;
5049 net_timestamp_check(!netdev_tstamp_prequeue, skb);
5051 trace_netif_receive_skb(skb);
5053 orig_dev = skb->dev;
5055 skb_reset_network_header(skb);
5056 if (!skb_transport_header_was_set(skb))
5057 skb_reset_transport_header(skb);
5058 skb_reset_mac_len(skb);
5063 skb->skb_iif = skb->dev->ifindex;
5065 __this_cpu_inc(softnet_data.processed);
5067 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5071 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5074 if (ret2 != XDP_PASS)
5076 skb_reset_mac_len(skb);
5079 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5080 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5081 skb = skb_vlan_untag(skb);
5086 if (skb_skip_tc_classify(skb))
5092 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5094 ret = deliver_skb(skb, pt_prev, orig_dev);
5098 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5100 ret = deliver_skb(skb, pt_prev, orig_dev);
5105 #ifdef CONFIG_NET_INGRESS
5106 if (static_branch_unlikely(&ingress_needed_key)) {
5107 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
5111 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5117 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5120 if (skb_vlan_tag_present(skb)) {
5122 ret = deliver_skb(skb, pt_prev, orig_dev);
5125 if (vlan_do_receive(&skb))
5127 else if (unlikely(!skb))
5131 rx_handler = rcu_dereference(skb->dev->rx_handler);
5134 ret = deliver_skb(skb, pt_prev, orig_dev);
5137 switch (rx_handler(&skb)) {
5138 case RX_HANDLER_CONSUMED:
5139 ret = NET_RX_SUCCESS;
5141 case RX_HANDLER_ANOTHER:
5143 case RX_HANDLER_EXACT:
5144 deliver_exact = true;
5145 case RX_HANDLER_PASS:
5152 if (unlikely(skb_vlan_tag_present(skb))) {
5154 if (skb_vlan_tag_get_id(skb)) {
5155 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5158 skb->pkt_type = PACKET_OTHERHOST;
5159 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5160 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5161 /* Outer header is 802.1P with vlan 0, inner header is
5162 * 802.1Q or 802.1AD and vlan_do_receive() above could
5163 * not find vlan dev for vlan id 0.
5165 __vlan_hwaccel_clear_tag(skb);
5166 skb = skb_vlan_untag(skb);
5169 if (vlan_do_receive(&skb))
5170 /* After stripping off 802.1P header with vlan 0
5171 * vlan dev is found for inner header.
5174 else if (unlikely(!skb))
5177 /* We have stripped outer 802.1P vlan 0 header.
5178 * But could not find vlan dev.
5179 * check again for vlan id to set OTHERHOST.
5183 /* Note: we might in the future use prio bits
5184 * and set skb->priority like in vlan_do_receive()
5185 * For the time being, just ignore Priority Code Point
5187 __vlan_hwaccel_clear_tag(skb);
5190 type = skb->protocol;
5192 /* deliver only exact match when indicated */
5193 if (likely(!deliver_exact)) {
5194 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5195 &ptype_base[ntohs(type) &
5199 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5200 &orig_dev->ptype_specific);
5202 if (unlikely(skb->dev != orig_dev)) {
5203 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5204 &skb->dev->ptype_specific);
5208 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5210 *ppt_prev = pt_prev;
5214 atomic_long_inc(&skb->dev->rx_dropped);
5216 atomic_long_inc(&skb->dev->rx_nohandler);
5218 /* Jamal, now you will not able to escape explaining
5219 * me how you were going to use this. :-)
5228 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5230 struct net_device *orig_dev = skb->dev;
5231 struct packet_type *pt_prev = NULL;
5234 ret = __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
5236 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5237 skb->dev, pt_prev, orig_dev);
5242 * netif_receive_skb_core - special purpose version of netif_receive_skb
5243 * @skb: buffer to process
5245 * More direct receive version of netif_receive_skb(). It should
5246 * only be used by callers that have a need to skip RPS and Generic XDP.
5247 * Caller must also take care of handling if (page_is_)pfmemalloc.
5249 * This function may only be called from softirq context and interrupts
5250 * should be enabled.
5252 * Return values (usually ignored):
5253 * NET_RX_SUCCESS: no congestion
5254 * NET_RX_DROP: packet was dropped
5256 int netif_receive_skb_core(struct sk_buff *skb)
5261 ret = __netif_receive_skb_one_core(skb, false);
5266 EXPORT_SYMBOL(netif_receive_skb_core);
5268 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5269 struct packet_type *pt_prev,
5270 struct net_device *orig_dev)
5272 struct sk_buff *skb, *next;
5276 if (list_empty(head))
5278 if (pt_prev->list_func != NULL)
5279 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5280 ip_list_rcv, head, pt_prev, orig_dev);
5282 list_for_each_entry_safe(skb, next, head, list) {
5283 skb_list_del_init(skb);
5284 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5288 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5290 /* Fast-path assumptions:
5291 * - There is no RX handler.
5292 * - Only one packet_type matches.
5293 * If either of these fails, we will end up doing some per-packet
5294 * processing in-line, then handling the 'last ptype' for the whole
5295 * sublist. This can't cause out-of-order delivery to any single ptype,
5296 * because the 'last ptype' must be constant across the sublist, and all
5297 * other ptypes are handled per-packet.
5299 /* Current (common) ptype of sublist */
5300 struct packet_type *pt_curr = NULL;
5301 /* Current (common) orig_dev of sublist */
5302 struct net_device *od_curr = NULL;
5303 struct list_head sublist;
5304 struct sk_buff *skb, *next;
5306 INIT_LIST_HEAD(&sublist);
5307 list_for_each_entry_safe(skb, next, head, list) {
5308 struct net_device *orig_dev = skb->dev;
5309 struct packet_type *pt_prev = NULL;
5311 skb_list_del_init(skb);
5312 __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
5315 if (pt_curr != pt_prev || od_curr != orig_dev) {
5316 /* dispatch old sublist */
5317 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5318 /* start new sublist */
5319 INIT_LIST_HEAD(&sublist);
5323 list_add_tail(&skb->list, &sublist);
5326 /* dispatch final sublist */
5327 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5330 static int __netif_receive_skb(struct sk_buff *skb)
5334 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5335 unsigned int noreclaim_flag;
5338 * PFMEMALLOC skbs are special, they should
5339 * - be delivered to SOCK_MEMALLOC sockets only
5340 * - stay away from userspace
5341 * - have bounded memory usage
5343 * Use PF_MEMALLOC as this saves us from propagating the allocation
5344 * context down to all allocation sites.
5346 noreclaim_flag = memalloc_noreclaim_save();
5347 ret = __netif_receive_skb_one_core(skb, true);
5348 memalloc_noreclaim_restore(noreclaim_flag);
5350 ret = __netif_receive_skb_one_core(skb, false);
5355 static void __netif_receive_skb_list(struct list_head *head)
5357 unsigned long noreclaim_flag = 0;
5358 struct sk_buff *skb, *next;
5359 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5361 list_for_each_entry_safe(skb, next, head, list) {
5362 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5363 struct list_head sublist;
5365 /* Handle the previous sublist */
5366 list_cut_before(&sublist, head, &skb->list);
5367 if (!list_empty(&sublist))
5368 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5369 pfmemalloc = !pfmemalloc;
5370 /* See comments in __netif_receive_skb */
5372 noreclaim_flag = memalloc_noreclaim_save();
5374 memalloc_noreclaim_restore(noreclaim_flag);
5377 /* Handle the remaining sublist */
5378 if (!list_empty(head))
5379 __netif_receive_skb_list_core(head, pfmemalloc);
5380 /* Restore pflags */
5382 memalloc_noreclaim_restore(noreclaim_flag);
5385 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5387 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5388 struct bpf_prog *new = xdp->prog;
5391 switch (xdp->command) {
5392 case XDP_SETUP_PROG:
5393 rcu_assign_pointer(dev->xdp_prog, new);
5398 static_branch_dec(&generic_xdp_needed_key);
5399 } else if (new && !old) {
5400 static_branch_inc(&generic_xdp_needed_key);
5401 dev_disable_lro(dev);
5402 dev_disable_gro_hw(dev);
5406 case XDP_QUERY_PROG:
5407 xdp->prog_id = old ? old->aux->id : 0;
5418 static int netif_receive_skb_internal(struct sk_buff *skb)
5422 net_timestamp_check(netdev_tstamp_prequeue, skb);
5424 if (skb_defer_rx_timestamp(skb))
5425 return NET_RX_SUCCESS;
5429 if (static_branch_unlikely(&rps_needed)) {
5430 struct rps_dev_flow voidflow, *rflow = &voidflow;
5431 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5434 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5440 ret = __netif_receive_skb(skb);
5445 static void netif_receive_skb_list_internal(struct list_head *head)
5447 struct sk_buff *skb, *next;
5448 struct list_head sublist;
5450 INIT_LIST_HEAD(&sublist);
5451 list_for_each_entry_safe(skb, next, head, list) {
5452 net_timestamp_check(netdev_tstamp_prequeue, skb);
5453 skb_list_del_init(skb);
5454 if (!skb_defer_rx_timestamp(skb))
5455 list_add_tail(&skb->list, &sublist);
5457 list_splice_init(&sublist, head);
5461 if (static_branch_unlikely(&rps_needed)) {
5462 list_for_each_entry_safe(skb, next, head, list) {
5463 struct rps_dev_flow voidflow, *rflow = &voidflow;
5464 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5467 /* Will be handled, remove from list */
5468 skb_list_del_init(skb);
5469 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5474 __netif_receive_skb_list(head);
5479 * netif_receive_skb - process receive buffer from network
5480 * @skb: buffer to process
5482 * netif_receive_skb() is the main receive data processing function.
5483 * It always succeeds. The buffer may be dropped during processing
5484 * for congestion control or by the protocol layers.
5486 * This function may only be called from softirq context and interrupts
5487 * should be enabled.
5489 * Return values (usually ignored):
5490 * NET_RX_SUCCESS: no congestion
5491 * NET_RX_DROP: packet was dropped
5493 int netif_receive_skb(struct sk_buff *skb)
5497 trace_netif_receive_skb_entry(skb);
5499 ret = netif_receive_skb_internal(skb);
5500 trace_netif_receive_skb_exit(ret);
5504 EXPORT_SYMBOL(netif_receive_skb);
5507 * netif_receive_skb_list - process many receive buffers from network
5508 * @head: list of skbs to process.
5510 * Since return value of netif_receive_skb() is normally ignored, and
5511 * wouldn't be meaningful for a list, this function returns void.
5513 * This function may only be called from softirq context and interrupts
5514 * should be enabled.
5516 void netif_receive_skb_list(struct list_head *head)
5518 struct sk_buff *skb;
5520 if (list_empty(head))
5522 if (trace_netif_receive_skb_list_entry_enabled()) {
5523 list_for_each_entry(skb, head, list)
5524 trace_netif_receive_skb_list_entry(skb);
5526 netif_receive_skb_list_internal(head);
5527 trace_netif_receive_skb_list_exit(0);
5529 EXPORT_SYMBOL(netif_receive_skb_list);
5531 DEFINE_PER_CPU(struct work_struct, flush_works);
5533 /* Network device is going away, flush any packets still pending */
5534 static void flush_backlog(struct work_struct *work)
5536 struct sk_buff *skb, *tmp;
5537 struct softnet_data *sd;
5540 sd = this_cpu_ptr(&softnet_data);
5542 local_irq_disable();
5544 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5545 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5546 __skb_unlink(skb, &sd->input_pkt_queue);
5548 input_queue_head_incr(sd);
5554 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5555 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5556 __skb_unlink(skb, &sd->process_queue);
5558 input_queue_head_incr(sd);
5564 static void flush_all_backlogs(void)
5570 for_each_online_cpu(cpu)
5571 queue_work_on(cpu, system_highpri_wq,
5572 per_cpu_ptr(&flush_works, cpu));
5574 for_each_online_cpu(cpu)
5575 flush_work(per_cpu_ptr(&flush_works, cpu));
5580 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5581 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5582 static int napi_gro_complete(struct sk_buff *skb)
5584 struct packet_offload *ptype;
5585 __be16 type = skb->protocol;
5586 struct list_head *head = &offload_base;
5589 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5591 if (NAPI_GRO_CB(skb)->count == 1) {
5592 skb_shinfo(skb)->gso_size = 0;
5597 list_for_each_entry_rcu(ptype, head, list) {
5598 if (ptype->type != type || !ptype->callbacks.gro_complete)
5601 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5602 ipv6_gro_complete, inet_gro_complete,
5609 WARN_ON(&ptype->list == head);
5611 return NET_RX_SUCCESS;
5615 return netif_receive_skb_internal(skb);
5618 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5621 struct list_head *head = &napi->gro_hash[index].list;
5622 struct sk_buff *skb, *p;
5624 list_for_each_entry_safe_reverse(skb, p, head, list) {
5625 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5627 skb_list_del_init(skb);
5628 napi_gro_complete(skb);
5629 napi->gro_hash[index].count--;
5632 if (!napi->gro_hash[index].count)
5633 __clear_bit(index, &napi->gro_bitmask);
5636 /* napi->gro_hash[].list contains packets ordered by age.
5637 * youngest packets at the head of it.
5638 * Complete skbs in reverse order to reduce latencies.
5640 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5642 unsigned long bitmask = napi->gro_bitmask;
5643 unsigned int i, base = ~0U;
5645 while ((i = ffs(bitmask)) != 0) {
5648 __napi_gro_flush_chain(napi, base, flush_old);
5651 EXPORT_SYMBOL(napi_gro_flush);
5653 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5654 struct sk_buff *skb)
5656 unsigned int maclen = skb->dev->hard_header_len;
5657 u32 hash = skb_get_hash_raw(skb);
5658 struct list_head *head;
5661 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5662 list_for_each_entry(p, head, list) {
5663 unsigned long diffs;
5665 NAPI_GRO_CB(p)->flush = 0;
5667 if (hash != skb_get_hash_raw(p)) {
5668 NAPI_GRO_CB(p)->same_flow = 0;
5672 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5673 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5674 if (skb_vlan_tag_present(p))
5675 diffs |= p->vlan_tci ^ skb->vlan_tci;
5676 diffs |= skb_metadata_dst_cmp(p, skb);
5677 diffs |= skb_metadata_differs(p, skb);
5678 if (maclen == ETH_HLEN)
5679 diffs |= compare_ether_header(skb_mac_header(p),
5680 skb_mac_header(skb));
5682 diffs = memcmp(skb_mac_header(p),
5683 skb_mac_header(skb),
5685 NAPI_GRO_CB(p)->same_flow = !diffs;
5691 static void skb_gro_reset_offset(struct sk_buff *skb)
5693 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5694 const skb_frag_t *frag0 = &pinfo->frags[0];
5696 NAPI_GRO_CB(skb)->data_offset = 0;
5697 NAPI_GRO_CB(skb)->frag0 = NULL;
5698 NAPI_GRO_CB(skb)->frag0_len = 0;
5700 if (skb_mac_header(skb) == skb_tail_pointer(skb) &&
5702 !PageHighMem(skb_frag_page(frag0))) {
5703 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5704 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5705 skb_frag_size(frag0),
5706 skb->end - skb->tail);
5710 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5712 struct skb_shared_info *pinfo = skb_shinfo(skb);
5714 BUG_ON(skb->end - skb->tail < grow);
5716 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5718 skb->data_len -= grow;
5721 skb_frag_off_add(&pinfo->frags[0], grow);
5722 skb_frag_size_sub(&pinfo->frags[0], grow);
5724 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5725 skb_frag_unref(skb, 0);
5726 memmove(pinfo->frags, pinfo->frags + 1,
5727 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5731 static void gro_flush_oldest(struct list_head *head)
5733 struct sk_buff *oldest;
5735 oldest = list_last_entry(head, struct sk_buff, list);
5737 /* We are called with head length >= MAX_GRO_SKBS, so this is
5740 if (WARN_ON_ONCE(!oldest))
5743 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5746 skb_list_del_init(oldest);
5747 napi_gro_complete(oldest);
5750 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5752 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5754 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5756 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5757 struct list_head *head = &offload_base;
5758 struct packet_offload *ptype;
5759 __be16 type = skb->protocol;
5760 struct list_head *gro_head;
5761 struct sk_buff *pp = NULL;
5762 enum gro_result ret;
5766 if (netif_elide_gro(skb->dev))
5769 gro_head = gro_list_prepare(napi, skb);
5772 list_for_each_entry_rcu(ptype, head, list) {
5773 if (ptype->type != type || !ptype->callbacks.gro_receive)
5776 skb_set_network_header(skb, skb_gro_offset(skb));
5777 skb_reset_mac_len(skb);
5778 NAPI_GRO_CB(skb)->same_flow = 0;
5779 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5780 NAPI_GRO_CB(skb)->free = 0;
5781 NAPI_GRO_CB(skb)->encap_mark = 0;
5782 NAPI_GRO_CB(skb)->recursion_counter = 0;
5783 NAPI_GRO_CB(skb)->is_fou = 0;
5784 NAPI_GRO_CB(skb)->is_atomic = 1;
5785 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
5787 /* Setup for GRO checksum validation */
5788 switch (skb->ip_summed) {
5789 case CHECKSUM_COMPLETE:
5790 NAPI_GRO_CB(skb)->csum = skb->csum;
5791 NAPI_GRO_CB(skb)->csum_valid = 1;
5792 NAPI_GRO_CB(skb)->csum_cnt = 0;
5794 case CHECKSUM_UNNECESSARY:
5795 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
5796 NAPI_GRO_CB(skb)->csum_valid = 0;
5799 NAPI_GRO_CB(skb)->csum_cnt = 0;
5800 NAPI_GRO_CB(skb)->csum_valid = 0;
5803 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
5804 ipv6_gro_receive, inet_gro_receive,
5810 if (&ptype->list == head)
5813 if (IS_ERR(pp) && PTR_ERR(pp) == -EINPROGRESS) {
5818 same_flow = NAPI_GRO_CB(skb)->same_flow;
5819 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
5822 skb_list_del_init(pp);
5823 napi_gro_complete(pp);
5824 napi->gro_hash[hash].count--;
5830 if (NAPI_GRO_CB(skb)->flush)
5833 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
5834 gro_flush_oldest(gro_head);
5836 napi->gro_hash[hash].count++;
5838 NAPI_GRO_CB(skb)->count = 1;
5839 NAPI_GRO_CB(skb)->age = jiffies;
5840 NAPI_GRO_CB(skb)->last = skb;
5841 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
5842 list_add(&skb->list, gro_head);
5846 grow = skb_gro_offset(skb) - skb_headlen(skb);
5848 gro_pull_from_frag0(skb, grow);
5850 if (napi->gro_hash[hash].count) {
5851 if (!test_bit(hash, &napi->gro_bitmask))
5852 __set_bit(hash, &napi->gro_bitmask);
5853 } else if (test_bit(hash, &napi->gro_bitmask)) {
5854 __clear_bit(hash, &napi->gro_bitmask);
5864 struct packet_offload *gro_find_receive_by_type(__be16 type)
5866 struct list_head *offload_head = &offload_base;
5867 struct packet_offload *ptype;
5869 list_for_each_entry_rcu(ptype, offload_head, list) {
5870 if (ptype->type != type || !ptype->callbacks.gro_receive)
5876 EXPORT_SYMBOL(gro_find_receive_by_type);
5878 struct packet_offload *gro_find_complete_by_type(__be16 type)
5880 struct list_head *offload_head = &offload_base;
5881 struct packet_offload *ptype;
5883 list_for_each_entry_rcu(ptype, offload_head, list) {
5884 if (ptype->type != type || !ptype->callbacks.gro_complete)
5890 EXPORT_SYMBOL(gro_find_complete_by_type);
5892 static void napi_skb_free_stolen_head(struct sk_buff *skb)
5896 kmem_cache_free(skbuff_head_cache, skb);
5899 static gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
5903 if (netif_receive_skb_internal(skb))
5911 case GRO_MERGED_FREE:
5912 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
5913 napi_skb_free_stolen_head(skb);
5927 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5931 skb_mark_napi_id(skb, napi);
5932 trace_napi_gro_receive_entry(skb);
5934 skb_gro_reset_offset(skb);
5936 ret = napi_skb_finish(dev_gro_receive(napi, skb), skb);
5937 trace_napi_gro_receive_exit(ret);
5941 EXPORT_SYMBOL(napi_gro_receive);
5943 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
5945 if (unlikely(skb->pfmemalloc)) {
5949 __skb_pull(skb, skb_headlen(skb));
5950 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
5951 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
5952 __vlan_hwaccel_clear_tag(skb);
5953 skb->dev = napi->dev;
5956 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
5957 skb->pkt_type = PACKET_HOST;
5959 skb->encapsulation = 0;
5960 skb_shinfo(skb)->gso_type = 0;
5961 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
5967 struct sk_buff *napi_get_frags(struct napi_struct *napi)
5969 struct sk_buff *skb = napi->skb;
5972 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
5975 skb_mark_napi_id(skb, napi);
5980 EXPORT_SYMBOL(napi_get_frags);
5982 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
5983 static void gro_normal_list(struct napi_struct *napi)
5985 if (!napi->rx_count)
5987 netif_receive_skb_list_internal(&napi->rx_list);
5988 INIT_LIST_HEAD(&napi->rx_list);
5992 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5993 * pass the whole batch up to the stack.
5995 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb)
5997 list_add_tail(&skb->list, &napi->rx_list);
5998 if (++napi->rx_count >= gro_normal_batch)
5999 gro_normal_list(napi);
6002 static gro_result_t napi_frags_finish(struct napi_struct *napi,
6003 struct sk_buff *skb,
6009 __skb_push(skb, ETH_HLEN);
6010 skb->protocol = eth_type_trans(skb, skb->dev);
6011 if (ret == GRO_NORMAL)
6012 gro_normal_one(napi, skb);
6016 napi_reuse_skb(napi, skb);
6019 case GRO_MERGED_FREE:
6020 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6021 napi_skb_free_stolen_head(skb);
6023 napi_reuse_skb(napi, skb);
6034 /* Upper GRO stack assumes network header starts at gro_offset=0
6035 * Drivers could call both napi_gro_frags() and napi_gro_receive()
6036 * We copy ethernet header into skb->data to have a common layout.
6038 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
6040 struct sk_buff *skb = napi->skb;
6041 const struct ethhdr *eth;
6042 unsigned int hlen = sizeof(*eth);
6046 skb_reset_mac_header(skb);
6047 skb_gro_reset_offset(skb);
6049 if (unlikely(skb_gro_header_hard(skb, hlen))) {
6050 eth = skb_gro_header_slow(skb, hlen, 0);
6051 if (unlikely(!eth)) {
6052 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
6053 __func__, napi->dev->name);
6054 napi_reuse_skb(napi, skb);
6058 eth = (const struct ethhdr *)skb->data;
6059 gro_pull_from_frag0(skb, hlen);
6060 NAPI_GRO_CB(skb)->frag0 += hlen;
6061 NAPI_GRO_CB(skb)->frag0_len -= hlen;
6063 __skb_pull(skb, hlen);
6066 * This works because the only protocols we care about don't require
6068 * We'll fix it up properly in napi_frags_finish()
6070 skb->protocol = eth->h_proto;
6075 gro_result_t napi_gro_frags(struct napi_struct *napi)
6078 struct sk_buff *skb = napi_frags_skb(napi);
6083 trace_napi_gro_frags_entry(skb);
6085 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6086 trace_napi_gro_frags_exit(ret);
6090 EXPORT_SYMBOL(napi_gro_frags);
6092 /* Compute the checksum from gro_offset and return the folded value
6093 * after adding in any pseudo checksum.
6095 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6100 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6102 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6103 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6104 /* See comments in __skb_checksum_complete(). */
6106 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6107 !skb->csum_complete_sw)
6108 netdev_rx_csum_fault(skb->dev, skb);
6111 NAPI_GRO_CB(skb)->csum = wsum;
6112 NAPI_GRO_CB(skb)->csum_valid = 1;
6116 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6118 static void net_rps_send_ipi(struct softnet_data *remsd)
6122 struct softnet_data *next = remsd->rps_ipi_next;
6124 if (cpu_online(remsd->cpu))
6125 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6132 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6133 * Note: called with local irq disabled, but exits with local irq enabled.
6135 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6138 struct softnet_data *remsd = sd->rps_ipi_list;
6141 sd->rps_ipi_list = NULL;
6145 /* Send pending IPI's to kick RPS processing on remote cpus. */
6146 net_rps_send_ipi(remsd);
6152 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6155 return sd->rps_ipi_list != NULL;
6161 static int process_backlog(struct napi_struct *napi, int quota)
6163 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6167 /* Check if we have pending ipi, its better to send them now,
6168 * not waiting net_rx_action() end.
6170 if (sd_has_rps_ipi_waiting(sd)) {
6171 local_irq_disable();
6172 net_rps_action_and_irq_enable(sd);
6175 napi->weight = dev_rx_weight;
6177 struct sk_buff *skb;
6179 while ((skb = __skb_dequeue(&sd->process_queue))) {
6181 __netif_receive_skb(skb);
6183 input_queue_head_incr(sd);
6184 if (++work >= quota)
6189 local_irq_disable();
6191 if (skb_queue_empty(&sd->input_pkt_queue)) {
6193 * Inline a custom version of __napi_complete().
6194 * only current cpu owns and manipulates this napi,
6195 * and NAPI_STATE_SCHED is the only possible flag set
6197 * We can use a plain write instead of clear_bit(),
6198 * and we dont need an smp_mb() memory barrier.
6203 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6204 &sd->process_queue);
6214 * __napi_schedule - schedule for receive
6215 * @n: entry to schedule
6217 * The entry's receive function will be scheduled to run.
6218 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6220 void __napi_schedule(struct napi_struct *n)
6222 unsigned long flags;
6224 local_irq_save(flags);
6225 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6226 local_irq_restore(flags);
6228 EXPORT_SYMBOL(__napi_schedule);
6231 * napi_schedule_prep - check if napi can be scheduled
6234 * Test if NAPI routine is already running, and if not mark
6235 * it as running. This is used as a condition variable
6236 * insure only one NAPI poll instance runs. We also make
6237 * sure there is no pending NAPI disable.
6239 bool napi_schedule_prep(struct napi_struct *n)
6241 unsigned long val, new;
6244 val = READ_ONCE(n->state);
6245 if (unlikely(val & NAPIF_STATE_DISABLE))
6247 new = val | NAPIF_STATE_SCHED;
6249 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6250 * This was suggested by Alexander Duyck, as compiler
6251 * emits better code than :
6252 * if (val & NAPIF_STATE_SCHED)
6253 * new |= NAPIF_STATE_MISSED;
6255 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6257 } while (cmpxchg(&n->state, val, new) != val);
6259 return !(val & NAPIF_STATE_SCHED);
6261 EXPORT_SYMBOL(napi_schedule_prep);
6264 * __napi_schedule_irqoff - schedule for receive
6265 * @n: entry to schedule
6267 * Variant of __napi_schedule() assuming hard irqs are masked
6269 void __napi_schedule_irqoff(struct napi_struct *n)
6271 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6273 EXPORT_SYMBOL(__napi_schedule_irqoff);
6275 bool napi_complete_done(struct napi_struct *n, int work_done)
6277 unsigned long flags, val, new;
6280 * 1) Don't let napi dequeue from the cpu poll list
6281 * just in case its running on a different cpu.
6282 * 2) If we are busy polling, do nothing here, we have
6283 * the guarantee we will be called later.
6285 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6286 NAPIF_STATE_IN_BUSY_POLL)))
6291 if (n->gro_bitmask) {
6292 unsigned long timeout = 0;
6295 timeout = n->dev->gro_flush_timeout;
6297 /* When the NAPI instance uses a timeout and keeps postponing
6298 * it, we need to bound somehow the time packets are kept in
6301 napi_gro_flush(n, !!timeout);
6303 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6304 HRTIMER_MODE_REL_PINNED);
6306 if (unlikely(!list_empty(&n->poll_list))) {
6307 /* If n->poll_list is not empty, we need to mask irqs */
6308 local_irq_save(flags);
6309 list_del_init(&n->poll_list);
6310 local_irq_restore(flags);
6314 val = READ_ONCE(n->state);
6316 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6318 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6320 /* If STATE_MISSED was set, leave STATE_SCHED set,
6321 * because we will call napi->poll() one more time.
6322 * This C code was suggested by Alexander Duyck to help gcc.
6324 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6326 } while (cmpxchg(&n->state, val, new) != val);
6328 if (unlikely(val & NAPIF_STATE_MISSED)) {
6335 EXPORT_SYMBOL(napi_complete_done);
6337 /* must be called under rcu_read_lock(), as we dont take a reference */
6338 static struct napi_struct *napi_by_id(unsigned int napi_id)
6340 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6341 struct napi_struct *napi;
6343 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6344 if (napi->napi_id == napi_id)
6350 #if defined(CONFIG_NET_RX_BUSY_POLL)
6352 #define BUSY_POLL_BUDGET 8
6354 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6358 /* Busy polling means there is a high chance device driver hard irq
6359 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6360 * set in napi_schedule_prep().
6361 * Since we are about to call napi->poll() once more, we can safely
6362 * clear NAPI_STATE_MISSED.
6364 * Note: x86 could use a single "lock and ..." instruction
6365 * to perform these two clear_bit()
6367 clear_bit(NAPI_STATE_MISSED, &napi->state);
6368 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6372 /* All we really want here is to re-enable device interrupts.
6373 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6375 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6376 /* We can't gro_normal_list() here, because napi->poll() might have
6377 * rearmed the napi (napi_complete_done()) in which case it could
6378 * already be running on another CPU.
6380 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6381 netpoll_poll_unlock(have_poll_lock);
6382 if (rc == BUSY_POLL_BUDGET) {
6383 /* As the whole budget was spent, we still own the napi so can
6384 * safely handle the rx_list.
6386 gro_normal_list(napi);
6387 __napi_schedule(napi);
6392 void napi_busy_loop(unsigned int napi_id,
6393 bool (*loop_end)(void *, unsigned long),
6396 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6397 int (*napi_poll)(struct napi_struct *napi, int budget);
6398 void *have_poll_lock = NULL;
6399 struct napi_struct *napi;
6406 napi = napi_by_id(napi_id);
6416 unsigned long val = READ_ONCE(napi->state);
6418 /* If multiple threads are competing for this napi,
6419 * we avoid dirtying napi->state as much as we can.
6421 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6422 NAPIF_STATE_IN_BUSY_POLL))
6424 if (cmpxchg(&napi->state, val,
6425 val | NAPIF_STATE_IN_BUSY_POLL |
6426 NAPIF_STATE_SCHED) != val)
6428 have_poll_lock = netpoll_poll_lock(napi);
6429 napi_poll = napi->poll;
6431 work = napi_poll(napi, BUSY_POLL_BUDGET);
6432 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6433 gro_normal_list(napi);
6436 __NET_ADD_STATS(dev_net(napi->dev),
6437 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6440 if (!loop_end || loop_end(loop_end_arg, start_time))
6443 if (unlikely(need_resched())) {
6445 busy_poll_stop(napi, have_poll_lock);
6449 if (loop_end(loop_end_arg, start_time))
6456 busy_poll_stop(napi, have_poll_lock);
6461 EXPORT_SYMBOL(napi_busy_loop);
6463 #endif /* CONFIG_NET_RX_BUSY_POLL */
6465 static void napi_hash_add(struct napi_struct *napi)
6467 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
6468 test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
6471 spin_lock(&napi_hash_lock);
6473 /* 0..NR_CPUS range is reserved for sender_cpu use */
6475 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6476 napi_gen_id = MIN_NAPI_ID;
6477 } while (napi_by_id(napi_gen_id));
6478 napi->napi_id = napi_gen_id;
6480 hlist_add_head_rcu(&napi->napi_hash_node,
6481 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6483 spin_unlock(&napi_hash_lock);
6486 /* Warning : caller is responsible to make sure rcu grace period
6487 * is respected before freeing memory containing @napi
6489 bool napi_hash_del(struct napi_struct *napi)
6491 bool rcu_sync_needed = false;
6493 spin_lock(&napi_hash_lock);
6495 if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
6496 rcu_sync_needed = true;
6497 hlist_del_rcu(&napi->napi_hash_node);
6499 spin_unlock(&napi_hash_lock);
6500 return rcu_sync_needed;
6502 EXPORT_SYMBOL_GPL(napi_hash_del);
6504 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6506 struct napi_struct *napi;
6508 napi = container_of(timer, struct napi_struct, timer);
6510 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6511 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6513 if (napi->gro_bitmask && !napi_disable_pending(napi) &&
6514 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6515 __napi_schedule_irqoff(napi);
6517 return HRTIMER_NORESTART;
6520 static void init_gro_hash(struct napi_struct *napi)
6524 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6525 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6526 napi->gro_hash[i].count = 0;
6528 napi->gro_bitmask = 0;
6531 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6532 int (*poll)(struct napi_struct *, int), int weight)
6534 INIT_LIST_HEAD(&napi->poll_list);
6535 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6536 napi->timer.function = napi_watchdog;
6537 init_gro_hash(napi);
6539 INIT_LIST_HEAD(&napi->rx_list);
6542 if (weight > NAPI_POLL_WEIGHT)
6543 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6545 napi->weight = weight;
6546 list_add(&napi->dev_list, &dev->napi_list);
6548 #ifdef CONFIG_NETPOLL
6549 napi->poll_owner = -1;
6551 set_bit(NAPI_STATE_SCHED, &napi->state);
6552 napi_hash_add(napi);
6554 EXPORT_SYMBOL(netif_napi_add);
6556 void napi_disable(struct napi_struct *n)
6559 set_bit(NAPI_STATE_DISABLE, &n->state);
6561 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6563 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6566 hrtimer_cancel(&n->timer);
6568 clear_bit(NAPI_STATE_DISABLE, &n->state);
6570 EXPORT_SYMBOL(napi_disable);
6572 static void flush_gro_hash(struct napi_struct *napi)
6576 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6577 struct sk_buff *skb, *n;
6579 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6581 napi->gro_hash[i].count = 0;
6585 /* Must be called in process context */
6586 void netif_napi_del(struct napi_struct *napi)
6589 if (napi_hash_del(napi))
6591 list_del_init(&napi->dev_list);
6592 napi_free_frags(napi);
6594 flush_gro_hash(napi);
6595 napi->gro_bitmask = 0;
6597 EXPORT_SYMBOL(netif_napi_del);
6599 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6604 list_del_init(&n->poll_list);
6606 have = netpoll_poll_lock(n);
6610 /* This NAPI_STATE_SCHED test is for avoiding a race
6611 * with netpoll's poll_napi(). Only the entity which
6612 * obtains the lock and sees NAPI_STATE_SCHED set will
6613 * actually make the ->poll() call. Therefore we avoid
6614 * accidentally calling ->poll() when NAPI is not scheduled.
6617 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6618 work = n->poll(n, weight);
6619 trace_napi_poll(n, work, weight);
6622 WARN_ON_ONCE(work > weight);
6624 if (likely(work < weight))
6627 /* Drivers must not modify the NAPI state if they
6628 * consume the entire weight. In such cases this code
6629 * still "owns" the NAPI instance and therefore can
6630 * move the instance around on the list at-will.
6632 if (unlikely(napi_disable_pending(n))) {
6639 if (n->gro_bitmask) {
6640 /* flush too old packets
6641 * If HZ < 1000, flush all packets.
6643 napi_gro_flush(n, HZ >= 1000);
6646 /* Some drivers may have called napi_schedule
6647 * prior to exhausting their budget.
6649 if (unlikely(!list_empty(&n->poll_list))) {
6650 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6651 n->dev ? n->dev->name : "backlog");
6655 list_add_tail(&n->poll_list, repoll);
6658 netpoll_poll_unlock(have);
6663 static __latent_entropy void net_rx_action(struct softirq_action *h)
6665 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6666 unsigned long time_limit = jiffies +
6667 usecs_to_jiffies(netdev_budget_usecs);
6668 int budget = netdev_budget;
6672 local_irq_disable();
6673 list_splice_init(&sd->poll_list, &list);
6677 struct napi_struct *n;
6679 if (list_empty(&list)) {
6680 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6685 n = list_first_entry(&list, struct napi_struct, poll_list);
6686 budget -= napi_poll(n, &repoll);
6688 /* If softirq window is exhausted then punt.
6689 * Allow this to run for 2 jiffies since which will allow
6690 * an average latency of 1.5/HZ.
6692 if (unlikely(budget <= 0 ||
6693 time_after_eq(jiffies, time_limit))) {
6699 local_irq_disable();
6701 list_splice_tail_init(&sd->poll_list, &list);
6702 list_splice_tail(&repoll, &list);
6703 list_splice(&list, &sd->poll_list);
6704 if (!list_empty(&sd->poll_list))
6705 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6707 net_rps_action_and_irq_enable(sd);
6709 __kfree_skb_flush();
6712 struct netdev_adjacent {
6713 struct net_device *dev;
6715 /* upper master flag, there can only be one master device per list */
6718 /* counter for the number of times this device was added to us */
6721 /* private field for the users */
6724 struct list_head list;
6725 struct rcu_head rcu;
6728 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6729 struct list_head *adj_list)
6731 struct netdev_adjacent *adj;
6733 list_for_each_entry(adj, adj_list, list) {
6734 if (adj->dev == adj_dev)
6740 static int __netdev_has_upper_dev(struct net_device *upper_dev, void *data)
6742 struct net_device *dev = data;
6744 return upper_dev == dev;
6748 * netdev_has_upper_dev - Check if device is linked to an upper device
6750 * @upper_dev: upper device to check
6752 * Find out if a device is linked to specified upper device and return true
6753 * in case it is. Note that this checks only immediate upper device,
6754 * not through a complete stack of devices. The caller must hold the RTNL lock.
6756 bool netdev_has_upper_dev(struct net_device *dev,
6757 struct net_device *upper_dev)
6761 return netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
6764 EXPORT_SYMBOL(netdev_has_upper_dev);
6767 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6769 * @upper_dev: upper device to check
6771 * Find out if a device is linked to specified upper device and return true
6772 * in case it is. Note that this checks the entire upper device chain.
6773 * The caller must hold rcu lock.
6776 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6777 struct net_device *upper_dev)
6779 return !!netdev_walk_all_upper_dev_rcu(dev, __netdev_has_upper_dev,
6782 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6785 * netdev_has_any_upper_dev - Check if device is linked to some device
6788 * Find out if a device is linked to an upper device and return true in case
6789 * it is. The caller must hold the RTNL lock.
6791 bool netdev_has_any_upper_dev(struct net_device *dev)
6795 return !list_empty(&dev->adj_list.upper);
6797 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6800 * netdev_master_upper_dev_get - Get master upper device
6803 * Find a master upper device and return pointer to it or NULL in case
6804 * it's not there. The caller must hold the RTNL lock.
6806 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6808 struct netdev_adjacent *upper;
6812 if (list_empty(&dev->adj_list.upper))
6815 upper = list_first_entry(&dev->adj_list.upper,
6816 struct netdev_adjacent, list);
6817 if (likely(upper->master))
6821 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6824 * netdev_has_any_lower_dev - Check if device is linked to some device
6827 * Find out if a device is linked to a lower device and return true in case
6828 * it is. The caller must hold the RTNL lock.
6830 static bool netdev_has_any_lower_dev(struct net_device *dev)
6834 return !list_empty(&dev->adj_list.lower);
6837 void *netdev_adjacent_get_private(struct list_head *adj_list)
6839 struct netdev_adjacent *adj;
6841 adj = list_entry(adj_list, struct netdev_adjacent, list);
6843 return adj->private;
6845 EXPORT_SYMBOL(netdev_adjacent_get_private);
6848 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6850 * @iter: list_head ** of the current position
6852 * Gets the next device from the dev's upper list, starting from iter
6853 * position. The caller must hold RCU read lock.
6855 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6856 struct list_head **iter)
6858 struct netdev_adjacent *upper;
6860 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6862 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6864 if (&upper->list == &dev->adj_list.upper)
6867 *iter = &upper->list;
6871 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6873 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6874 struct list_head **iter)
6876 struct netdev_adjacent *upper;
6878 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6880 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6882 if (&upper->list == &dev->adj_list.upper)
6885 *iter = &upper->list;
6890 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
6891 int (*fn)(struct net_device *dev,
6895 struct net_device *udev;
6896 struct list_head *iter;
6899 for (iter = &dev->adj_list.upper,
6900 udev = netdev_next_upper_dev_rcu(dev, &iter);
6902 udev = netdev_next_upper_dev_rcu(dev, &iter)) {
6903 /* first is the upper device itself */
6904 ret = fn(udev, data);
6908 /* then look at all of its upper devices */
6909 ret = netdev_walk_all_upper_dev_rcu(udev, fn, data);
6916 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
6919 * netdev_lower_get_next_private - Get the next ->private from the
6920 * lower neighbour list
6922 * @iter: list_head ** of the current position
6924 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6925 * list, starting from iter position. The caller must hold either hold the
6926 * RTNL lock or its own locking that guarantees that the neighbour lower
6927 * list will remain unchanged.
6929 void *netdev_lower_get_next_private(struct net_device *dev,
6930 struct list_head **iter)
6932 struct netdev_adjacent *lower;
6934 lower = list_entry(*iter, struct netdev_adjacent, list);
6936 if (&lower->list == &dev->adj_list.lower)
6939 *iter = lower->list.next;
6941 return lower->private;
6943 EXPORT_SYMBOL(netdev_lower_get_next_private);
6946 * netdev_lower_get_next_private_rcu - Get the next ->private from the
6947 * lower neighbour list, RCU
6950 * @iter: list_head ** of the current position
6952 * Gets the next netdev_adjacent->private from the dev's lower neighbour
6953 * list, starting from iter position. The caller must hold RCU read lock.
6955 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
6956 struct list_head **iter)
6958 struct netdev_adjacent *lower;
6960 WARN_ON_ONCE(!rcu_read_lock_held());
6962 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6964 if (&lower->list == &dev->adj_list.lower)
6967 *iter = &lower->list;
6969 return lower->private;
6971 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
6974 * netdev_lower_get_next - Get the next device from the lower neighbour
6977 * @iter: list_head ** of the current position
6979 * Gets the next netdev_adjacent from the dev's lower neighbour
6980 * list, starting from iter position. The caller must hold RTNL lock or
6981 * its own locking that guarantees that the neighbour lower
6982 * list will remain unchanged.
6984 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
6986 struct netdev_adjacent *lower;
6988 lower = list_entry(*iter, struct netdev_adjacent, list);
6990 if (&lower->list == &dev->adj_list.lower)
6993 *iter = lower->list.next;
6997 EXPORT_SYMBOL(netdev_lower_get_next);
6999 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7000 struct list_head **iter)
7002 struct netdev_adjacent *lower;
7004 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7006 if (&lower->list == &dev->adj_list.lower)
7009 *iter = &lower->list;
7014 int netdev_walk_all_lower_dev(struct net_device *dev,
7015 int (*fn)(struct net_device *dev,
7019 struct net_device *ldev;
7020 struct list_head *iter;
7023 for (iter = &dev->adj_list.lower,
7024 ldev = netdev_next_lower_dev(dev, &iter);
7026 ldev = netdev_next_lower_dev(dev, &iter)) {
7027 /* first is the lower device itself */
7028 ret = fn(ldev, data);
7032 /* then look at all of its lower devices */
7033 ret = netdev_walk_all_lower_dev(ldev, fn, data);
7040 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7042 static struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7043 struct list_head **iter)
7045 struct netdev_adjacent *lower;
7047 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7048 if (&lower->list == &dev->adj_list.lower)
7051 *iter = &lower->list;
7056 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7057 int (*fn)(struct net_device *dev,
7061 struct net_device *ldev;
7062 struct list_head *iter;
7065 for (iter = &dev->adj_list.lower,
7066 ldev = netdev_next_lower_dev_rcu(dev, &iter);
7068 ldev = netdev_next_lower_dev_rcu(dev, &iter)) {
7069 /* first is the lower device itself */
7070 ret = fn(ldev, data);
7074 /* then look at all of its lower devices */
7075 ret = netdev_walk_all_lower_dev_rcu(ldev, fn, data);
7082 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7085 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7086 * lower neighbour list, RCU
7090 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7091 * list. The caller must hold RCU read lock.
7093 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7095 struct netdev_adjacent *lower;
7097 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7098 struct netdev_adjacent, list);
7100 return lower->private;
7103 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7106 * netdev_master_upper_dev_get_rcu - Get master upper device
7109 * Find a master upper device and return pointer to it or NULL in case
7110 * it's not there. The caller must hold the RCU read lock.
7112 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7114 struct netdev_adjacent *upper;
7116 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7117 struct netdev_adjacent, list);
7118 if (upper && likely(upper->master))
7122 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7124 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7125 struct net_device *adj_dev,
7126 struct list_head *dev_list)
7128 char linkname[IFNAMSIZ+7];
7130 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7131 "upper_%s" : "lower_%s", adj_dev->name);
7132 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7135 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7137 struct list_head *dev_list)
7139 char linkname[IFNAMSIZ+7];
7141 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7142 "upper_%s" : "lower_%s", name);
7143 sysfs_remove_link(&(dev->dev.kobj), linkname);
7146 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7147 struct net_device *adj_dev,
7148 struct list_head *dev_list)
7150 return (dev_list == &dev->adj_list.upper ||
7151 dev_list == &dev->adj_list.lower) &&
7152 net_eq(dev_net(dev), dev_net(adj_dev));
7155 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7156 struct net_device *adj_dev,
7157 struct list_head *dev_list,
7158 void *private, bool master)
7160 struct netdev_adjacent *adj;
7163 adj = __netdev_find_adj(adj_dev, dev_list);
7167 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7168 dev->name, adj_dev->name, adj->ref_nr);
7173 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7178 adj->master = master;
7180 adj->private = private;
7183 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7184 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7186 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7187 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7192 /* Ensure that master link is always the first item in list. */
7194 ret = sysfs_create_link(&(dev->dev.kobj),
7195 &(adj_dev->dev.kobj), "master");
7197 goto remove_symlinks;
7199 list_add_rcu(&adj->list, dev_list);
7201 list_add_tail_rcu(&adj->list, dev_list);
7207 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7208 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7216 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7217 struct net_device *adj_dev,
7219 struct list_head *dev_list)
7221 struct netdev_adjacent *adj;
7223 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7224 dev->name, adj_dev->name, ref_nr);
7226 adj = __netdev_find_adj(adj_dev, dev_list);
7229 pr_err("Adjacency does not exist for device %s from %s\n",
7230 dev->name, adj_dev->name);
7235 if (adj->ref_nr > ref_nr) {
7236 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7237 dev->name, adj_dev->name, ref_nr,
7238 adj->ref_nr - ref_nr);
7239 adj->ref_nr -= ref_nr;
7244 sysfs_remove_link(&(dev->dev.kobj), "master");
7246 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7247 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7249 list_del_rcu(&adj->list);
7250 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7251 adj_dev->name, dev->name, adj_dev->name);
7253 kfree_rcu(adj, rcu);
7256 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7257 struct net_device *upper_dev,
7258 struct list_head *up_list,
7259 struct list_head *down_list,
7260 void *private, bool master)
7264 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7269 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7272 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7279 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7280 struct net_device *upper_dev,
7282 struct list_head *up_list,
7283 struct list_head *down_list)
7285 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7286 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7289 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7290 struct net_device *upper_dev,
7291 void *private, bool master)
7293 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7294 &dev->adj_list.upper,
7295 &upper_dev->adj_list.lower,
7299 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7300 struct net_device *upper_dev)
7302 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7303 &dev->adj_list.upper,
7304 &upper_dev->adj_list.lower);
7307 static int __netdev_upper_dev_link(struct net_device *dev,
7308 struct net_device *upper_dev, bool master,
7309 void *upper_priv, void *upper_info,
7310 struct netlink_ext_ack *extack)
7312 struct netdev_notifier_changeupper_info changeupper_info = {
7317 .upper_dev = upper_dev,
7320 .upper_info = upper_info,
7322 struct net_device *master_dev;
7327 if (dev == upper_dev)
7330 /* To prevent loops, check if dev is not upper device to upper_dev. */
7331 if (netdev_has_upper_dev(upper_dev, dev))
7335 if (netdev_has_upper_dev(dev, upper_dev))
7338 master_dev = netdev_master_upper_dev_get(dev);
7340 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7343 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7344 &changeupper_info.info);
7345 ret = notifier_to_errno(ret);
7349 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7354 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7355 &changeupper_info.info);
7356 ret = notifier_to_errno(ret);
7363 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7369 * netdev_upper_dev_link - Add a link to the upper device
7371 * @upper_dev: new upper device
7372 * @extack: netlink extended ack
7374 * Adds a link to device which is upper to this one. The caller must hold
7375 * the RTNL lock. On a failure a negative errno code is returned.
7376 * On success the reference counts are adjusted and the function
7379 int netdev_upper_dev_link(struct net_device *dev,
7380 struct net_device *upper_dev,
7381 struct netlink_ext_ack *extack)
7383 return __netdev_upper_dev_link(dev, upper_dev, false,
7384 NULL, NULL, extack);
7386 EXPORT_SYMBOL(netdev_upper_dev_link);
7389 * netdev_master_upper_dev_link - Add a master link to the upper device
7391 * @upper_dev: new upper device
7392 * @upper_priv: upper device private
7393 * @upper_info: upper info to be passed down via notifier
7394 * @extack: netlink extended ack
7396 * Adds a link to device which is upper to this one. In this case, only
7397 * one master upper device can be linked, although other non-master devices
7398 * might be linked as well. The caller must hold the RTNL lock.
7399 * On a failure a negative errno code is returned. On success the reference
7400 * counts are adjusted and the function returns zero.
7402 int netdev_master_upper_dev_link(struct net_device *dev,
7403 struct net_device *upper_dev,
7404 void *upper_priv, void *upper_info,
7405 struct netlink_ext_ack *extack)
7407 return __netdev_upper_dev_link(dev, upper_dev, true,
7408 upper_priv, upper_info, extack);
7410 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7413 * netdev_upper_dev_unlink - Removes a link to upper device
7415 * @upper_dev: new upper device
7417 * Removes a link to device which is upper to this one. The caller must hold
7420 void netdev_upper_dev_unlink(struct net_device *dev,
7421 struct net_device *upper_dev)
7423 struct netdev_notifier_changeupper_info changeupper_info = {
7427 .upper_dev = upper_dev,
7433 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7435 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7436 &changeupper_info.info);
7438 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7440 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7441 &changeupper_info.info);
7443 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7446 * netdev_bonding_info_change - Dispatch event about slave change
7448 * @bonding_info: info to dispatch
7450 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7451 * The caller must hold the RTNL lock.
7453 void netdev_bonding_info_change(struct net_device *dev,
7454 struct netdev_bonding_info *bonding_info)
7456 struct netdev_notifier_bonding_info info = {
7460 memcpy(&info.bonding_info, bonding_info,
7461 sizeof(struct netdev_bonding_info));
7462 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7465 EXPORT_SYMBOL(netdev_bonding_info_change);
7467 static void netdev_adjacent_add_links(struct net_device *dev)
7469 struct netdev_adjacent *iter;
7471 struct net *net = dev_net(dev);
7473 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7474 if (!net_eq(net, dev_net(iter->dev)))
7476 netdev_adjacent_sysfs_add(iter->dev, dev,
7477 &iter->dev->adj_list.lower);
7478 netdev_adjacent_sysfs_add(dev, iter->dev,
7479 &dev->adj_list.upper);
7482 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7483 if (!net_eq(net, dev_net(iter->dev)))
7485 netdev_adjacent_sysfs_add(iter->dev, dev,
7486 &iter->dev->adj_list.upper);
7487 netdev_adjacent_sysfs_add(dev, iter->dev,
7488 &dev->adj_list.lower);
7492 static void netdev_adjacent_del_links(struct net_device *dev)
7494 struct netdev_adjacent *iter;
7496 struct net *net = dev_net(dev);
7498 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7499 if (!net_eq(net, dev_net(iter->dev)))
7501 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7502 &iter->dev->adj_list.lower);
7503 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7504 &dev->adj_list.upper);
7507 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7508 if (!net_eq(net, dev_net(iter->dev)))
7510 netdev_adjacent_sysfs_del(iter->dev, dev->name,
7511 &iter->dev->adj_list.upper);
7512 netdev_adjacent_sysfs_del(dev, iter->dev->name,
7513 &dev->adj_list.lower);
7517 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
7519 struct netdev_adjacent *iter;
7521 struct net *net = dev_net(dev);
7523 list_for_each_entry(iter, &dev->adj_list.upper, list) {
7524 if (!net_eq(net, dev_net(iter->dev)))
7526 netdev_adjacent_sysfs_del(iter->dev, oldname,
7527 &iter->dev->adj_list.lower);
7528 netdev_adjacent_sysfs_add(iter->dev, dev,
7529 &iter->dev->adj_list.lower);
7532 list_for_each_entry(iter, &dev->adj_list.lower, list) {
7533 if (!net_eq(net, dev_net(iter->dev)))
7535 netdev_adjacent_sysfs_del(iter->dev, oldname,
7536 &iter->dev->adj_list.upper);
7537 netdev_adjacent_sysfs_add(iter->dev, dev,
7538 &iter->dev->adj_list.upper);
7542 void *netdev_lower_dev_get_private(struct net_device *dev,
7543 struct net_device *lower_dev)
7545 struct netdev_adjacent *lower;
7549 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
7553 return lower->private;
7555 EXPORT_SYMBOL(netdev_lower_dev_get_private);
7558 int dev_get_nest_level(struct net_device *dev)
7560 struct net_device *lower = NULL;
7561 struct list_head *iter;
7567 netdev_for_each_lower_dev(dev, lower, iter) {
7568 nest = dev_get_nest_level(lower);
7569 if (max_nest < nest)
7573 return max_nest + 1;
7575 EXPORT_SYMBOL(dev_get_nest_level);
7578 * netdev_lower_change - Dispatch event about lower device state change
7579 * @lower_dev: device
7580 * @lower_state_info: state to dispatch
7582 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
7583 * The caller must hold the RTNL lock.
7585 void netdev_lower_state_changed(struct net_device *lower_dev,
7586 void *lower_state_info)
7588 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
7589 .info.dev = lower_dev,
7593 changelowerstate_info.lower_state_info = lower_state_info;
7594 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
7595 &changelowerstate_info.info);
7597 EXPORT_SYMBOL(netdev_lower_state_changed);
7599 static void dev_change_rx_flags(struct net_device *dev, int flags)
7601 const struct net_device_ops *ops = dev->netdev_ops;
7603 if (ops->ndo_change_rx_flags)
7604 ops->ndo_change_rx_flags(dev, flags);
7607 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
7609 unsigned int old_flags = dev->flags;
7615 dev->flags |= IFF_PROMISC;
7616 dev->promiscuity += inc;
7617 if (dev->promiscuity == 0) {
7620 * If inc causes overflow, untouch promisc and return error.
7623 dev->flags &= ~IFF_PROMISC;
7625 dev->promiscuity -= inc;
7626 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
7631 if (dev->flags != old_flags) {
7632 pr_info("device %s %s promiscuous mode\n",
7634 dev->flags & IFF_PROMISC ? "entered" : "left");
7635 if (audit_enabled) {
7636 current_uid_gid(&uid, &gid);
7637 audit_log(audit_context(), GFP_ATOMIC,
7638 AUDIT_ANOM_PROMISCUOUS,
7639 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
7640 dev->name, (dev->flags & IFF_PROMISC),
7641 (old_flags & IFF_PROMISC),
7642 from_kuid(&init_user_ns, audit_get_loginuid(current)),
7643 from_kuid(&init_user_ns, uid),
7644 from_kgid(&init_user_ns, gid),
7645 audit_get_sessionid(current));
7648 dev_change_rx_flags(dev, IFF_PROMISC);
7651 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
7656 * dev_set_promiscuity - update promiscuity count on a device
7660 * Add or remove promiscuity from a device. While the count in the device
7661 * remains above zero the interface remains promiscuous. Once it hits zero
7662 * the device reverts back to normal filtering operation. A negative inc
7663 * value is used to drop promiscuity on the device.
7664 * Return 0 if successful or a negative errno code on error.
7666 int dev_set_promiscuity(struct net_device *dev, int inc)
7668 unsigned int old_flags = dev->flags;
7671 err = __dev_set_promiscuity(dev, inc, true);
7674 if (dev->flags != old_flags)
7675 dev_set_rx_mode(dev);
7678 EXPORT_SYMBOL(dev_set_promiscuity);
7680 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
7682 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
7686 dev->flags |= IFF_ALLMULTI;
7687 dev->allmulti += inc;
7688 if (dev->allmulti == 0) {
7691 * If inc causes overflow, untouch allmulti and return error.
7694 dev->flags &= ~IFF_ALLMULTI;
7696 dev->allmulti -= inc;
7697 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
7702 if (dev->flags ^ old_flags) {
7703 dev_change_rx_flags(dev, IFF_ALLMULTI);
7704 dev_set_rx_mode(dev);
7706 __dev_notify_flags(dev, old_flags,
7707 dev->gflags ^ old_gflags);
7713 * dev_set_allmulti - update allmulti count on a device
7717 * Add or remove reception of all multicast frames to a device. While the
7718 * count in the device remains above zero the interface remains listening
7719 * to all interfaces. Once it hits zero the device reverts back to normal
7720 * filtering operation. A negative @inc value is used to drop the counter
7721 * when releasing a resource needing all multicasts.
7722 * Return 0 if successful or a negative errno code on error.
7725 int dev_set_allmulti(struct net_device *dev, int inc)
7727 return __dev_set_allmulti(dev, inc, true);
7729 EXPORT_SYMBOL(dev_set_allmulti);
7732 * Upload unicast and multicast address lists to device and
7733 * configure RX filtering. When the device doesn't support unicast
7734 * filtering it is put in promiscuous mode while unicast addresses
7737 void __dev_set_rx_mode(struct net_device *dev)
7739 const struct net_device_ops *ops = dev->netdev_ops;
7741 /* dev_open will call this function so the list will stay sane. */
7742 if (!(dev->flags&IFF_UP))
7745 if (!netif_device_present(dev))
7748 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
7749 /* Unicast addresses changes may only happen under the rtnl,
7750 * therefore calling __dev_set_promiscuity here is safe.
7752 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
7753 __dev_set_promiscuity(dev, 1, false);
7754 dev->uc_promisc = true;
7755 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
7756 __dev_set_promiscuity(dev, -1, false);
7757 dev->uc_promisc = false;
7761 if (ops->ndo_set_rx_mode)
7762 ops->ndo_set_rx_mode(dev);
7765 void dev_set_rx_mode(struct net_device *dev)
7767 netif_addr_lock_bh(dev);
7768 __dev_set_rx_mode(dev);
7769 netif_addr_unlock_bh(dev);
7773 * dev_get_flags - get flags reported to userspace
7776 * Get the combination of flag bits exported through APIs to userspace.
7778 unsigned int dev_get_flags(const struct net_device *dev)
7782 flags = (dev->flags & ~(IFF_PROMISC |
7787 (dev->gflags & (IFF_PROMISC |
7790 if (netif_running(dev)) {
7791 if (netif_oper_up(dev))
7792 flags |= IFF_RUNNING;
7793 if (netif_carrier_ok(dev))
7794 flags |= IFF_LOWER_UP;
7795 if (netif_dormant(dev))
7796 flags |= IFF_DORMANT;
7801 EXPORT_SYMBOL(dev_get_flags);
7803 int __dev_change_flags(struct net_device *dev, unsigned int flags,
7804 struct netlink_ext_ack *extack)
7806 unsigned int old_flags = dev->flags;
7812 * Set the flags on our device.
7815 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
7816 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
7818 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
7822 * Load in the correct multicast list now the flags have changed.
7825 if ((old_flags ^ flags) & IFF_MULTICAST)
7826 dev_change_rx_flags(dev, IFF_MULTICAST);
7828 dev_set_rx_mode(dev);
7831 * Have we downed the interface. We handle IFF_UP ourselves
7832 * according to user attempts to set it, rather than blindly
7837 if ((old_flags ^ flags) & IFF_UP) {
7838 if (old_flags & IFF_UP)
7841 ret = __dev_open(dev, extack);
7844 if ((flags ^ dev->gflags) & IFF_PROMISC) {
7845 int inc = (flags & IFF_PROMISC) ? 1 : -1;
7846 unsigned int old_flags = dev->flags;
7848 dev->gflags ^= IFF_PROMISC;
7850 if (__dev_set_promiscuity(dev, inc, false) >= 0)
7851 if (dev->flags != old_flags)
7852 dev_set_rx_mode(dev);
7855 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
7856 * is important. Some (broken) drivers set IFF_PROMISC, when
7857 * IFF_ALLMULTI is requested not asking us and not reporting.
7859 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
7860 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
7862 dev->gflags ^= IFF_ALLMULTI;
7863 __dev_set_allmulti(dev, inc, false);
7869 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
7870 unsigned int gchanges)
7872 unsigned int changes = dev->flags ^ old_flags;
7875 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
7877 if (changes & IFF_UP) {
7878 if (dev->flags & IFF_UP)
7879 call_netdevice_notifiers(NETDEV_UP, dev);
7881 call_netdevice_notifiers(NETDEV_DOWN, dev);
7884 if (dev->flags & IFF_UP &&
7885 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
7886 struct netdev_notifier_change_info change_info = {
7890 .flags_changed = changes,
7893 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
7898 * dev_change_flags - change device settings
7900 * @flags: device state flags
7901 * @extack: netlink extended ack
7903 * Change settings on device based state flags. The flags are
7904 * in the userspace exported format.
7906 int dev_change_flags(struct net_device *dev, unsigned int flags,
7907 struct netlink_ext_ack *extack)
7910 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
7912 ret = __dev_change_flags(dev, flags, extack);
7916 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
7917 __dev_notify_flags(dev, old_flags, changes);
7920 EXPORT_SYMBOL(dev_change_flags);
7922 int __dev_set_mtu(struct net_device *dev, int new_mtu)
7924 const struct net_device_ops *ops = dev->netdev_ops;
7926 if (ops->ndo_change_mtu)
7927 return ops->ndo_change_mtu(dev, new_mtu);
7932 EXPORT_SYMBOL(__dev_set_mtu);
7935 * dev_set_mtu_ext - Change maximum transfer unit
7937 * @new_mtu: new transfer unit
7938 * @extack: netlink extended ack
7940 * Change the maximum transfer size of the network device.
7942 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
7943 struct netlink_ext_ack *extack)
7947 if (new_mtu == dev->mtu)
7950 /* MTU must be positive, and in range */
7951 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
7952 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
7956 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
7957 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
7961 if (!netif_device_present(dev))
7964 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
7965 err = notifier_to_errno(err);
7969 orig_mtu = dev->mtu;
7970 err = __dev_set_mtu(dev, new_mtu);
7973 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7975 err = notifier_to_errno(err);
7977 /* setting mtu back and notifying everyone again,
7978 * so that they have a chance to revert changes.
7980 __dev_set_mtu(dev, orig_mtu);
7981 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
7988 int dev_set_mtu(struct net_device *dev, int new_mtu)
7990 struct netlink_ext_ack extack;
7993 memset(&extack, 0, sizeof(extack));
7994 err = dev_set_mtu_ext(dev, new_mtu, &extack);
7995 if (err && extack._msg)
7996 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
7999 EXPORT_SYMBOL(dev_set_mtu);
8002 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8004 * @new_len: new tx queue length
8006 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8008 unsigned int orig_len = dev->tx_queue_len;
8011 if (new_len != (unsigned int)new_len)
8014 if (new_len != orig_len) {
8015 dev->tx_queue_len = new_len;
8016 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8017 res = notifier_to_errno(res);
8020 res = dev_qdisc_change_tx_queue_len(dev);
8028 netdev_err(dev, "refused to change device tx_queue_len\n");
8029 dev->tx_queue_len = orig_len;
8034 * dev_set_group - Change group this device belongs to
8036 * @new_group: group this device should belong to
8038 void dev_set_group(struct net_device *dev, int new_group)
8040 dev->group = new_group;
8042 EXPORT_SYMBOL(dev_set_group);
8045 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8047 * @addr: new address
8048 * @extack: netlink extended ack
8050 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8051 struct netlink_ext_ack *extack)
8053 struct netdev_notifier_pre_changeaddr_info info = {
8055 .info.extack = extack,
8060 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8061 return notifier_to_errno(rc);
8063 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8066 * dev_set_mac_address - Change Media Access Control Address
8069 * @extack: netlink extended ack
8071 * Change the hardware (MAC) address of the device
8073 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8074 struct netlink_ext_ack *extack)
8076 const struct net_device_ops *ops = dev->netdev_ops;
8079 if (!ops->ndo_set_mac_address)
8081 if (sa->sa_family != dev->type)
8083 if (!netif_device_present(dev))
8085 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8088 err = ops->ndo_set_mac_address(dev, sa);
8091 dev->addr_assign_type = NET_ADDR_SET;
8092 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8093 add_device_randomness(dev->dev_addr, dev->addr_len);
8096 EXPORT_SYMBOL(dev_set_mac_address);
8099 * dev_change_carrier - Change device carrier
8101 * @new_carrier: new value
8103 * Change device carrier
8105 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8107 const struct net_device_ops *ops = dev->netdev_ops;
8109 if (!ops->ndo_change_carrier)
8111 if (!netif_device_present(dev))
8113 return ops->ndo_change_carrier(dev, new_carrier);
8115 EXPORT_SYMBOL(dev_change_carrier);
8118 * dev_get_phys_port_id - Get device physical port ID
8122 * Get device physical port ID
8124 int dev_get_phys_port_id(struct net_device *dev,
8125 struct netdev_phys_item_id *ppid)
8127 const struct net_device_ops *ops = dev->netdev_ops;
8129 if (!ops->ndo_get_phys_port_id)
8131 return ops->ndo_get_phys_port_id(dev, ppid);
8133 EXPORT_SYMBOL(dev_get_phys_port_id);
8136 * dev_get_phys_port_name - Get device physical port name
8139 * @len: limit of bytes to copy to name
8141 * Get device physical port name
8143 int dev_get_phys_port_name(struct net_device *dev,
8144 char *name, size_t len)
8146 const struct net_device_ops *ops = dev->netdev_ops;
8149 if (ops->ndo_get_phys_port_name) {
8150 err = ops->ndo_get_phys_port_name(dev, name, len);
8151 if (err != -EOPNOTSUPP)
8154 return devlink_compat_phys_port_name_get(dev, name, len);
8156 EXPORT_SYMBOL(dev_get_phys_port_name);
8159 * dev_get_port_parent_id - Get the device's port parent identifier
8160 * @dev: network device
8161 * @ppid: pointer to a storage for the port's parent identifier
8162 * @recurse: allow/disallow recursion to lower devices
8164 * Get the devices's port parent identifier
8166 int dev_get_port_parent_id(struct net_device *dev,
8167 struct netdev_phys_item_id *ppid,
8170 const struct net_device_ops *ops = dev->netdev_ops;
8171 struct netdev_phys_item_id first = { };
8172 struct net_device *lower_dev;
8173 struct list_head *iter;
8176 if (ops->ndo_get_port_parent_id) {
8177 err = ops->ndo_get_port_parent_id(dev, ppid);
8178 if (err != -EOPNOTSUPP)
8182 err = devlink_compat_switch_id_get(dev, ppid);
8183 if (!err || err != -EOPNOTSUPP)
8189 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8190 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8195 else if (memcmp(&first, ppid, sizeof(*ppid)))
8201 EXPORT_SYMBOL(dev_get_port_parent_id);
8204 * netdev_port_same_parent_id - Indicate if two network devices have
8205 * the same port parent identifier
8206 * @a: first network device
8207 * @b: second network device
8209 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8211 struct netdev_phys_item_id a_id = { };
8212 struct netdev_phys_item_id b_id = { };
8214 if (dev_get_port_parent_id(a, &a_id, true) ||
8215 dev_get_port_parent_id(b, &b_id, true))
8218 return netdev_phys_item_id_same(&a_id, &b_id);
8220 EXPORT_SYMBOL(netdev_port_same_parent_id);
8223 * dev_change_proto_down - update protocol port state information
8225 * @proto_down: new value
8227 * This info can be used by switch drivers to set the phys state of the
8230 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8232 const struct net_device_ops *ops = dev->netdev_ops;
8234 if (!ops->ndo_change_proto_down)
8236 if (!netif_device_present(dev))
8238 return ops->ndo_change_proto_down(dev, proto_down);
8240 EXPORT_SYMBOL(dev_change_proto_down);
8243 * dev_change_proto_down_generic - generic implementation for
8244 * ndo_change_proto_down that sets carrier according to
8248 * @proto_down: new value
8250 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8253 netif_carrier_off(dev);
8255 netif_carrier_on(dev);
8256 dev->proto_down = proto_down;
8259 EXPORT_SYMBOL(dev_change_proto_down_generic);
8261 u32 __dev_xdp_query(struct net_device *dev, bpf_op_t bpf_op,
8262 enum bpf_netdev_command cmd)
8264 struct netdev_bpf xdp;
8269 memset(&xdp, 0, sizeof(xdp));
8272 /* Query must always succeed. */
8273 WARN_ON(bpf_op(dev, &xdp) < 0 && cmd == XDP_QUERY_PROG);
8278 static int dev_xdp_install(struct net_device *dev, bpf_op_t bpf_op,
8279 struct netlink_ext_ack *extack, u32 flags,
8280 struct bpf_prog *prog)
8282 struct netdev_bpf xdp;
8284 memset(&xdp, 0, sizeof(xdp));
8285 if (flags & XDP_FLAGS_HW_MODE)
8286 xdp.command = XDP_SETUP_PROG_HW;
8288 xdp.command = XDP_SETUP_PROG;
8289 xdp.extack = extack;
8293 return bpf_op(dev, &xdp);
8296 static void dev_xdp_uninstall(struct net_device *dev)
8298 struct netdev_bpf xdp;
8301 /* Remove generic XDP */
8302 WARN_ON(dev_xdp_install(dev, generic_xdp_install, NULL, 0, NULL));
8304 /* Remove from the driver */
8305 ndo_bpf = dev->netdev_ops->ndo_bpf;
8309 memset(&xdp, 0, sizeof(xdp));
8310 xdp.command = XDP_QUERY_PROG;
8311 WARN_ON(ndo_bpf(dev, &xdp));
8313 WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
8316 /* Remove HW offload */
8317 memset(&xdp, 0, sizeof(xdp));
8318 xdp.command = XDP_QUERY_PROG_HW;
8319 if (!ndo_bpf(dev, &xdp) && xdp.prog_id)
8320 WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
8325 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
8327 * @extack: netlink extended ack
8328 * @fd: new program fd or negative value to clear
8329 * @flags: xdp-related flags
8331 * Set or clear a bpf program for a device
8333 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
8336 const struct net_device_ops *ops = dev->netdev_ops;
8337 enum bpf_netdev_command query;
8338 struct bpf_prog *prog = NULL;
8339 bpf_op_t bpf_op, bpf_chk;
8345 offload = flags & XDP_FLAGS_HW_MODE;
8346 query = offload ? XDP_QUERY_PROG_HW : XDP_QUERY_PROG;
8348 bpf_op = bpf_chk = ops->ndo_bpf;
8349 if (!bpf_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE))) {
8350 NL_SET_ERR_MSG(extack, "underlying driver does not support XDP in native mode");
8353 if (!bpf_op || (flags & XDP_FLAGS_SKB_MODE))
8354 bpf_op = generic_xdp_install;
8355 if (bpf_op == bpf_chk)
8356 bpf_chk = generic_xdp_install;
8361 if (!offload && __dev_xdp_query(dev, bpf_chk, XDP_QUERY_PROG)) {
8362 NL_SET_ERR_MSG(extack, "native and generic XDP can't be active at the same time");
8366 prog_id = __dev_xdp_query(dev, bpf_op, query);
8367 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && prog_id) {
8368 NL_SET_ERR_MSG(extack, "XDP program already attached");
8372 prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
8373 bpf_op == ops->ndo_bpf);
8375 return PTR_ERR(prog);
8377 if (!offload && bpf_prog_is_dev_bound(prog->aux)) {
8378 NL_SET_ERR_MSG(extack, "using device-bound program without HW_MODE flag is not supported");
8383 if (prog->aux->id == prog_id) {
8388 if (!__dev_xdp_query(dev, bpf_op, query))
8392 err = dev_xdp_install(dev, bpf_op, extack, flags, prog);
8393 if (err < 0 && prog)
8400 * dev_new_index - allocate an ifindex
8401 * @net: the applicable net namespace
8403 * Returns a suitable unique value for a new device interface
8404 * number. The caller must hold the rtnl semaphore or the
8405 * dev_base_lock to be sure it remains unique.
8407 static int dev_new_index(struct net *net)
8409 int ifindex = net->ifindex;
8414 if (!__dev_get_by_index(net, ifindex))
8415 return net->ifindex = ifindex;
8419 /* Delayed registration/unregisteration */
8420 static LIST_HEAD(net_todo_list);
8421 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
8423 static void net_set_todo(struct net_device *dev)
8425 list_add_tail(&dev->todo_list, &net_todo_list);
8426 dev_net(dev)->dev_unreg_count++;
8429 static void rollback_registered_many(struct list_head *head)
8431 struct net_device *dev, *tmp;
8432 LIST_HEAD(close_head);
8434 BUG_ON(dev_boot_phase);
8437 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
8438 /* Some devices call without registering
8439 * for initialization unwind. Remove those
8440 * devices and proceed with the remaining.
8442 if (dev->reg_state == NETREG_UNINITIALIZED) {
8443 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
8447 list_del(&dev->unreg_list);
8450 dev->dismantle = true;
8451 BUG_ON(dev->reg_state != NETREG_REGISTERED);
8454 /* If device is running, close it first. */
8455 list_for_each_entry(dev, head, unreg_list)
8456 list_add_tail(&dev->close_list, &close_head);
8457 dev_close_many(&close_head, true);
8459 list_for_each_entry(dev, head, unreg_list) {
8460 /* And unlink it from device chain. */
8461 unlist_netdevice(dev);
8463 dev->reg_state = NETREG_UNREGISTERING;
8465 flush_all_backlogs();
8469 list_for_each_entry(dev, head, unreg_list) {
8470 struct sk_buff *skb = NULL;
8472 /* Shutdown queueing discipline. */
8475 dev_xdp_uninstall(dev);
8477 /* Notify protocols, that we are about to destroy
8478 * this device. They should clean all the things.
8480 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
8482 if (!dev->rtnl_link_ops ||
8483 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
8484 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
8485 GFP_KERNEL, NULL, 0);
8488 * Flush the unicast and multicast chains
8493 netdev_name_node_alt_flush(dev);
8494 netdev_name_node_free(dev->name_node);
8496 if (dev->netdev_ops->ndo_uninit)
8497 dev->netdev_ops->ndo_uninit(dev);
8500 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
8502 /* Notifier chain MUST detach us all upper devices. */
8503 WARN_ON(netdev_has_any_upper_dev(dev));
8504 WARN_ON(netdev_has_any_lower_dev(dev));
8506 /* Remove entries from kobject tree */
8507 netdev_unregister_kobject(dev);
8509 /* Remove XPS queueing entries */
8510 netif_reset_xps_queues_gt(dev, 0);
8516 list_for_each_entry(dev, head, unreg_list)
8520 static void rollback_registered(struct net_device *dev)
8524 list_add(&dev->unreg_list, &single);
8525 rollback_registered_many(&single);
8529 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
8530 struct net_device *upper, netdev_features_t features)
8532 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
8533 netdev_features_t feature;
8536 for_each_netdev_feature(upper_disables, feature_bit) {
8537 feature = __NETIF_F_BIT(feature_bit);
8538 if (!(upper->wanted_features & feature)
8539 && (features & feature)) {
8540 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
8541 &feature, upper->name);
8542 features &= ~feature;
8549 static void netdev_sync_lower_features(struct net_device *upper,
8550 struct net_device *lower, netdev_features_t features)
8552 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
8553 netdev_features_t feature;
8556 for_each_netdev_feature(upper_disables, feature_bit) {
8557 feature = __NETIF_F_BIT(feature_bit);
8558 if (!(features & feature) && (lower->features & feature)) {
8559 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
8560 &feature, lower->name);
8561 lower->wanted_features &= ~feature;
8562 netdev_update_features(lower);
8564 if (unlikely(lower->features & feature))
8565 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
8566 &feature, lower->name);
8571 static netdev_features_t netdev_fix_features(struct net_device *dev,
8572 netdev_features_t features)
8574 /* Fix illegal checksum combinations */
8575 if ((features & NETIF_F_HW_CSUM) &&
8576 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
8577 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
8578 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
8581 /* TSO requires that SG is present as well. */
8582 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
8583 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
8584 features &= ~NETIF_F_ALL_TSO;
8587 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
8588 !(features & NETIF_F_IP_CSUM)) {
8589 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
8590 features &= ~NETIF_F_TSO;
8591 features &= ~NETIF_F_TSO_ECN;
8594 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
8595 !(features & NETIF_F_IPV6_CSUM)) {
8596 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
8597 features &= ~NETIF_F_TSO6;
8600 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
8601 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
8602 features &= ~NETIF_F_TSO_MANGLEID;
8604 /* TSO ECN requires that TSO is present as well. */
8605 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
8606 features &= ~NETIF_F_TSO_ECN;
8608 /* Software GSO depends on SG. */
8609 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
8610 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
8611 features &= ~NETIF_F_GSO;
8614 /* GSO partial features require GSO partial be set */
8615 if ((features & dev->gso_partial_features) &&
8616 !(features & NETIF_F_GSO_PARTIAL)) {
8618 "Dropping partially supported GSO features since no GSO partial.\n");
8619 features &= ~dev->gso_partial_features;
8622 if (!(features & NETIF_F_RXCSUM)) {
8623 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
8624 * successfully merged by hardware must also have the
8625 * checksum verified by hardware. If the user does not
8626 * want to enable RXCSUM, logically, we should disable GRO_HW.
8628 if (features & NETIF_F_GRO_HW) {
8629 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
8630 features &= ~NETIF_F_GRO_HW;
8634 /* LRO/HW-GRO features cannot be combined with RX-FCS */
8635 if (features & NETIF_F_RXFCS) {
8636 if (features & NETIF_F_LRO) {
8637 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
8638 features &= ~NETIF_F_LRO;
8641 if (features & NETIF_F_GRO_HW) {
8642 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
8643 features &= ~NETIF_F_GRO_HW;
8650 int __netdev_update_features(struct net_device *dev)
8652 struct net_device *upper, *lower;
8653 netdev_features_t features;
8654 struct list_head *iter;
8659 features = netdev_get_wanted_features(dev);
8661 if (dev->netdev_ops->ndo_fix_features)
8662 features = dev->netdev_ops->ndo_fix_features(dev, features);
8664 /* driver might be less strict about feature dependencies */
8665 features = netdev_fix_features(dev, features);
8667 /* some features can't be enabled if they're off an an upper device */
8668 netdev_for_each_upper_dev_rcu(dev, upper, iter)
8669 features = netdev_sync_upper_features(dev, upper, features);
8671 if (dev->features == features)
8674 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
8675 &dev->features, &features);
8677 if (dev->netdev_ops->ndo_set_features)
8678 err = dev->netdev_ops->ndo_set_features(dev, features);
8682 if (unlikely(err < 0)) {
8684 "set_features() failed (%d); wanted %pNF, left %pNF\n",
8685 err, &features, &dev->features);
8686 /* return non-0 since some features might have changed and
8687 * it's better to fire a spurious notification than miss it
8693 /* some features must be disabled on lower devices when disabled
8694 * on an upper device (think: bonding master or bridge)
8696 netdev_for_each_lower_dev(dev, lower, iter)
8697 netdev_sync_lower_features(dev, lower, features);
8700 netdev_features_t diff = features ^ dev->features;
8702 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
8703 /* udp_tunnel_{get,drop}_rx_info both need
8704 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
8705 * device, or they won't do anything.
8706 * Thus we need to update dev->features
8707 * *before* calling udp_tunnel_get_rx_info,
8708 * but *after* calling udp_tunnel_drop_rx_info.
8710 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
8711 dev->features = features;
8712 udp_tunnel_get_rx_info(dev);
8714 udp_tunnel_drop_rx_info(dev);
8718 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
8719 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
8720 dev->features = features;
8721 err |= vlan_get_rx_ctag_filter_info(dev);
8723 vlan_drop_rx_ctag_filter_info(dev);
8727 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
8728 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
8729 dev->features = features;
8730 err |= vlan_get_rx_stag_filter_info(dev);
8732 vlan_drop_rx_stag_filter_info(dev);
8736 dev->features = features;
8739 return err < 0 ? 0 : 1;
8743 * netdev_update_features - recalculate device features
8744 * @dev: the device to check
8746 * Recalculate dev->features set and send notifications if it
8747 * has changed. Should be called after driver or hardware dependent
8748 * conditions might have changed that influence the features.
8750 void netdev_update_features(struct net_device *dev)
8752 if (__netdev_update_features(dev))
8753 netdev_features_change(dev);
8755 EXPORT_SYMBOL(netdev_update_features);
8758 * netdev_change_features - recalculate device features
8759 * @dev: the device to check
8761 * Recalculate dev->features set and send notifications even
8762 * if they have not changed. Should be called instead of
8763 * netdev_update_features() if also dev->vlan_features might
8764 * have changed to allow the changes to be propagated to stacked
8767 void netdev_change_features(struct net_device *dev)
8769 __netdev_update_features(dev);
8770 netdev_features_change(dev);
8772 EXPORT_SYMBOL(netdev_change_features);
8775 * netif_stacked_transfer_operstate - transfer operstate
8776 * @rootdev: the root or lower level device to transfer state from
8777 * @dev: the device to transfer operstate to
8779 * Transfer operational state from root to device. This is normally
8780 * called when a stacking relationship exists between the root
8781 * device and the device(a leaf device).
8783 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
8784 struct net_device *dev)
8786 if (rootdev->operstate == IF_OPER_DORMANT)
8787 netif_dormant_on(dev);
8789 netif_dormant_off(dev);
8791 if (netif_carrier_ok(rootdev))
8792 netif_carrier_on(dev);
8794 netif_carrier_off(dev);
8796 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
8798 static int netif_alloc_rx_queues(struct net_device *dev)
8800 unsigned int i, count = dev->num_rx_queues;
8801 struct netdev_rx_queue *rx;
8802 size_t sz = count * sizeof(*rx);
8807 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8813 for (i = 0; i < count; i++) {
8816 /* XDP RX-queue setup */
8817 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
8824 /* Rollback successful reg's and free other resources */
8826 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
8832 static void netif_free_rx_queues(struct net_device *dev)
8834 unsigned int i, count = dev->num_rx_queues;
8836 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
8840 for (i = 0; i < count; i++)
8841 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
8846 static void netdev_init_one_queue(struct net_device *dev,
8847 struct netdev_queue *queue, void *_unused)
8849 /* Initialize queue lock */
8850 spin_lock_init(&queue->_xmit_lock);
8851 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
8852 queue->xmit_lock_owner = -1;
8853 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
8856 dql_init(&queue->dql, HZ);
8860 static void netif_free_tx_queues(struct net_device *dev)
8865 static int netif_alloc_netdev_queues(struct net_device *dev)
8867 unsigned int count = dev->num_tx_queues;
8868 struct netdev_queue *tx;
8869 size_t sz = count * sizeof(*tx);
8871 if (count < 1 || count > 0xffff)
8874 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
8880 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
8881 spin_lock_init(&dev->tx_global_lock);
8886 void netif_tx_stop_all_queues(struct net_device *dev)
8890 for (i = 0; i < dev->num_tx_queues; i++) {
8891 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
8893 netif_tx_stop_queue(txq);
8896 EXPORT_SYMBOL(netif_tx_stop_all_queues);
8899 * register_netdevice - register a network device
8900 * @dev: device to register
8902 * Take a completed network device structure and add it to the kernel
8903 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
8904 * chain. 0 is returned on success. A negative errno code is returned
8905 * on a failure to set up the device, or if the name is a duplicate.
8907 * Callers must hold the rtnl semaphore. You may want
8908 * register_netdev() instead of this.
8911 * The locking appears insufficient to guarantee two parallel registers
8912 * will not get the same name.
8915 int register_netdevice(struct net_device *dev)
8918 struct net *net = dev_net(dev);
8920 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
8921 NETDEV_FEATURE_COUNT);
8922 BUG_ON(dev_boot_phase);
8927 /* When net_device's are persistent, this will be fatal. */
8928 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
8931 spin_lock_init(&dev->addr_list_lock);
8932 netdev_set_addr_lockdep_class(dev);
8934 ret = dev_get_valid_name(net, dev, dev->name);
8938 dev->name_node = netdev_name_node_head_alloc(dev);
8939 if (!dev->name_node)
8942 /* Init, if this function is available */
8943 if (dev->netdev_ops->ndo_init) {
8944 ret = dev->netdev_ops->ndo_init(dev);
8952 if (((dev->hw_features | dev->features) &
8953 NETIF_F_HW_VLAN_CTAG_FILTER) &&
8954 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
8955 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
8956 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
8963 dev->ifindex = dev_new_index(net);
8964 else if (__dev_get_by_index(net, dev->ifindex))
8967 /* Transfer changeable features to wanted_features and enable
8968 * software offloads (GSO and GRO).
8970 dev->hw_features |= NETIF_F_SOFT_FEATURES;
8971 dev->features |= NETIF_F_SOFT_FEATURES;
8973 if (dev->netdev_ops->ndo_udp_tunnel_add) {
8974 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
8975 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
8978 dev->wanted_features = dev->features & dev->hw_features;
8980 if (!(dev->flags & IFF_LOOPBACK))
8981 dev->hw_features |= NETIF_F_NOCACHE_COPY;
8983 /* If IPv4 TCP segmentation offload is supported we should also
8984 * allow the device to enable segmenting the frame with the option
8985 * of ignoring a static IP ID value. This doesn't enable the
8986 * feature itself but allows the user to enable it later.
8988 if (dev->hw_features & NETIF_F_TSO)
8989 dev->hw_features |= NETIF_F_TSO_MANGLEID;
8990 if (dev->vlan_features & NETIF_F_TSO)
8991 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
8992 if (dev->mpls_features & NETIF_F_TSO)
8993 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
8994 if (dev->hw_enc_features & NETIF_F_TSO)
8995 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
8997 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
8999 dev->vlan_features |= NETIF_F_HIGHDMA;
9001 /* Make NETIF_F_SG inheritable to tunnel devices.
9003 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
9005 /* Make NETIF_F_SG inheritable to MPLS.
9007 dev->mpls_features |= NETIF_F_SG;
9009 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
9010 ret = notifier_to_errno(ret);
9014 ret = netdev_register_kobject(dev);
9017 dev->reg_state = NETREG_REGISTERED;
9019 __netdev_update_features(dev);
9022 * Default initial state at registry is that the
9023 * device is present.
9026 set_bit(__LINK_STATE_PRESENT, &dev->state);
9028 linkwatch_init_dev(dev);
9030 dev_init_scheduler(dev);
9032 list_netdevice(dev);
9033 add_device_randomness(dev->dev_addr, dev->addr_len);
9035 /* If the device has permanent device address, driver should
9036 * set dev_addr and also addr_assign_type should be set to
9037 * NET_ADDR_PERM (default value).
9039 if (dev->addr_assign_type == NET_ADDR_PERM)
9040 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
9042 /* Notify protocols, that a new device appeared. */
9043 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
9044 ret = notifier_to_errno(ret);
9046 rollback_registered(dev);
9049 dev->reg_state = NETREG_UNREGISTERED;
9052 * Prevent userspace races by waiting until the network
9053 * device is fully setup before sending notifications.
9055 if (!dev->rtnl_link_ops ||
9056 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
9057 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9064 netdev_name_node_free(dev->name_node);
9065 if (dev->netdev_ops->ndo_uninit)
9066 dev->netdev_ops->ndo_uninit(dev);
9067 if (dev->priv_destructor)
9068 dev->priv_destructor(dev);
9071 EXPORT_SYMBOL(register_netdevice);
9074 * init_dummy_netdev - init a dummy network device for NAPI
9075 * @dev: device to init
9077 * This takes a network device structure and initialize the minimum
9078 * amount of fields so it can be used to schedule NAPI polls without
9079 * registering a full blown interface. This is to be used by drivers
9080 * that need to tie several hardware interfaces to a single NAPI
9081 * poll scheduler due to HW limitations.
9083 int init_dummy_netdev(struct net_device *dev)
9085 /* Clear everything. Note we don't initialize spinlocks
9086 * are they aren't supposed to be taken by any of the
9087 * NAPI code and this dummy netdev is supposed to be
9088 * only ever used for NAPI polls
9090 memset(dev, 0, sizeof(struct net_device));
9092 /* make sure we BUG if trying to hit standard
9093 * register/unregister code path
9095 dev->reg_state = NETREG_DUMMY;
9097 /* NAPI wants this */
9098 INIT_LIST_HEAD(&dev->napi_list);
9100 /* a dummy interface is started by default */
9101 set_bit(__LINK_STATE_PRESENT, &dev->state);
9102 set_bit(__LINK_STATE_START, &dev->state);
9104 /* napi_busy_loop stats accounting wants this */
9105 dev_net_set(dev, &init_net);
9107 /* Note : We dont allocate pcpu_refcnt for dummy devices,
9108 * because users of this 'device' dont need to change
9114 EXPORT_SYMBOL_GPL(init_dummy_netdev);
9118 * register_netdev - register a network device
9119 * @dev: device to register
9121 * Take a completed network device structure and add it to the kernel
9122 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9123 * chain. 0 is returned on success. A negative errno code is returned
9124 * on a failure to set up the device, or if the name is a duplicate.
9126 * This is a wrapper around register_netdevice that takes the rtnl semaphore
9127 * and expands the device name if you passed a format string to
9130 int register_netdev(struct net_device *dev)
9134 if (rtnl_lock_killable())
9136 err = register_netdevice(dev);
9140 EXPORT_SYMBOL(register_netdev);
9142 int netdev_refcnt_read(const struct net_device *dev)
9146 for_each_possible_cpu(i)
9147 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
9150 EXPORT_SYMBOL(netdev_refcnt_read);
9153 * netdev_wait_allrefs - wait until all references are gone.
9154 * @dev: target net_device
9156 * This is called when unregistering network devices.
9158 * Any protocol or device that holds a reference should register
9159 * for netdevice notification, and cleanup and put back the
9160 * reference if they receive an UNREGISTER event.
9161 * We can get stuck here if buggy protocols don't correctly
9164 static void netdev_wait_allrefs(struct net_device *dev)
9166 unsigned long rebroadcast_time, warning_time;
9169 linkwatch_forget_dev(dev);
9171 rebroadcast_time = warning_time = jiffies;
9172 refcnt = netdev_refcnt_read(dev);
9174 while (refcnt != 0) {
9175 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
9178 /* Rebroadcast unregister notification */
9179 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9185 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
9187 /* We must not have linkwatch events
9188 * pending on unregister. If this
9189 * happens, we simply run the queue
9190 * unscheduled, resulting in a noop
9193 linkwatch_run_queue();
9198 rebroadcast_time = jiffies;
9203 refcnt = netdev_refcnt_read(dev);
9205 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
9206 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
9208 warning_time = jiffies;
9217 * register_netdevice(x1);
9218 * register_netdevice(x2);
9220 * unregister_netdevice(y1);
9221 * unregister_netdevice(y2);
9227 * We are invoked by rtnl_unlock().
9228 * This allows us to deal with problems:
9229 * 1) We can delete sysfs objects which invoke hotplug
9230 * without deadlocking with linkwatch via keventd.
9231 * 2) Since we run with the RTNL semaphore not held, we can sleep
9232 * safely in order to wait for the netdev refcnt to drop to zero.
9234 * We must not return until all unregister events added during
9235 * the interval the lock was held have been completed.
9237 void netdev_run_todo(void)
9239 struct list_head list;
9241 /* Snapshot list, allow later requests */
9242 list_replace_init(&net_todo_list, &list);
9247 /* Wait for rcu callbacks to finish before next phase */
9248 if (!list_empty(&list))
9251 while (!list_empty(&list)) {
9252 struct net_device *dev
9253 = list_first_entry(&list, struct net_device, todo_list);
9254 list_del(&dev->todo_list);
9256 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
9257 pr_err("network todo '%s' but state %d\n",
9258 dev->name, dev->reg_state);
9263 dev->reg_state = NETREG_UNREGISTERED;
9265 netdev_wait_allrefs(dev);
9268 BUG_ON(netdev_refcnt_read(dev));
9269 BUG_ON(!list_empty(&dev->ptype_all));
9270 BUG_ON(!list_empty(&dev->ptype_specific));
9271 WARN_ON(rcu_access_pointer(dev->ip_ptr));
9272 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
9273 #if IS_ENABLED(CONFIG_DECNET)
9274 WARN_ON(dev->dn_ptr);
9276 if (dev->priv_destructor)
9277 dev->priv_destructor(dev);
9278 if (dev->needs_free_netdev)
9281 /* Report a network device has been unregistered */
9283 dev_net(dev)->dev_unreg_count--;
9285 wake_up(&netdev_unregistering_wq);
9287 /* Free network device */
9288 kobject_put(&dev->dev.kobj);
9292 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
9293 * all the same fields in the same order as net_device_stats, with only
9294 * the type differing, but rtnl_link_stats64 may have additional fields
9295 * at the end for newer counters.
9297 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
9298 const struct net_device_stats *netdev_stats)
9300 #if BITS_PER_LONG == 64
9301 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
9302 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
9303 /* zero out counters that only exist in rtnl_link_stats64 */
9304 memset((char *)stats64 + sizeof(*netdev_stats), 0,
9305 sizeof(*stats64) - sizeof(*netdev_stats));
9307 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
9308 const unsigned long *src = (const unsigned long *)netdev_stats;
9309 u64 *dst = (u64 *)stats64;
9311 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
9312 for (i = 0; i < n; i++)
9314 /* zero out counters that only exist in rtnl_link_stats64 */
9315 memset((char *)stats64 + n * sizeof(u64), 0,
9316 sizeof(*stats64) - n * sizeof(u64));
9319 EXPORT_SYMBOL(netdev_stats_to_stats64);
9322 * dev_get_stats - get network device statistics
9323 * @dev: device to get statistics from
9324 * @storage: place to store stats
9326 * Get network statistics from device. Return @storage.
9327 * The device driver may provide its own method by setting
9328 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
9329 * otherwise the internal statistics structure is used.
9331 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
9332 struct rtnl_link_stats64 *storage)
9334 const struct net_device_ops *ops = dev->netdev_ops;
9336 if (ops->ndo_get_stats64) {
9337 memset(storage, 0, sizeof(*storage));
9338 ops->ndo_get_stats64(dev, storage);
9339 } else if (ops->ndo_get_stats) {
9340 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
9342 netdev_stats_to_stats64(storage, &dev->stats);
9344 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
9345 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
9346 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
9349 EXPORT_SYMBOL(dev_get_stats);
9351 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
9353 struct netdev_queue *queue = dev_ingress_queue(dev);
9355 #ifdef CONFIG_NET_CLS_ACT
9358 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
9361 netdev_init_one_queue(dev, queue, NULL);
9362 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
9363 queue->qdisc_sleeping = &noop_qdisc;
9364 rcu_assign_pointer(dev->ingress_queue, queue);
9369 static const struct ethtool_ops default_ethtool_ops;
9371 void netdev_set_default_ethtool_ops(struct net_device *dev,
9372 const struct ethtool_ops *ops)
9374 if (dev->ethtool_ops == &default_ethtool_ops)
9375 dev->ethtool_ops = ops;
9377 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
9379 void netdev_freemem(struct net_device *dev)
9381 char *addr = (char *)dev - dev->padded;
9387 * alloc_netdev_mqs - allocate network device
9388 * @sizeof_priv: size of private data to allocate space for
9389 * @name: device name format string
9390 * @name_assign_type: origin of device name
9391 * @setup: callback to initialize device
9392 * @txqs: the number of TX subqueues to allocate
9393 * @rxqs: the number of RX subqueues to allocate
9395 * Allocates a struct net_device with private data area for driver use
9396 * and performs basic initialization. Also allocates subqueue structs
9397 * for each queue on the device.
9399 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
9400 unsigned char name_assign_type,
9401 void (*setup)(struct net_device *),
9402 unsigned int txqs, unsigned int rxqs)
9404 struct net_device *dev;
9405 unsigned int alloc_size;
9406 struct net_device *p;
9408 BUG_ON(strlen(name) >= sizeof(dev->name));
9411 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
9416 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
9420 alloc_size = sizeof(struct net_device);
9422 /* ensure 32-byte alignment of private area */
9423 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
9424 alloc_size += sizeof_priv;
9426 /* ensure 32-byte alignment of whole construct */
9427 alloc_size += NETDEV_ALIGN - 1;
9429 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9433 dev = PTR_ALIGN(p, NETDEV_ALIGN);
9434 dev->padded = (char *)dev - (char *)p;
9436 dev->pcpu_refcnt = alloc_percpu(int);
9437 if (!dev->pcpu_refcnt)
9440 if (dev_addr_init(dev))
9446 dev_net_set(dev, &init_net);
9448 dev->gso_max_size = GSO_MAX_SIZE;
9449 dev->gso_max_segs = GSO_MAX_SEGS;
9451 INIT_LIST_HEAD(&dev->napi_list);
9452 INIT_LIST_HEAD(&dev->unreg_list);
9453 INIT_LIST_HEAD(&dev->close_list);
9454 INIT_LIST_HEAD(&dev->link_watch_list);
9455 INIT_LIST_HEAD(&dev->adj_list.upper);
9456 INIT_LIST_HEAD(&dev->adj_list.lower);
9457 INIT_LIST_HEAD(&dev->ptype_all);
9458 INIT_LIST_HEAD(&dev->ptype_specific);
9459 #ifdef CONFIG_NET_SCHED
9460 hash_init(dev->qdisc_hash);
9462 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
9465 if (!dev->tx_queue_len) {
9466 dev->priv_flags |= IFF_NO_QUEUE;
9467 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
9470 dev->num_tx_queues = txqs;
9471 dev->real_num_tx_queues = txqs;
9472 if (netif_alloc_netdev_queues(dev))
9475 dev->num_rx_queues = rxqs;
9476 dev->real_num_rx_queues = rxqs;
9477 if (netif_alloc_rx_queues(dev))
9480 strcpy(dev->name, name);
9481 dev->name_assign_type = name_assign_type;
9482 dev->group = INIT_NETDEV_GROUP;
9483 if (!dev->ethtool_ops)
9484 dev->ethtool_ops = &default_ethtool_ops;
9486 nf_hook_ingress_init(dev);
9495 free_percpu(dev->pcpu_refcnt);
9497 netdev_freemem(dev);
9500 EXPORT_SYMBOL(alloc_netdev_mqs);
9503 * free_netdev - free network device
9506 * This function does the last stage of destroying an allocated device
9507 * interface. The reference to the device object is released. If this
9508 * is the last reference then it will be freed.Must be called in process
9511 void free_netdev(struct net_device *dev)
9513 struct napi_struct *p, *n;
9516 netif_free_tx_queues(dev);
9517 netif_free_rx_queues(dev);
9519 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
9521 /* Flush device addresses */
9522 dev_addr_flush(dev);
9524 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
9527 free_percpu(dev->pcpu_refcnt);
9528 dev->pcpu_refcnt = NULL;
9530 /* Compatibility with error handling in drivers */
9531 if (dev->reg_state == NETREG_UNINITIALIZED) {
9532 netdev_freemem(dev);
9536 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
9537 dev->reg_state = NETREG_RELEASED;
9539 /* will free via device release */
9540 put_device(&dev->dev);
9542 EXPORT_SYMBOL(free_netdev);
9545 * synchronize_net - Synchronize with packet receive processing
9547 * Wait for packets currently being received to be done.
9548 * Does not block later packets from starting.
9550 void synchronize_net(void)
9553 if (rtnl_is_locked())
9554 synchronize_rcu_expedited();
9558 EXPORT_SYMBOL(synchronize_net);
9561 * unregister_netdevice_queue - remove device from the kernel
9565 * This function shuts down a device interface and removes it
9566 * from the kernel tables.
9567 * If head not NULL, device is queued to be unregistered later.
9569 * Callers must hold the rtnl semaphore. You may want
9570 * unregister_netdev() instead of this.
9573 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
9578 list_move_tail(&dev->unreg_list, head);
9580 rollback_registered(dev);
9581 /* Finish processing unregister after unlock */
9585 EXPORT_SYMBOL(unregister_netdevice_queue);
9588 * unregister_netdevice_many - unregister many devices
9589 * @head: list of devices
9591 * Note: As most callers use a stack allocated list_head,
9592 * we force a list_del() to make sure stack wont be corrupted later.
9594 void unregister_netdevice_many(struct list_head *head)
9596 struct net_device *dev;
9598 if (!list_empty(head)) {
9599 rollback_registered_many(head);
9600 list_for_each_entry(dev, head, unreg_list)
9605 EXPORT_SYMBOL(unregister_netdevice_many);
9608 * unregister_netdev - remove device from the kernel
9611 * This function shuts down a device interface and removes it
9612 * from the kernel tables.
9614 * This is just a wrapper for unregister_netdevice that takes
9615 * the rtnl semaphore. In general you want to use this and not
9616 * unregister_netdevice.
9618 void unregister_netdev(struct net_device *dev)
9621 unregister_netdevice(dev);
9624 EXPORT_SYMBOL(unregister_netdev);
9627 * dev_change_net_namespace - move device to different nethost namespace
9629 * @net: network namespace
9630 * @pat: If not NULL name pattern to try if the current device name
9631 * is already taken in the destination network namespace.
9633 * This function shuts down a device interface and moves it
9634 * to a new network namespace. On success 0 is returned, on
9635 * a failure a netagive errno code is returned.
9637 * Callers must hold the rtnl semaphore.
9640 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
9642 int err, new_nsid, new_ifindex;
9646 /* Don't allow namespace local devices to be moved. */
9648 if (dev->features & NETIF_F_NETNS_LOCAL)
9651 /* Ensure the device has been registrered */
9652 if (dev->reg_state != NETREG_REGISTERED)
9655 /* Get out if there is nothing todo */
9657 if (net_eq(dev_net(dev), net))
9660 /* Pick the destination device name, and ensure
9661 * we can use it in the destination network namespace.
9664 if (__dev_get_by_name(net, dev->name)) {
9665 /* We get here if we can't use the current device name */
9668 err = dev_get_valid_name(net, dev, pat);
9674 * And now a mini version of register_netdevice unregister_netdevice.
9677 /* If device is running close it first. */
9680 /* And unlink it from device chain */
9681 unlist_netdevice(dev);
9685 /* Shutdown queueing discipline. */
9688 /* Notify protocols, that we are about to destroy
9689 * this device. They should clean all the things.
9691 * Note that dev->reg_state stays at NETREG_REGISTERED.
9692 * This is wanted because this way 8021q and macvlan know
9693 * the device is just moving and can keep their slaves up.
9695 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
9698 new_nsid = peernet2id_alloc(dev_net(dev), net);
9699 /* If there is an ifindex conflict assign a new one */
9700 if (__dev_get_by_index(net, dev->ifindex))
9701 new_ifindex = dev_new_index(net);
9703 new_ifindex = dev->ifindex;
9705 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
9709 * Flush the unicast and multicast chains
9714 /* Send a netdev-removed uevent to the old namespace */
9715 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
9716 netdev_adjacent_del_links(dev);
9718 /* Actually switch the network namespace */
9719 dev_net_set(dev, net);
9720 dev->ifindex = new_ifindex;
9722 /* Send a netdev-add uevent to the new namespace */
9723 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
9724 netdev_adjacent_add_links(dev);
9726 /* Fixup kobjects */
9727 err = device_rename(&dev->dev, dev->name);
9730 /* Add the device back in the hashes */
9731 list_netdevice(dev);
9733 /* Notify protocols, that a new device appeared. */
9734 call_netdevice_notifiers(NETDEV_REGISTER, dev);
9737 * Prevent userspace races by waiting until the network
9738 * device is fully setup before sending notifications.
9740 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
9747 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
9749 static int dev_cpu_dead(unsigned int oldcpu)
9751 struct sk_buff **list_skb;
9752 struct sk_buff *skb;
9754 struct softnet_data *sd, *oldsd, *remsd = NULL;
9756 local_irq_disable();
9757 cpu = smp_processor_id();
9758 sd = &per_cpu(softnet_data, cpu);
9759 oldsd = &per_cpu(softnet_data, oldcpu);
9761 /* Find end of our completion_queue. */
9762 list_skb = &sd->completion_queue;
9764 list_skb = &(*list_skb)->next;
9765 /* Append completion queue from offline CPU. */
9766 *list_skb = oldsd->completion_queue;
9767 oldsd->completion_queue = NULL;
9769 /* Append output queue from offline CPU. */
9770 if (oldsd->output_queue) {
9771 *sd->output_queue_tailp = oldsd->output_queue;
9772 sd->output_queue_tailp = oldsd->output_queue_tailp;
9773 oldsd->output_queue = NULL;
9774 oldsd->output_queue_tailp = &oldsd->output_queue;
9776 /* Append NAPI poll list from offline CPU, with one exception :
9777 * process_backlog() must be called by cpu owning percpu backlog.
9778 * We properly handle process_queue & input_pkt_queue later.
9780 while (!list_empty(&oldsd->poll_list)) {
9781 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
9785 list_del_init(&napi->poll_list);
9786 if (napi->poll == process_backlog)
9789 ____napi_schedule(sd, napi);
9792 raise_softirq_irqoff(NET_TX_SOFTIRQ);
9796 remsd = oldsd->rps_ipi_list;
9797 oldsd->rps_ipi_list = NULL;
9799 /* send out pending IPI's on offline CPU */
9800 net_rps_send_ipi(remsd);
9802 /* Process offline CPU's input_pkt_queue */
9803 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
9805 input_queue_head_incr(oldsd);
9807 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
9809 input_queue_head_incr(oldsd);
9816 * netdev_increment_features - increment feature set by one
9817 * @all: current feature set
9818 * @one: new feature set
9819 * @mask: mask feature set
9821 * Computes a new feature set after adding a device with feature set
9822 * @one to the master device with current feature set @all. Will not
9823 * enable anything that is off in @mask. Returns the new feature set.
9825 netdev_features_t netdev_increment_features(netdev_features_t all,
9826 netdev_features_t one, netdev_features_t mask)
9828 if (mask & NETIF_F_HW_CSUM)
9829 mask |= NETIF_F_CSUM_MASK;
9830 mask |= NETIF_F_VLAN_CHALLENGED;
9832 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
9833 all &= one | ~NETIF_F_ALL_FOR_ALL;
9835 /* If one device supports hw checksumming, set for all. */
9836 if (all & NETIF_F_HW_CSUM)
9837 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
9841 EXPORT_SYMBOL(netdev_increment_features);
9843 static struct hlist_head * __net_init netdev_create_hash(void)
9846 struct hlist_head *hash;
9848 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
9850 for (i = 0; i < NETDEV_HASHENTRIES; i++)
9851 INIT_HLIST_HEAD(&hash[i]);
9856 /* Initialize per network namespace state */
9857 static int __net_init netdev_init(struct net *net)
9859 BUILD_BUG_ON(GRO_HASH_BUCKETS >
9860 8 * FIELD_SIZEOF(struct napi_struct, gro_bitmask));
9862 if (net != &init_net)
9863 INIT_LIST_HEAD(&net->dev_base_head);
9865 net->dev_name_head = netdev_create_hash();
9866 if (net->dev_name_head == NULL)
9869 net->dev_index_head = netdev_create_hash();
9870 if (net->dev_index_head == NULL)
9873 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
9878 kfree(net->dev_name_head);
9884 * netdev_drivername - network driver for the device
9885 * @dev: network device
9887 * Determine network driver for device.
9889 const char *netdev_drivername(const struct net_device *dev)
9891 const struct device_driver *driver;
9892 const struct device *parent;
9893 const char *empty = "";
9895 parent = dev->dev.parent;
9899 driver = parent->driver;
9900 if (driver && driver->name)
9901 return driver->name;
9905 static void __netdev_printk(const char *level, const struct net_device *dev,
9906 struct va_format *vaf)
9908 if (dev && dev->dev.parent) {
9909 dev_printk_emit(level[1] - '0',
9912 dev_driver_string(dev->dev.parent),
9913 dev_name(dev->dev.parent),
9914 netdev_name(dev), netdev_reg_state(dev),
9917 printk("%s%s%s: %pV",
9918 level, netdev_name(dev), netdev_reg_state(dev), vaf);
9920 printk("%s(NULL net_device): %pV", level, vaf);
9924 void netdev_printk(const char *level, const struct net_device *dev,
9925 const char *format, ...)
9927 struct va_format vaf;
9930 va_start(args, format);
9935 __netdev_printk(level, dev, &vaf);
9939 EXPORT_SYMBOL(netdev_printk);
9941 #define define_netdev_printk_level(func, level) \
9942 void func(const struct net_device *dev, const char *fmt, ...) \
9944 struct va_format vaf; \
9947 va_start(args, fmt); \
9952 __netdev_printk(level, dev, &vaf); \
9956 EXPORT_SYMBOL(func);
9958 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
9959 define_netdev_printk_level(netdev_alert, KERN_ALERT);
9960 define_netdev_printk_level(netdev_crit, KERN_CRIT);
9961 define_netdev_printk_level(netdev_err, KERN_ERR);
9962 define_netdev_printk_level(netdev_warn, KERN_WARNING);
9963 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
9964 define_netdev_printk_level(netdev_info, KERN_INFO);
9966 static void __net_exit netdev_exit(struct net *net)
9968 kfree(net->dev_name_head);
9969 kfree(net->dev_index_head);
9970 if (net != &init_net)
9971 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
9974 static struct pernet_operations __net_initdata netdev_net_ops = {
9975 .init = netdev_init,
9976 .exit = netdev_exit,
9979 static void __net_exit default_device_exit(struct net *net)
9981 struct net_device *dev, *aux;
9983 * Push all migratable network devices back to the
9984 * initial network namespace
9987 for_each_netdev_safe(net, dev, aux) {
9989 char fb_name[IFNAMSIZ];
9991 /* Ignore unmoveable devices (i.e. loopback) */
9992 if (dev->features & NETIF_F_NETNS_LOCAL)
9995 /* Leave virtual devices for the generic cleanup */
9996 if (dev->rtnl_link_ops)
9999 /* Push remaining network devices to init_net */
10000 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
10001 if (__dev_get_by_name(&init_net, fb_name))
10002 snprintf(fb_name, IFNAMSIZ, "dev%%d");
10003 err = dev_change_net_namespace(dev, &init_net, fb_name);
10005 pr_emerg("%s: failed to move %s to init_net: %d\n",
10006 __func__, dev->name, err);
10013 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
10015 /* Return with the rtnl_lock held when there are no network
10016 * devices unregistering in any network namespace in net_list.
10019 bool unregistering;
10020 DEFINE_WAIT_FUNC(wait, woken_wake_function);
10022 add_wait_queue(&netdev_unregistering_wq, &wait);
10024 unregistering = false;
10026 list_for_each_entry(net, net_list, exit_list) {
10027 if (net->dev_unreg_count > 0) {
10028 unregistering = true;
10032 if (!unregistering)
10036 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
10038 remove_wait_queue(&netdev_unregistering_wq, &wait);
10041 static void __net_exit default_device_exit_batch(struct list_head *net_list)
10043 /* At exit all network devices most be removed from a network
10044 * namespace. Do this in the reverse order of registration.
10045 * Do this across as many network namespaces as possible to
10046 * improve batching efficiency.
10048 struct net_device *dev;
10050 LIST_HEAD(dev_kill_list);
10052 /* To prevent network device cleanup code from dereferencing
10053 * loopback devices or network devices that have been freed
10054 * wait here for all pending unregistrations to complete,
10055 * before unregistring the loopback device and allowing the
10056 * network namespace be freed.
10058 * The netdev todo list containing all network devices
10059 * unregistrations that happen in default_device_exit_batch
10060 * will run in the rtnl_unlock() at the end of
10061 * default_device_exit_batch.
10063 rtnl_lock_unregistering(net_list);
10064 list_for_each_entry(net, net_list, exit_list) {
10065 for_each_netdev_reverse(net, dev) {
10066 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
10067 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
10069 unregister_netdevice_queue(dev, &dev_kill_list);
10072 unregister_netdevice_many(&dev_kill_list);
10076 static struct pernet_operations __net_initdata default_device_ops = {
10077 .exit = default_device_exit,
10078 .exit_batch = default_device_exit_batch,
10082 * Initialize the DEV module. At boot time this walks the device list and
10083 * unhooks any devices that fail to initialise (normally hardware not
10084 * present) and leaves us with a valid list of present and active devices.
10089 * This is called single threaded during boot, so no need
10090 * to take the rtnl semaphore.
10092 static int __init net_dev_init(void)
10094 int i, rc = -ENOMEM;
10096 BUG_ON(!dev_boot_phase);
10098 if (dev_proc_init())
10101 if (netdev_kobject_init())
10104 INIT_LIST_HEAD(&ptype_all);
10105 for (i = 0; i < PTYPE_HASH_SIZE; i++)
10106 INIT_LIST_HEAD(&ptype_base[i]);
10108 INIT_LIST_HEAD(&offload_base);
10110 if (register_pernet_subsys(&netdev_net_ops))
10114 * Initialise the packet receive queues.
10117 for_each_possible_cpu(i) {
10118 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
10119 struct softnet_data *sd = &per_cpu(softnet_data, i);
10121 INIT_WORK(flush, flush_backlog);
10123 skb_queue_head_init(&sd->input_pkt_queue);
10124 skb_queue_head_init(&sd->process_queue);
10125 #ifdef CONFIG_XFRM_OFFLOAD
10126 skb_queue_head_init(&sd->xfrm_backlog);
10128 INIT_LIST_HEAD(&sd->poll_list);
10129 sd->output_queue_tailp = &sd->output_queue;
10131 sd->csd.func = rps_trigger_softirq;
10136 init_gro_hash(&sd->backlog);
10137 sd->backlog.poll = process_backlog;
10138 sd->backlog.weight = weight_p;
10141 dev_boot_phase = 0;
10143 /* The loopback device is special if any other network devices
10144 * is present in a network namespace the loopback device must
10145 * be present. Since we now dynamically allocate and free the
10146 * loopback device ensure this invariant is maintained by
10147 * keeping the loopback device as the first device on the
10148 * list of network devices. Ensuring the loopback devices
10149 * is the first device that appears and the last network device
10152 if (register_pernet_device(&loopback_net_ops))
10155 if (register_pernet_device(&default_device_ops))
10158 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
10159 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
10161 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
10162 NULL, dev_cpu_dead);
10169 subsys_initcall(net_dev_init);