1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * NET3 Protocol independent device support routines.
5 * Derived from the non IP parts of dev.c 1.0.19
7 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
8 * Mark Evans, <evansmp@uhura.aston.ac.uk>
11 * Florian la Roche <rzsfl@rz.uni-sb.de>
12 * Alan Cox <gw4pts@gw4pts.ampr.org>
13 * David Hinds <dahinds@users.sourceforge.net>
14 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
15 * Adam Sulmicki <adam@cfar.umd.edu>
16 * Pekka Riikonen <priikone@poesidon.pspt.fi>
19 * D.J. Barrow : Fixed bug where dev->refcnt gets set
20 * to 2 if register_netdev gets called
21 * before net_dev_init & also removed a
22 * few lines of code in the process.
23 * Alan Cox : device private ioctl copies fields back.
24 * Alan Cox : Transmit queue code does relevant
25 * stunts to keep the queue safe.
26 * Alan Cox : Fixed double lock.
27 * Alan Cox : Fixed promisc NULL pointer trap
28 * ???????? : Support the full private ioctl range
29 * Alan Cox : Moved ioctl permission check into
31 * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
32 * Alan Cox : 100 backlog just doesn't cut it when
33 * you start doing multicast video 8)
34 * Alan Cox : Rewrote net_bh and list manager.
35 * Alan Cox : Fix ETH_P_ALL echoback lengths.
36 * Alan Cox : Took out transmit every packet pass
37 * Saved a few bytes in the ioctl handler
38 * Alan Cox : Network driver sets packet type before
39 * calling netif_rx. Saves a function
41 * Alan Cox : Hashed net_bh()
42 * Richard Kooijman: Timestamp fixes.
43 * Alan Cox : Wrong field in SIOCGIFDSTADDR
44 * Alan Cox : Device lock protection.
45 * Alan Cox : Fixed nasty side effect of device close
47 * Rudi Cilibrasi : Pass the right thing to
49 * Dave Miller : 32bit quantity for the device lock to
50 * make it work out on a Sparc.
51 * Bjorn Ekwall : Added KERNELD hack.
52 * Alan Cox : Cleaned up the backlog initialise.
53 * Craig Metz : SIOCGIFCONF fix if space for under
55 * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
56 * is no device open function.
57 * Andi Kleen : Fix error reporting for SIOCGIFCONF
58 * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
59 * Cyrus Durgin : Cleaned for KMOD
60 * Adam Sulmicki : Bug Fix : Network Device Unload
61 * A network device unload needs to purge
63 * Paul Rusty Russell : SIOCSIFNAME
64 * Pekka Riikonen : Netdev boot-time settings code
65 * Andrew Morton : Make unregister_netdevice wait
66 * indefinitely on dev->refcnt
67 * J Hadi Salim : - Backlog queue sampling
68 * - netif_rx() feedback
71 #include <linux/uaccess.h>
72 #include <linux/bitops.h>
73 #include <linux/capability.h>
74 #include <linux/cpu.h>
75 #include <linux/types.h>
76 #include <linux/kernel.h>
77 #include <linux/hash.h>
78 #include <linux/slab.h>
79 #include <linux/sched.h>
80 #include <linux/sched/mm.h>
81 #include <linux/mutex.h>
82 #include <linux/rwsem.h>
83 #include <linux/string.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/errno.h>
88 #include <linux/interrupt.h>
89 #include <linux/if_ether.h>
90 #include <linux/netdevice.h>
91 #include <linux/etherdevice.h>
92 #include <linux/ethtool.h>
93 #include <linux/skbuff.h>
94 #include <linux/bpf.h>
95 #include <linux/bpf_trace.h>
96 #include <net/net_namespace.h>
98 #include <net/busy_poll.h>
99 #include <linux/rtnetlink.h>
100 #include <linux/stat.h>
103 #include <net/dst_metadata.h>
104 #include <net/pkt_sched.h>
105 #include <net/pkt_cls.h>
106 #include <net/checksum.h>
107 #include <net/xfrm.h>
108 #include <linux/highmem.h>
109 #include <linux/init.h>
110 #include <linux/module.h>
111 #include <linux/netpoll.h>
112 #include <linux/rcupdate.h>
113 #include <linux/delay.h>
114 #include <net/iw_handler.h>
115 #include <asm/current.h>
116 #include <linux/audit.h>
117 #include <linux/dmaengine.h>
118 #include <linux/err.h>
119 #include <linux/ctype.h>
120 #include <linux/if_arp.h>
121 #include <linux/if_vlan.h>
122 #include <linux/ip.h>
124 #include <net/mpls.h>
125 #include <linux/ipv6.h>
126 #include <linux/in.h>
127 #include <linux/jhash.h>
128 #include <linux/random.h>
129 #include <trace/events/napi.h>
130 #include <trace/events/net.h>
131 #include <trace/events/skb.h>
132 #include <linux/inetdevice.h>
133 #include <linux/cpu_rmap.h>
134 #include <linux/static_key.h>
135 #include <linux/hashtable.h>
136 #include <linux/vmalloc.h>
137 #include <linux/if_macvlan.h>
138 #include <linux/errqueue.h>
139 #include <linux/hrtimer.h>
140 #include <linux/netfilter_ingress.h>
141 #include <linux/crash_dump.h>
142 #include <linux/sctp.h>
143 #include <net/udp_tunnel.h>
144 #include <linux/net_namespace.h>
145 #include <linux/indirect_call_wrapper.h>
146 #include <net/devlink.h>
147 #include <linux/pm_runtime.h>
148 #include <linux/prandom.h>
150 #include "net-sysfs.h"
152 #define MAX_GRO_SKBS 8
154 /* This should be increased if a protocol with a bigger head is added. */
155 #define GRO_MAX_HEAD (MAX_HEADER + 128)
157 static DEFINE_SPINLOCK(ptype_lock);
158 static DEFINE_SPINLOCK(offload_lock);
159 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
160 struct list_head ptype_all __read_mostly; /* Taps */
161 static struct list_head offload_base __read_mostly;
163 static int netif_rx_internal(struct sk_buff *skb);
164 static int call_netdevice_notifiers_info(unsigned long val,
165 struct netdev_notifier_info *info);
166 static int call_netdevice_notifiers_extack(unsigned long val,
167 struct net_device *dev,
168 struct netlink_ext_ack *extack);
169 static struct napi_struct *napi_by_id(unsigned int napi_id);
172 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
175 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
177 * Writers must hold the rtnl semaphore while they loop through the
178 * dev_base_head list, and hold dev_base_lock for writing when they do the
179 * actual updates. This allows pure readers to access the list even
180 * while a writer is preparing to update it.
182 * To put it another way, dev_base_lock is held for writing only to
183 * protect against pure readers; the rtnl semaphore provides the
184 * protection against other writers.
186 * See, for example usages, register_netdevice() and
187 * unregister_netdevice(), which must be called with the rtnl
190 DEFINE_RWLOCK(dev_base_lock);
191 EXPORT_SYMBOL(dev_base_lock);
193 static DEFINE_MUTEX(ifalias_mutex);
195 /* protects napi_hash addition/deletion and napi_gen_id */
196 static DEFINE_SPINLOCK(napi_hash_lock);
198 static unsigned int napi_gen_id = NR_CPUS;
199 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
201 static DECLARE_RWSEM(devnet_rename_sem);
203 static inline void dev_base_seq_inc(struct net *net)
205 while (++net->dev_base_seq == 0)
209 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
211 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
213 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
216 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
218 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
221 static inline void rps_lock(struct softnet_data *sd)
224 spin_lock(&sd->input_pkt_queue.lock);
228 static inline void rps_unlock(struct softnet_data *sd)
231 spin_unlock(&sd->input_pkt_queue.lock);
235 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
238 struct netdev_name_node *name_node;
240 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
243 INIT_HLIST_NODE(&name_node->hlist);
244 name_node->dev = dev;
245 name_node->name = name;
249 static struct netdev_name_node *
250 netdev_name_node_head_alloc(struct net_device *dev)
252 struct netdev_name_node *name_node;
254 name_node = netdev_name_node_alloc(dev, dev->name);
257 INIT_LIST_HEAD(&name_node->list);
261 static void netdev_name_node_free(struct netdev_name_node *name_node)
266 static void netdev_name_node_add(struct net *net,
267 struct netdev_name_node *name_node)
269 hlist_add_head_rcu(&name_node->hlist,
270 dev_name_hash(net, name_node->name));
273 static void netdev_name_node_del(struct netdev_name_node *name_node)
275 hlist_del_rcu(&name_node->hlist);
278 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
281 struct hlist_head *head = dev_name_hash(net, name);
282 struct netdev_name_node *name_node;
284 hlist_for_each_entry(name_node, head, hlist)
285 if (!strcmp(name_node->name, name))
290 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
293 struct hlist_head *head = dev_name_hash(net, name);
294 struct netdev_name_node *name_node;
296 hlist_for_each_entry_rcu(name_node, head, hlist)
297 if (!strcmp(name_node->name, name))
302 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
304 struct netdev_name_node *name_node;
305 struct net *net = dev_net(dev);
307 name_node = netdev_name_node_lookup(net, name);
310 name_node = netdev_name_node_alloc(dev, name);
313 netdev_name_node_add(net, name_node);
314 /* The node that holds dev->name acts as a head of per-device list. */
315 list_add_tail(&name_node->list, &dev->name_node->list);
319 EXPORT_SYMBOL(netdev_name_node_alt_create);
321 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
323 list_del(&name_node->list);
324 netdev_name_node_del(name_node);
325 kfree(name_node->name);
326 netdev_name_node_free(name_node);
329 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
331 struct netdev_name_node *name_node;
332 struct net *net = dev_net(dev);
334 name_node = netdev_name_node_lookup(net, name);
337 /* lookup might have found our primary name or a name belonging
340 if (name_node == dev->name_node || name_node->dev != dev)
343 __netdev_name_node_alt_destroy(name_node);
347 EXPORT_SYMBOL(netdev_name_node_alt_destroy);
349 static void netdev_name_node_alt_flush(struct net_device *dev)
351 struct netdev_name_node *name_node, *tmp;
353 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
354 __netdev_name_node_alt_destroy(name_node);
357 /* Device list insertion */
358 static void list_netdevice(struct net_device *dev)
360 struct net *net = dev_net(dev);
364 write_lock_bh(&dev_base_lock);
365 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
366 netdev_name_node_add(net, dev->name_node);
367 hlist_add_head_rcu(&dev->index_hlist,
368 dev_index_hash(net, dev->ifindex));
369 write_unlock_bh(&dev_base_lock);
371 dev_base_seq_inc(net);
374 /* Device list removal
375 * caller must respect a RCU grace period before freeing/reusing dev
377 static void unlist_netdevice(struct net_device *dev)
381 /* Unlink dev from the device chain */
382 write_lock_bh(&dev_base_lock);
383 list_del_rcu(&dev->dev_list);
384 netdev_name_node_del(dev->name_node);
385 hlist_del_rcu(&dev->index_hlist);
386 write_unlock_bh(&dev_base_lock);
388 dev_base_seq_inc(dev_net(dev));
395 static RAW_NOTIFIER_HEAD(netdev_chain);
398 * Device drivers call our routines to queue packets here. We empty the
399 * queue in the local softnet handler.
402 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
403 EXPORT_PER_CPU_SYMBOL(softnet_data);
405 #ifdef CONFIG_LOCKDEP
407 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
408 * according to dev->type
410 static const unsigned short netdev_lock_type[] = {
411 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
412 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
413 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
414 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
415 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
416 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
417 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
418 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
419 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
420 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
421 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
422 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
423 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
424 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
425 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
427 static const char *const netdev_lock_name[] = {
428 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
429 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
430 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
431 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
432 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
433 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
434 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
435 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
436 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
437 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
438 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
439 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
440 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
441 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
442 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
444 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
445 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
447 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
451 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
452 if (netdev_lock_type[i] == dev_type)
454 /* the last key is used by default */
455 return ARRAY_SIZE(netdev_lock_type) - 1;
458 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
459 unsigned short dev_type)
463 i = netdev_lock_pos(dev_type);
464 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
465 netdev_lock_name[i]);
468 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
472 i = netdev_lock_pos(dev->type);
473 lockdep_set_class_and_name(&dev->addr_list_lock,
474 &netdev_addr_lock_key[i],
475 netdev_lock_name[i]);
478 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
479 unsigned short dev_type)
483 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
488 /*******************************************************************************
490 * Protocol management and registration routines
492 *******************************************************************************/
496 * Add a protocol ID to the list. Now that the input handler is
497 * smarter we can dispense with all the messy stuff that used to be
500 * BEWARE!!! Protocol handlers, mangling input packets,
501 * MUST BE last in hash buckets and checking protocol handlers
502 * MUST start from promiscuous ptype_all chain in net_bh.
503 * It is true now, do not change it.
504 * Explanation follows: if protocol handler, mangling packet, will
505 * be the first on list, it is not able to sense, that packet
506 * is cloned and should be copied-on-write, so that it will
507 * change it and subsequent readers will get broken packet.
511 static inline struct list_head *ptype_head(const struct packet_type *pt)
513 if (pt->type == htons(ETH_P_ALL))
514 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
516 return pt->dev ? &pt->dev->ptype_specific :
517 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
521 * dev_add_pack - add packet handler
522 * @pt: packet type declaration
524 * Add a protocol handler to the networking stack. The passed &packet_type
525 * is linked into kernel lists and may not be freed until it has been
526 * removed from the kernel lists.
528 * This call does not sleep therefore it can not
529 * guarantee all CPU's that are in middle of receiving packets
530 * will see the new packet type (until the next received packet).
533 void dev_add_pack(struct packet_type *pt)
535 struct list_head *head = ptype_head(pt);
537 spin_lock(&ptype_lock);
538 list_add_rcu(&pt->list, head);
539 spin_unlock(&ptype_lock);
541 EXPORT_SYMBOL(dev_add_pack);
544 * __dev_remove_pack - remove packet handler
545 * @pt: packet type declaration
547 * Remove a protocol handler that was previously added to the kernel
548 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
549 * from the kernel lists and can be freed or reused once this function
552 * The packet type might still be in use by receivers
553 * and must not be freed until after all the CPU's have gone
554 * through a quiescent state.
556 void __dev_remove_pack(struct packet_type *pt)
558 struct list_head *head = ptype_head(pt);
559 struct packet_type *pt1;
561 spin_lock(&ptype_lock);
563 list_for_each_entry(pt1, head, list) {
565 list_del_rcu(&pt->list);
570 pr_warn("dev_remove_pack: %p not found\n", pt);
572 spin_unlock(&ptype_lock);
574 EXPORT_SYMBOL(__dev_remove_pack);
577 * dev_remove_pack - remove packet handler
578 * @pt: packet type declaration
580 * Remove a protocol handler that was previously added to the kernel
581 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
582 * from the kernel lists and can be freed or reused once this function
585 * This call sleeps to guarantee that no CPU is looking at the packet
588 void dev_remove_pack(struct packet_type *pt)
590 __dev_remove_pack(pt);
594 EXPORT_SYMBOL(dev_remove_pack);
598 * dev_add_offload - register offload handlers
599 * @po: protocol offload declaration
601 * Add protocol offload handlers to the networking stack. The passed
602 * &proto_offload is linked into kernel lists and may not be freed until
603 * it has been removed from the kernel lists.
605 * This call does not sleep therefore it can not
606 * guarantee all CPU's that are in middle of receiving packets
607 * will see the new offload handlers (until the next received packet).
609 void dev_add_offload(struct packet_offload *po)
611 struct packet_offload *elem;
613 spin_lock(&offload_lock);
614 list_for_each_entry(elem, &offload_base, list) {
615 if (po->priority < elem->priority)
618 list_add_rcu(&po->list, elem->list.prev);
619 spin_unlock(&offload_lock);
621 EXPORT_SYMBOL(dev_add_offload);
624 * __dev_remove_offload - remove offload handler
625 * @po: packet offload declaration
627 * Remove a protocol offload handler that was previously added to the
628 * kernel offload handlers by dev_add_offload(). The passed &offload_type
629 * is removed from the kernel lists and can be freed or reused once this
632 * The packet type might still be in use by receivers
633 * and must not be freed until after all the CPU's have gone
634 * through a quiescent state.
636 static void __dev_remove_offload(struct packet_offload *po)
638 struct list_head *head = &offload_base;
639 struct packet_offload *po1;
641 spin_lock(&offload_lock);
643 list_for_each_entry(po1, head, list) {
645 list_del_rcu(&po->list);
650 pr_warn("dev_remove_offload: %p not found\n", po);
652 spin_unlock(&offload_lock);
656 * dev_remove_offload - remove packet offload handler
657 * @po: packet offload declaration
659 * Remove a packet offload handler that was previously added to the kernel
660 * offload handlers by dev_add_offload(). The passed &offload_type is
661 * removed from the kernel lists and can be freed or reused once this
664 * This call sleeps to guarantee that no CPU is looking at the packet
667 void dev_remove_offload(struct packet_offload *po)
669 __dev_remove_offload(po);
673 EXPORT_SYMBOL(dev_remove_offload);
675 /******************************************************************************
677 * Device Boot-time Settings Routines
679 ******************************************************************************/
681 /* Boot time configuration table */
682 static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
685 * netdev_boot_setup_add - add new setup entry
686 * @name: name of the device
687 * @map: configured settings for the device
689 * Adds new setup entry to the dev_boot_setup list. The function
690 * returns 0 on error and 1 on success. This is a generic routine to
693 static int netdev_boot_setup_add(char *name, struct ifmap *map)
695 struct netdev_boot_setup *s;
699 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
700 if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
701 memset(s[i].name, 0, sizeof(s[i].name));
702 strlcpy(s[i].name, name, IFNAMSIZ);
703 memcpy(&s[i].map, map, sizeof(s[i].map));
708 return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
712 * netdev_boot_setup_check - check boot time settings
713 * @dev: the netdevice
715 * Check boot time settings for the device.
716 * The found settings are set for the device to be used
717 * later in the device probing.
718 * Returns 0 if no settings found, 1 if they are.
720 int netdev_boot_setup_check(struct net_device *dev)
722 struct netdev_boot_setup *s = dev_boot_setup;
725 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
726 if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
727 !strcmp(dev->name, s[i].name)) {
728 dev->irq = s[i].map.irq;
729 dev->base_addr = s[i].map.base_addr;
730 dev->mem_start = s[i].map.mem_start;
731 dev->mem_end = s[i].map.mem_end;
737 EXPORT_SYMBOL(netdev_boot_setup_check);
741 * netdev_boot_base - get address from boot time settings
742 * @prefix: prefix for network device
743 * @unit: id for network device
745 * Check boot time settings for the base address of device.
746 * The found settings are set for the device to be used
747 * later in the device probing.
748 * Returns 0 if no settings found.
750 unsigned long netdev_boot_base(const char *prefix, int unit)
752 const struct netdev_boot_setup *s = dev_boot_setup;
756 sprintf(name, "%s%d", prefix, unit);
759 * If device already registered then return base of 1
760 * to indicate not to probe for this interface
762 if (__dev_get_by_name(&init_net, name))
765 for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
766 if (!strcmp(name, s[i].name))
767 return s[i].map.base_addr;
772 * Saves at boot time configured settings for any netdevice.
774 int __init netdev_boot_setup(char *str)
779 str = get_options(str, ARRAY_SIZE(ints), ints);
784 memset(&map, 0, sizeof(map));
788 map.base_addr = ints[2];
790 map.mem_start = ints[3];
792 map.mem_end = ints[4];
794 /* Add new entry to the list */
795 return netdev_boot_setup_add(str, &map);
798 __setup("netdev=", netdev_boot_setup);
800 /*******************************************************************************
802 * Device Interface Subroutines
804 *******************************************************************************/
807 * dev_get_iflink - get 'iflink' value of a interface
808 * @dev: targeted interface
810 * Indicates the ifindex the interface is linked to.
811 * Physical interfaces have the same 'ifindex' and 'iflink' values.
814 int dev_get_iflink(const struct net_device *dev)
816 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
817 return dev->netdev_ops->ndo_get_iflink(dev);
821 EXPORT_SYMBOL(dev_get_iflink);
824 * dev_fill_metadata_dst - Retrieve tunnel egress information.
825 * @dev: targeted interface
828 * For better visibility of tunnel traffic OVS needs to retrieve
829 * egress tunnel information for a packet. Following API allows
830 * user to get this info.
832 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
834 struct ip_tunnel_info *info;
836 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
839 info = skb_tunnel_info_unclone(skb);
842 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
845 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
847 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
850 * __dev_get_by_name - find a device by its name
851 * @net: the applicable net namespace
852 * @name: name to find
854 * Find an interface by name. Must be called under RTNL semaphore
855 * or @dev_base_lock. If the name is found a pointer to the device
856 * is returned. If the name is not found then %NULL is returned. The
857 * reference counters are not incremented so the caller must be
858 * careful with locks.
861 struct net_device *__dev_get_by_name(struct net *net, const char *name)
863 struct netdev_name_node *node_name;
865 node_name = netdev_name_node_lookup(net, name);
866 return node_name ? node_name->dev : NULL;
868 EXPORT_SYMBOL(__dev_get_by_name);
871 * dev_get_by_name_rcu - find a device by its name
872 * @net: the applicable net namespace
873 * @name: name to find
875 * Find an interface by name.
876 * If the name is found a pointer to the device is returned.
877 * If the name is not found then %NULL is returned.
878 * The reference counters are not incremented so the caller must be
879 * careful with locks. The caller must hold RCU lock.
882 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
884 struct netdev_name_node *node_name;
886 node_name = netdev_name_node_lookup_rcu(net, name);
887 return node_name ? node_name->dev : NULL;
889 EXPORT_SYMBOL(dev_get_by_name_rcu);
892 * dev_get_by_name - find a device by its name
893 * @net: the applicable net namespace
894 * @name: name to find
896 * Find an interface by name. This can be called from any
897 * context and does its own locking. The returned handle has
898 * the usage count incremented and the caller must use dev_put() to
899 * release it when it is no longer needed. %NULL is returned if no
900 * matching device is found.
903 struct net_device *dev_get_by_name(struct net *net, const char *name)
905 struct net_device *dev;
908 dev = dev_get_by_name_rcu(net, name);
914 EXPORT_SYMBOL(dev_get_by_name);
917 * __dev_get_by_index - find a device by its ifindex
918 * @net: the applicable net namespace
919 * @ifindex: index of device
921 * Search for an interface by index. Returns %NULL if the device
922 * is not found or a pointer to the device. The device has not
923 * had its reference counter increased so the caller must be careful
924 * about locking. The caller must hold either the RTNL semaphore
928 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
930 struct net_device *dev;
931 struct hlist_head *head = dev_index_hash(net, ifindex);
933 hlist_for_each_entry(dev, head, index_hlist)
934 if (dev->ifindex == ifindex)
939 EXPORT_SYMBOL(__dev_get_by_index);
942 * dev_get_by_index_rcu - find a device by its ifindex
943 * @net: the applicable net namespace
944 * @ifindex: index of device
946 * Search for an interface by index. Returns %NULL if the device
947 * is not found or a pointer to the device. The device has not
948 * had its reference counter increased so the caller must be careful
949 * about locking. The caller must hold RCU lock.
952 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
954 struct net_device *dev;
955 struct hlist_head *head = dev_index_hash(net, ifindex);
957 hlist_for_each_entry_rcu(dev, head, index_hlist)
958 if (dev->ifindex == ifindex)
963 EXPORT_SYMBOL(dev_get_by_index_rcu);
967 * dev_get_by_index - find a device by its ifindex
968 * @net: the applicable net namespace
969 * @ifindex: index of device
971 * Search for an interface by index. Returns NULL if the device
972 * is not found or a pointer to the device. The device returned has
973 * had a reference added and the pointer is safe until the user calls
974 * dev_put to indicate they have finished with it.
977 struct net_device *dev_get_by_index(struct net *net, int ifindex)
979 struct net_device *dev;
982 dev = dev_get_by_index_rcu(net, ifindex);
988 EXPORT_SYMBOL(dev_get_by_index);
991 * dev_get_by_napi_id - find a device by napi_id
992 * @napi_id: ID of the NAPI struct
994 * Search for an interface by NAPI ID. Returns %NULL if the device
995 * is not found or a pointer to the device. The device has not had
996 * its reference counter increased so the caller must be careful
997 * about locking. The caller must hold RCU lock.
1000 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
1002 struct napi_struct *napi;
1004 WARN_ON_ONCE(!rcu_read_lock_held());
1006 if (napi_id < MIN_NAPI_ID)
1009 napi = napi_by_id(napi_id);
1011 return napi ? napi->dev : NULL;
1013 EXPORT_SYMBOL(dev_get_by_napi_id);
1016 * netdev_get_name - get a netdevice name, knowing its ifindex.
1017 * @net: network namespace
1018 * @name: a pointer to the buffer where the name will be stored.
1019 * @ifindex: the ifindex of the interface to get the name from.
1021 int netdev_get_name(struct net *net, char *name, int ifindex)
1023 struct net_device *dev;
1026 down_read(&devnet_rename_sem);
1029 dev = dev_get_by_index_rcu(net, ifindex);
1035 strcpy(name, dev->name);
1040 up_read(&devnet_rename_sem);
1045 * dev_getbyhwaddr_rcu - find a device by its hardware address
1046 * @net: the applicable net namespace
1047 * @type: media type of device
1048 * @ha: hardware address
1050 * Search for an interface by MAC address. Returns NULL if the device
1051 * is not found or a pointer to the device.
1052 * The caller must hold RCU or RTNL.
1053 * The returned device has not had its ref count increased
1054 * and the caller must therefore be careful about locking
1058 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
1061 struct net_device *dev;
1063 for_each_netdev_rcu(net, dev)
1064 if (dev->type == type &&
1065 !memcmp(dev->dev_addr, ha, dev->addr_len))
1070 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
1072 struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
1074 struct net_device *dev;
1077 for_each_netdev(net, dev)
1078 if (dev->type == type)
1083 EXPORT_SYMBOL(__dev_getfirstbyhwtype);
1085 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1087 struct net_device *dev, *ret = NULL;
1090 for_each_netdev_rcu(net, dev)
1091 if (dev->type == type) {
1099 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1102 * __dev_get_by_flags - find any device with given flags
1103 * @net: the applicable net namespace
1104 * @if_flags: IFF_* values
1105 * @mask: bitmask of bits in if_flags to check
1107 * Search for any interface with the given flags. Returns NULL if a device
1108 * is not found or a pointer to the device. Must be called inside
1109 * rtnl_lock(), and result refcount is unchanged.
1112 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1113 unsigned short mask)
1115 struct net_device *dev, *ret;
1120 for_each_netdev(net, dev) {
1121 if (((dev->flags ^ if_flags) & mask) == 0) {
1128 EXPORT_SYMBOL(__dev_get_by_flags);
1131 * dev_valid_name - check if name is okay for network device
1132 * @name: name string
1134 * Network device names need to be valid file names to
1135 * allow sysfs to work. We also disallow any kind of
1138 bool dev_valid_name(const char *name)
1142 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1144 if (!strcmp(name, ".") || !strcmp(name, ".."))
1148 if (*name == '/' || *name == ':' || isspace(*name))
1154 EXPORT_SYMBOL(dev_valid_name);
1157 * __dev_alloc_name - allocate a name for a device
1158 * @net: network namespace to allocate the device name in
1159 * @name: name format string
1160 * @buf: scratch buffer and result name string
1162 * Passed a format string - eg "lt%d" it will try and find a suitable
1163 * id. It scans list of devices to build up a free map, then chooses
1164 * the first empty slot. The caller must hold the dev_base or rtnl lock
1165 * while allocating the name and adding the device in order to avoid
1167 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1168 * Returns the number of the unit assigned or a negative errno code.
1171 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1175 const int max_netdevices = 8*PAGE_SIZE;
1176 unsigned long *inuse;
1177 struct net_device *d;
1179 if (!dev_valid_name(name))
1182 p = strchr(name, '%');
1185 * Verify the string as this thing may have come from
1186 * the user. There must be either one "%d" and no other "%"
1189 if (p[1] != 'd' || strchr(p + 2, '%'))
1192 /* Use one page as a bit array of possible slots */
1193 inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
1197 for_each_netdev(net, d) {
1198 struct netdev_name_node *name_node;
1199 list_for_each_entry(name_node, &d->name_node->list, list) {
1200 if (!sscanf(name_node->name, name, &i))
1202 if (i < 0 || i >= max_netdevices)
1205 /* avoid cases where sscanf is not exact inverse of printf */
1206 snprintf(buf, IFNAMSIZ, name, i);
1207 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1210 if (!sscanf(d->name, name, &i))
1212 if (i < 0 || i >= max_netdevices)
1215 /* avoid cases where sscanf is not exact inverse of printf */
1216 snprintf(buf, IFNAMSIZ, name, i);
1217 if (!strncmp(buf, d->name, IFNAMSIZ))
1221 i = find_first_zero_bit(inuse, max_netdevices);
1222 free_page((unsigned long) inuse);
1225 snprintf(buf, IFNAMSIZ, name, i);
1226 if (!__dev_get_by_name(net, buf))
1229 /* It is possible to run out of possible slots
1230 * when the name is long and there isn't enough space left
1231 * for the digits, or if all bits are used.
1236 static int dev_alloc_name_ns(struct net *net,
1237 struct net_device *dev,
1244 ret = __dev_alloc_name(net, name, buf);
1246 strlcpy(dev->name, buf, IFNAMSIZ);
1251 * dev_alloc_name - allocate a name for a device
1253 * @name: name format string
1255 * Passed a format string - eg "lt%d" it will try and find a suitable
1256 * id. It scans list of devices to build up a free map, then chooses
1257 * the first empty slot. The caller must hold the dev_base or rtnl lock
1258 * while allocating the name and adding the device in order to avoid
1260 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1261 * Returns the number of the unit assigned or a negative errno code.
1264 int dev_alloc_name(struct net_device *dev, const char *name)
1266 return dev_alloc_name_ns(dev_net(dev), dev, name);
1268 EXPORT_SYMBOL(dev_alloc_name);
1270 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1275 if (!dev_valid_name(name))
1278 if (strchr(name, '%'))
1279 return dev_alloc_name_ns(net, dev, name);
1280 else if (__dev_get_by_name(net, name))
1282 else if (dev->name != name)
1283 strlcpy(dev->name, name, IFNAMSIZ);
1289 * dev_change_name - change name of a device
1291 * @newname: name (or format string) must be at least IFNAMSIZ
1293 * Change name of a device, can pass format strings "eth%d".
1296 int dev_change_name(struct net_device *dev, const char *newname)
1298 unsigned char old_assign_type;
1299 char oldname[IFNAMSIZ];
1305 BUG_ON(!dev_net(dev));
1309 /* Some auto-enslaved devices e.g. failover slaves are
1310 * special, as userspace might rename the device after
1311 * the interface had been brought up and running since
1312 * the point kernel initiated auto-enslavement. Allow
1313 * live name change even when these slave devices are
1316 * Typically, users of these auto-enslaving devices
1317 * don't actually care about slave name change, as
1318 * they are supposed to operate on master interface
1321 if (dev->flags & IFF_UP &&
1322 likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
1325 down_write(&devnet_rename_sem);
1327 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1328 up_write(&devnet_rename_sem);
1332 memcpy(oldname, dev->name, IFNAMSIZ);
1334 err = dev_get_valid_name(net, dev, newname);
1336 up_write(&devnet_rename_sem);
1340 if (oldname[0] && !strchr(oldname, '%'))
1341 netdev_info(dev, "renamed from %s\n", oldname);
1343 old_assign_type = dev->name_assign_type;
1344 dev->name_assign_type = NET_NAME_RENAMED;
1347 ret = device_rename(&dev->dev, dev->name);
1349 memcpy(dev->name, oldname, IFNAMSIZ);
1350 dev->name_assign_type = old_assign_type;
1351 up_write(&devnet_rename_sem);
1355 up_write(&devnet_rename_sem);
1357 netdev_adjacent_rename_links(dev, oldname);
1359 write_lock_bh(&dev_base_lock);
1360 netdev_name_node_del(dev->name_node);
1361 write_unlock_bh(&dev_base_lock);
1365 write_lock_bh(&dev_base_lock);
1366 netdev_name_node_add(net, dev->name_node);
1367 write_unlock_bh(&dev_base_lock);
1369 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1370 ret = notifier_to_errno(ret);
1373 /* err >= 0 after dev_alloc_name() or stores the first errno */
1376 down_write(&devnet_rename_sem);
1377 memcpy(dev->name, oldname, IFNAMSIZ);
1378 memcpy(oldname, newname, IFNAMSIZ);
1379 dev->name_assign_type = old_assign_type;
1380 old_assign_type = NET_NAME_RENAMED;
1383 pr_err("%s: name change rollback failed: %d\n",
1392 * dev_set_alias - change ifalias of a device
1394 * @alias: name up to IFALIASZ
1395 * @len: limit of bytes to copy from info
1397 * Set ifalias for a device,
1399 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1401 struct dev_ifalias *new_alias = NULL;
1403 if (len >= IFALIASZ)
1407 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1411 memcpy(new_alias->ifalias, alias, len);
1412 new_alias->ifalias[len] = 0;
1415 mutex_lock(&ifalias_mutex);
1416 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1417 mutex_is_locked(&ifalias_mutex));
1418 mutex_unlock(&ifalias_mutex);
1421 kfree_rcu(new_alias, rcuhead);
1425 EXPORT_SYMBOL(dev_set_alias);
1428 * dev_get_alias - get ifalias of a device
1430 * @name: buffer to store name of ifalias
1431 * @len: size of buffer
1433 * get ifalias for a device. Caller must make sure dev cannot go
1434 * away, e.g. rcu read lock or own a reference count to device.
1436 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1438 const struct dev_ifalias *alias;
1442 alias = rcu_dereference(dev->ifalias);
1444 ret = snprintf(name, len, "%s", alias->ifalias);
1451 * netdev_features_change - device changes features
1452 * @dev: device to cause notification
1454 * Called to indicate a device has changed features.
1456 void netdev_features_change(struct net_device *dev)
1458 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1460 EXPORT_SYMBOL(netdev_features_change);
1463 * netdev_state_change - device changes state
1464 * @dev: device to cause notification
1466 * Called to indicate a device has changed state. This function calls
1467 * the notifier chains for netdev_chain and sends a NEWLINK message
1468 * to the routing socket.
1470 void netdev_state_change(struct net_device *dev)
1472 if (dev->flags & IFF_UP) {
1473 struct netdev_notifier_change_info change_info = {
1477 call_netdevice_notifiers_info(NETDEV_CHANGE,
1479 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
1482 EXPORT_SYMBOL(netdev_state_change);
1485 * netdev_notify_peers - notify network peers about existence of @dev
1486 * @dev: network device
1488 * Generate traffic such that interested network peers are aware of
1489 * @dev, such as by generating a gratuitous ARP. This may be used when
1490 * a device wants to inform the rest of the network about some sort of
1491 * reconfiguration such as a failover event or virtual machine
1494 void netdev_notify_peers(struct net_device *dev)
1497 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1498 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1501 EXPORT_SYMBOL(netdev_notify_peers);
1503 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1505 const struct net_device_ops *ops = dev->netdev_ops;
1510 if (!netif_device_present(dev)) {
1511 /* may be detached because parent is runtime-suspended */
1512 if (dev->dev.parent)
1513 pm_runtime_resume(dev->dev.parent);
1514 if (!netif_device_present(dev))
1518 /* Block netpoll from trying to do any rx path servicing.
1519 * If we don't do this there is a chance ndo_poll_controller
1520 * or ndo_poll may be running while we open the device
1522 netpoll_poll_disable(dev);
1524 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1525 ret = notifier_to_errno(ret);
1529 set_bit(__LINK_STATE_START, &dev->state);
1531 if (ops->ndo_validate_addr)
1532 ret = ops->ndo_validate_addr(dev);
1534 if (!ret && ops->ndo_open)
1535 ret = ops->ndo_open(dev);
1537 netpoll_poll_enable(dev);
1540 clear_bit(__LINK_STATE_START, &dev->state);
1542 dev->flags |= IFF_UP;
1543 dev_set_rx_mode(dev);
1545 add_device_randomness(dev->dev_addr, dev->addr_len);
1552 * dev_open - prepare an interface for use.
1553 * @dev: device to open
1554 * @extack: netlink extended ack
1556 * Takes a device from down to up state. The device's private open
1557 * function is invoked and then the multicast lists are loaded. Finally
1558 * the device is moved into the up state and a %NETDEV_UP message is
1559 * sent to the netdev notifier chain.
1561 * Calling this function on an active interface is a nop. On a failure
1562 * a negative errno code is returned.
1564 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1568 if (dev->flags & IFF_UP)
1571 ret = __dev_open(dev, extack);
1575 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1576 call_netdevice_notifiers(NETDEV_UP, dev);
1580 EXPORT_SYMBOL(dev_open);
1582 static void __dev_close_many(struct list_head *head)
1584 struct net_device *dev;
1589 list_for_each_entry(dev, head, close_list) {
1590 /* Temporarily disable netpoll until the interface is down */
1591 netpoll_poll_disable(dev);
1593 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1595 clear_bit(__LINK_STATE_START, &dev->state);
1597 /* Synchronize to scheduled poll. We cannot touch poll list, it
1598 * can be even on different cpu. So just clear netif_running().
1600 * dev->stop() will invoke napi_disable() on all of it's
1601 * napi_struct instances on this device.
1603 smp_mb__after_atomic(); /* Commit netif_running(). */
1606 dev_deactivate_many(head);
1608 list_for_each_entry(dev, head, close_list) {
1609 const struct net_device_ops *ops = dev->netdev_ops;
1612 * Call the device specific close. This cannot fail.
1613 * Only if device is UP
1615 * We allow it to be called even after a DETACH hot-plug
1621 dev->flags &= ~IFF_UP;
1622 netpoll_poll_enable(dev);
1626 static void __dev_close(struct net_device *dev)
1630 list_add(&dev->close_list, &single);
1631 __dev_close_many(&single);
1635 void dev_close_many(struct list_head *head, bool unlink)
1637 struct net_device *dev, *tmp;
1639 /* Remove the devices that don't need to be closed */
1640 list_for_each_entry_safe(dev, tmp, head, close_list)
1641 if (!(dev->flags & IFF_UP))
1642 list_del_init(&dev->close_list);
1644 __dev_close_many(head);
1646 list_for_each_entry_safe(dev, tmp, head, close_list) {
1647 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
1648 call_netdevice_notifiers(NETDEV_DOWN, dev);
1650 list_del_init(&dev->close_list);
1653 EXPORT_SYMBOL(dev_close_many);
1656 * dev_close - shutdown an interface.
1657 * @dev: device to shutdown
1659 * This function moves an active device into down state. A
1660 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1661 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1664 void dev_close(struct net_device *dev)
1666 if (dev->flags & IFF_UP) {
1669 list_add(&dev->close_list, &single);
1670 dev_close_many(&single, true);
1674 EXPORT_SYMBOL(dev_close);
1678 * dev_disable_lro - disable Large Receive Offload on a device
1681 * Disable Large Receive Offload (LRO) on a net device. Must be
1682 * called under RTNL. This is needed if received packets may be
1683 * forwarded to another interface.
1685 void dev_disable_lro(struct net_device *dev)
1687 struct net_device *lower_dev;
1688 struct list_head *iter;
1690 dev->wanted_features &= ~NETIF_F_LRO;
1691 netdev_update_features(dev);
1693 if (unlikely(dev->features & NETIF_F_LRO))
1694 netdev_WARN(dev, "failed to disable LRO!\n");
1696 netdev_for_each_lower_dev(dev, lower_dev, iter)
1697 dev_disable_lro(lower_dev);
1699 EXPORT_SYMBOL(dev_disable_lro);
1702 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1705 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1706 * called under RTNL. This is needed if Generic XDP is installed on
1709 static void dev_disable_gro_hw(struct net_device *dev)
1711 dev->wanted_features &= ~NETIF_F_GRO_HW;
1712 netdev_update_features(dev);
1714 if (unlikely(dev->features & NETIF_F_GRO_HW))
1715 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1718 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1721 case NETDEV_##val: \
1722 return "NETDEV_" __stringify(val);
1724 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1725 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1726 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1727 N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
1728 N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
1729 N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
1730 N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1731 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1732 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1736 return "UNKNOWN_NETDEV_EVENT";
1738 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1740 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1741 struct net_device *dev)
1743 struct netdev_notifier_info info = {
1747 return nb->notifier_call(nb, val, &info);
1750 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1751 struct net_device *dev)
1755 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1756 err = notifier_to_errno(err);
1760 if (!(dev->flags & IFF_UP))
1763 call_netdevice_notifier(nb, NETDEV_UP, dev);
1767 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1768 struct net_device *dev)
1770 if (dev->flags & IFF_UP) {
1771 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1773 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1775 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1778 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1781 struct net_device *dev;
1784 for_each_netdev(net, dev) {
1785 err = call_netdevice_register_notifiers(nb, dev);
1792 for_each_netdev_continue_reverse(net, dev)
1793 call_netdevice_unregister_notifiers(nb, dev);
1797 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1800 struct net_device *dev;
1802 for_each_netdev(net, dev)
1803 call_netdevice_unregister_notifiers(nb, dev);
1806 static int dev_boot_phase = 1;
1809 * register_netdevice_notifier - register a network notifier block
1812 * Register a notifier to be called when network device events occur.
1813 * The notifier passed is linked into the kernel structures and must
1814 * not be reused until it has been unregistered. A negative errno code
1815 * is returned on a failure.
1817 * When registered all registration and up events are replayed
1818 * to the new notifier to allow device to have a race free
1819 * view of the network device list.
1822 int register_netdevice_notifier(struct notifier_block *nb)
1827 /* Close race with setup_net() and cleanup_net() */
1828 down_write(&pernet_ops_rwsem);
1830 err = raw_notifier_chain_register(&netdev_chain, nb);
1836 err = call_netdevice_register_net_notifiers(nb, net);
1843 up_write(&pernet_ops_rwsem);
1847 for_each_net_continue_reverse(net)
1848 call_netdevice_unregister_net_notifiers(nb, net);
1850 raw_notifier_chain_unregister(&netdev_chain, nb);
1853 EXPORT_SYMBOL(register_netdevice_notifier);
1856 * unregister_netdevice_notifier - unregister a network notifier block
1859 * Unregister a notifier previously registered by
1860 * register_netdevice_notifier(). The notifier is unlinked into the
1861 * kernel structures and may then be reused. A negative errno code
1862 * is returned on a failure.
1864 * After unregistering unregister and down device events are synthesized
1865 * for all devices on the device list to the removed notifier to remove
1866 * the need for special case cleanup code.
1869 int unregister_netdevice_notifier(struct notifier_block *nb)
1874 /* Close race with setup_net() and cleanup_net() */
1875 down_write(&pernet_ops_rwsem);
1877 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1882 call_netdevice_unregister_net_notifiers(nb, net);
1886 up_write(&pernet_ops_rwsem);
1889 EXPORT_SYMBOL(unregister_netdevice_notifier);
1891 static int __register_netdevice_notifier_net(struct net *net,
1892 struct notifier_block *nb,
1893 bool ignore_call_fail)
1897 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1903 err = call_netdevice_register_net_notifiers(nb, net);
1904 if (err && !ignore_call_fail)
1905 goto chain_unregister;
1910 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1914 static int __unregister_netdevice_notifier_net(struct net *net,
1915 struct notifier_block *nb)
1919 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1923 call_netdevice_unregister_net_notifiers(nb, net);
1928 * register_netdevice_notifier_net - register a per-netns network notifier block
1929 * @net: network namespace
1932 * Register a notifier to be called when network device events occur.
1933 * The notifier passed is linked into the kernel structures and must
1934 * not be reused until it has been unregistered. A negative errno code
1935 * is returned on a failure.
1937 * When registered all registration and up events are replayed
1938 * to the new notifier to allow device to have a race free
1939 * view of the network device list.
1942 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1947 err = __register_netdevice_notifier_net(net, nb, false);
1951 EXPORT_SYMBOL(register_netdevice_notifier_net);
1954 * unregister_netdevice_notifier_net - unregister a per-netns
1955 * network notifier block
1956 * @net: network namespace
1959 * Unregister a notifier previously registered by
1960 * register_netdevice_notifier(). The notifier is unlinked into the
1961 * kernel structures and may then be reused. A negative errno code
1962 * is returned on a failure.
1964 * After unregistering unregister and down device events are synthesized
1965 * for all devices on the device list to the removed notifier to remove
1966 * the need for special case cleanup code.
1969 int unregister_netdevice_notifier_net(struct net *net,
1970 struct notifier_block *nb)
1975 err = __unregister_netdevice_notifier_net(net, nb);
1979 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1981 int register_netdevice_notifier_dev_net(struct net_device *dev,
1982 struct notifier_block *nb,
1983 struct netdev_net_notifier *nn)
1988 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1991 list_add(&nn->list, &dev->net_notifier_list);
1996 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1998 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1999 struct notifier_block *nb,
2000 struct netdev_net_notifier *nn)
2005 list_del(&nn->list);
2006 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
2010 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
2012 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
2015 struct netdev_net_notifier *nn;
2017 list_for_each_entry(nn, &dev->net_notifier_list, list) {
2018 __unregister_netdevice_notifier_net(dev_net(dev), nn->nb);
2019 __register_netdevice_notifier_net(net, nn->nb, true);
2024 * call_netdevice_notifiers_info - call all network notifier blocks
2025 * @val: value passed unmodified to notifier function
2026 * @info: notifier information data
2028 * Call all network notifier blocks. Parameters and return value
2029 * are as for raw_notifier_call_chain().
2032 static int call_netdevice_notifiers_info(unsigned long val,
2033 struct netdev_notifier_info *info)
2035 struct net *net = dev_net(info->dev);
2040 /* Run per-netns notifier block chain first, then run the global one.
2041 * Hopefully, one day, the global one is going to be removed after
2042 * all notifier block registrators get converted to be per-netns.
2044 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
2045 if (ret & NOTIFY_STOP_MASK)
2047 return raw_notifier_call_chain(&netdev_chain, val, info);
2050 static int call_netdevice_notifiers_extack(unsigned long val,
2051 struct net_device *dev,
2052 struct netlink_ext_ack *extack)
2054 struct netdev_notifier_info info = {
2059 return call_netdevice_notifiers_info(val, &info);
2063 * call_netdevice_notifiers - call all network notifier blocks
2064 * @val: value passed unmodified to notifier function
2065 * @dev: net_device pointer passed unmodified to notifier function
2067 * Call all network notifier blocks. Parameters and return value
2068 * are as for raw_notifier_call_chain().
2071 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2073 return call_netdevice_notifiers_extack(val, dev, NULL);
2075 EXPORT_SYMBOL(call_netdevice_notifiers);
2078 * call_netdevice_notifiers_mtu - call all network notifier blocks
2079 * @val: value passed unmodified to notifier function
2080 * @dev: net_device pointer passed unmodified to notifier function
2081 * @arg: additional u32 argument passed to the notifier function
2083 * Call all network notifier blocks. Parameters and return value
2084 * are as for raw_notifier_call_chain().
2086 static int call_netdevice_notifiers_mtu(unsigned long val,
2087 struct net_device *dev, u32 arg)
2089 struct netdev_notifier_info_ext info = {
2094 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2096 return call_netdevice_notifiers_info(val, &info.info);
2099 #ifdef CONFIG_NET_INGRESS
2100 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2102 void net_inc_ingress_queue(void)
2104 static_branch_inc(&ingress_needed_key);
2106 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2108 void net_dec_ingress_queue(void)
2110 static_branch_dec(&ingress_needed_key);
2112 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2115 #ifdef CONFIG_NET_EGRESS
2116 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2118 void net_inc_egress_queue(void)
2120 static_branch_inc(&egress_needed_key);
2122 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2124 void net_dec_egress_queue(void)
2126 static_branch_dec(&egress_needed_key);
2128 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2131 static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2132 #ifdef CONFIG_JUMP_LABEL
2133 static atomic_t netstamp_needed_deferred;
2134 static atomic_t netstamp_wanted;
2135 static void netstamp_clear(struct work_struct *work)
2137 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2140 wanted = atomic_add_return(deferred, &netstamp_wanted);
2142 static_branch_enable(&netstamp_needed_key);
2144 static_branch_disable(&netstamp_needed_key);
2146 static DECLARE_WORK(netstamp_work, netstamp_clear);
2149 void net_enable_timestamp(void)
2151 #ifdef CONFIG_JUMP_LABEL
2155 wanted = atomic_read(&netstamp_wanted);
2158 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
2161 atomic_inc(&netstamp_needed_deferred);
2162 schedule_work(&netstamp_work);
2164 static_branch_inc(&netstamp_needed_key);
2167 EXPORT_SYMBOL(net_enable_timestamp);
2169 void net_disable_timestamp(void)
2171 #ifdef CONFIG_JUMP_LABEL
2175 wanted = atomic_read(&netstamp_wanted);
2178 if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
2181 atomic_dec(&netstamp_needed_deferred);
2182 schedule_work(&netstamp_work);
2184 static_branch_dec(&netstamp_needed_key);
2187 EXPORT_SYMBOL(net_disable_timestamp);
2189 static inline void net_timestamp_set(struct sk_buff *skb)
2192 if (static_branch_unlikely(&netstamp_needed_key))
2193 __net_timestamp(skb);
2196 #define net_timestamp_check(COND, SKB) \
2197 if (static_branch_unlikely(&netstamp_needed_key)) { \
2198 if ((COND) && !(SKB)->tstamp) \
2199 __net_timestamp(SKB); \
2202 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2206 if (!(dev->flags & IFF_UP))
2209 len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
2210 if (skb->len <= len)
2213 /* if TSO is enabled, we don't care about the length as the packet
2214 * could be forwarded without being segmented before
2216 if (skb_is_gso(skb))
2221 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2223 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2225 int ret = ____dev_forward_skb(dev, skb);
2228 skb->protocol = eth_type_trans(skb, dev);
2229 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2234 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2237 * dev_forward_skb - loopback an skb to another netif
2239 * @dev: destination network device
2240 * @skb: buffer to forward
2243 * NET_RX_SUCCESS (no congestion)
2244 * NET_RX_DROP (packet was dropped, but freed)
2246 * dev_forward_skb can be used for injecting an skb from the
2247 * start_xmit function of one device into the receive queue
2248 * of another device.
2250 * The receiving device may be in another namespace, so
2251 * we have to clear all information in the skb that could
2252 * impact namespace isolation.
2254 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2256 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2258 EXPORT_SYMBOL_GPL(dev_forward_skb);
2260 static inline int deliver_skb(struct sk_buff *skb,
2261 struct packet_type *pt_prev,
2262 struct net_device *orig_dev)
2264 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2266 refcount_inc(&skb->users);
2267 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2270 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2271 struct packet_type **pt,
2272 struct net_device *orig_dev,
2274 struct list_head *ptype_list)
2276 struct packet_type *ptype, *pt_prev = *pt;
2278 list_for_each_entry_rcu(ptype, ptype_list, list) {
2279 if (ptype->type != type)
2282 deliver_skb(skb, pt_prev, orig_dev);
2288 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2290 if (!ptype->af_packet_priv || !skb->sk)
2293 if (ptype->id_match)
2294 return ptype->id_match(ptype, skb->sk);
2295 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2302 * dev_nit_active - return true if any network interface taps are in use
2304 * @dev: network device to check for the presence of taps
2306 bool dev_nit_active(struct net_device *dev)
2308 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2310 EXPORT_SYMBOL_GPL(dev_nit_active);
2313 * Support routine. Sends outgoing frames to any network
2314 * taps currently in use.
2317 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2319 struct packet_type *ptype;
2320 struct sk_buff *skb2 = NULL;
2321 struct packet_type *pt_prev = NULL;
2322 struct list_head *ptype_list = &ptype_all;
2326 list_for_each_entry_rcu(ptype, ptype_list, list) {
2327 if (ptype->ignore_outgoing)
2330 /* Never send packets back to the socket
2331 * they originated from - MvS (miquels@drinkel.ow.org)
2333 if (skb_loop_sk(ptype, skb))
2337 deliver_skb(skb2, pt_prev, skb->dev);
2342 /* need to clone skb, done only once */
2343 skb2 = skb_clone(skb, GFP_ATOMIC);
2347 net_timestamp_set(skb2);
2349 /* skb->nh should be correctly
2350 * set by sender, so that the second statement is
2351 * just protection against buggy protocols.
2353 skb_reset_mac_header(skb2);
2355 if (skb_network_header(skb2) < skb2->data ||
2356 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2357 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2358 ntohs(skb2->protocol),
2360 skb_reset_network_header(skb2);
2363 skb2->transport_header = skb2->network_header;
2364 skb2->pkt_type = PACKET_OUTGOING;
2368 if (ptype_list == &ptype_all) {
2369 ptype_list = &dev->ptype_all;
2374 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2375 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2381 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2384 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2385 * @dev: Network device
2386 * @txq: number of queues available
2388 * If real_num_tx_queues is changed the tc mappings may no longer be
2389 * valid. To resolve this verify the tc mapping remains valid and if
2390 * not NULL the mapping. With no priorities mapping to this
2391 * offset/count pair it will no longer be used. In the worst case TC0
2392 * is invalid nothing can be done so disable priority mappings. If is
2393 * expected that drivers will fix this mapping if they can before
2394 * calling netif_set_real_num_tx_queues.
2396 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2399 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2401 /* If TC0 is invalidated disable TC mapping */
2402 if (tc->offset + tc->count > txq) {
2403 pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2408 /* Invalidated prio to tc mappings set to TC0 */
2409 for (i = 1; i < TC_BITMASK + 1; i++) {
2410 int q = netdev_get_prio_tc_map(dev, i);
2412 tc = &dev->tc_to_txq[q];
2413 if (tc->offset + tc->count > txq) {
2414 pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2416 netdev_set_prio_tc_map(dev, i, 0);
2421 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2424 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2427 /* walk through the TCs and see if it falls into any of them */
2428 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2429 if ((txq - tc->offset) < tc->count)
2433 /* didn't find it, just return -1 to indicate no match */
2439 EXPORT_SYMBOL(netdev_txq_to_tc);
2442 struct static_key xps_needed __read_mostly;
2443 EXPORT_SYMBOL(xps_needed);
2444 struct static_key xps_rxqs_needed __read_mostly;
2445 EXPORT_SYMBOL(xps_rxqs_needed);
2446 static DEFINE_MUTEX(xps_map_mutex);
2447 #define xmap_dereference(P) \
2448 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2450 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2453 struct xps_map *map = NULL;
2457 map = xmap_dereference(dev_maps->attr_map[tci]);
2461 for (pos = map->len; pos--;) {
2462 if (map->queues[pos] != index)
2466 map->queues[pos] = map->queues[--map->len];
2470 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2471 kfree_rcu(map, rcu);
2478 static bool remove_xps_queue_cpu(struct net_device *dev,
2479 struct xps_dev_maps *dev_maps,
2480 int cpu, u16 offset, u16 count)
2482 int num_tc = dev->num_tc ? : 1;
2483 bool active = false;
2486 for (tci = cpu * num_tc; num_tc--; tci++) {
2489 for (i = count, j = offset; i--; j++) {
2490 if (!remove_xps_queue(dev_maps, tci, j))
2500 static void reset_xps_maps(struct net_device *dev,
2501 struct xps_dev_maps *dev_maps,
2505 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2506 RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
2508 RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
2510 static_key_slow_dec_cpuslocked(&xps_needed);
2511 kfree_rcu(dev_maps, rcu);
2514 static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
2515 struct xps_dev_maps *dev_maps, unsigned int nr_ids,
2516 u16 offset, u16 count, bool is_rxqs_map)
2518 bool active = false;
2521 for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
2523 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
2526 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2529 for (i = offset + (count - 1); count--; i--) {
2530 netdev_queue_numa_node_write(
2531 netdev_get_tx_queue(dev, i),
2537 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2540 const unsigned long *possible_mask = NULL;
2541 struct xps_dev_maps *dev_maps;
2542 unsigned int nr_ids;
2544 if (!static_key_false(&xps_needed))
2548 mutex_lock(&xps_map_mutex);
2550 if (static_key_false(&xps_rxqs_needed)) {
2551 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2553 nr_ids = dev->num_rx_queues;
2554 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
2555 offset, count, true);
2559 dev_maps = xmap_dereference(dev->xps_cpus_map);
2563 if (num_possible_cpus() > 1)
2564 possible_mask = cpumask_bits(cpu_possible_mask);
2565 nr_ids = nr_cpu_ids;
2566 clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
2570 mutex_unlock(&xps_map_mutex);
2574 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2576 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2579 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2580 u16 index, bool is_rxqs_map)
2582 struct xps_map *new_map;
2583 int alloc_len = XPS_MIN_MAP_ALLOC;
2586 for (pos = 0; map && pos < map->len; pos++) {
2587 if (map->queues[pos] != index)
2592 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2594 if (pos < map->alloc_len)
2597 alloc_len = map->alloc_len * 2;
2600 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2604 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2606 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2607 cpu_to_node(attr_index));
2611 for (i = 0; i < pos; i++)
2612 new_map->queues[i] = map->queues[i];
2613 new_map->alloc_len = alloc_len;
2619 /* Must be called under cpus_read_lock */
2620 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2621 u16 index, bool is_rxqs_map)
2623 const unsigned long *online_mask = NULL, *possible_mask = NULL;
2624 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
2625 int i, j, tci, numa_node_id = -2;
2626 int maps_sz, num_tc = 1, tc = 0;
2627 struct xps_map *map, *new_map;
2628 bool active = false;
2629 unsigned int nr_ids;
2632 /* Do not allow XPS on subordinate device directly */
2633 num_tc = dev->num_tc;
2637 /* If queue belongs to subordinate dev use its map */
2638 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2640 tc = netdev_txq_to_tc(dev, index);
2645 mutex_lock(&xps_map_mutex);
2647 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2648 dev_maps = xmap_dereference(dev->xps_rxqs_map);
2649 nr_ids = dev->num_rx_queues;
2651 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2652 if (num_possible_cpus() > 1) {
2653 online_mask = cpumask_bits(cpu_online_mask);
2654 possible_mask = cpumask_bits(cpu_possible_mask);
2656 dev_maps = xmap_dereference(dev->xps_cpus_map);
2657 nr_ids = nr_cpu_ids;
2660 if (maps_sz < L1_CACHE_BYTES)
2661 maps_sz = L1_CACHE_BYTES;
2663 /* allocate memory for queue storage */
2664 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2667 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2668 if (!new_dev_maps) {
2669 mutex_unlock(&xps_map_mutex);
2673 tci = j * num_tc + tc;
2674 map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
2677 map = expand_xps_map(map, j, index, is_rxqs_map);
2681 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2685 goto out_no_new_maps;
2688 /* Increment static keys at most once per type */
2689 static_key_slow_inc_cpuslocked(&xps_needed);
2691 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2694 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2696 /* copy maps belonging to foreign traffic classes */
2697 for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
2698 /* fill in the new device map from the old device map */
2699 map = xmap_dereference(dev_maps->attr_map[tci]);
2700 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2703 /* We need to explicitly update tci as prevous loop
2704 * could break out early if dev_maps is NULL.
2706 tci = j * num_tc + tc;
2708 if (netif_attr_test_mask(j, mask, nr_ids) &&
2709 netif_attr_test_online(j, online_mask, nr_ids)) {
2710 /* add tx-queue to CPU/rx-queue maps */
2713 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2714 while ((pos < map->len) && (map->queues[pos] != index))
2717 if (pos == map->len)
2718 map->queues[map->len++] = index;
2721 if (numa_node_id == -2)
2722 numa_node_id = cpu_to_node(j);
2723 else if (numa_node_id != cpu_to_node(j))
2727 } else if (dev_maps) {
2728 /* fill in the new device map from the old device map */
2729 map = xmap_dereference(dev_maps->attr_map[tci]);
2730 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2733 /* copy maps belonging to foreign traffic classes */
2734 for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
2735 /* fill in the new device map from the old device map */
2736 map = xmap_dereference(dev_maps->attr_map[tci]);
2737 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2742 rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
2744 rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
2746 /* Cleanup old maps */
2748 goto out_no_old_maps;
2750 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2752 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2753 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2754 map = xmap_dereference(dev_maps->attr_map[tci]);
2755 if (map && map != new_map)
2756 kfree_rcu(map, rcu);
2760 kfree_rcu(dev_maps, rcu);
2763 dev_maps = new_dev_maps;
2768 /* update Tx queue numa node */
2769 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2770 (numa_node_id >= 0) ?
2771 numa_node_id : NUMA_NO_NODE);
2777 /* removes tx-queue from unused CPUs/rx-queues */
2778 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2780 for (i = tc, tci = j * num_tc; i--; tci++)
2781 active |= remove_xps_queue(dev_maps, tci, index);
2782 if (!netif_attr_test_mask(j, mask, nr_ids) ||
2783 !netif_attr_test_online(j, online_mask, nr_ids))
2784 active |= remove_xps_queue(dev_maps, tci, index);
2785 for (i = num_tc - tc, tci++; --i; tci++)
2786 active |= remove_xps_queue(dev_maps, tci, index);
2789 /* free map if not active */
2791 reset_xps_maps(dev, dev_maps, is_rxqs_map);
2794 mutex_unlock(&xps_map_mutex);
2798 /* remove any maps that we added */
2799 for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
2801 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2802 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2804 xmap_dereference(dev_maps->attr_map[tci]) :
2806 if (new_map && new_map != map)
2811 mutex_unlock(&xps_map_mutex);
2813 kfree(new_dev_maps);
2816 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2818 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2824 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
2829 EXPORT_SYMBOL(netif_set_xps_queue);
2832 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2834 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2836 /* Unbind any subordinate channels */
2837 while (txq-- != &dev->_tx[0]) {
2839 netdev_unbind_sb_channel(dev, txq->sb_dev);
2843 void netdev_reset_tc(struct net_device *dev)
2846 netif_reset_xps_queues_gt(dev, 0);
2848 netdev_unbind_all_sb_channels(dev);
2850 /* Reset TC configuration of device */
2852 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2853 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2855 EXPORT_SYMBOL(netdev_reset_tc);
2857 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2859 if (tc >= dev->num_tc)
2863 netif_reset_xps_queues(dev, offset, count);
2865 dev->tc_to_txq[tc].count = count;
2866 dev->tc_to_txq[tc].offset = offset;
2869 EXPORT_SYMBOL(netdev_set_tc_queue);
2871 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2873 if (num_tc > TC_MAX_QUEUE)
2877 netif_reset_xps_queues_gt(dev, 0);
2879 netdev_unbind_all_sb_channels(dev);
2881 dev->num_tc = num_tc;
2884 EXPORT_SYMBOL(netdev_set_num_tc);
2886 void netdev_unbind_sb_channel(struct net_device *dev,
2887 struct net_device *sb_dev)
2889 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2892 netif_reset_xps_queues_gt(sb_dev, 0);
2894 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2895 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2897 while (txq-- != &dev->_tx[0]) {
2898 if (txq->sb_dev == sb_dev)
2902 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2904 int netdev_bind_sb_channel_queue(struct net_device *dev,
2905 struct net_device *sb_dev,
2906 u8 tc, u16 count, u16 offset)
2908 /* Make certain the sb_dev and dev are already configured */
2909 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2912 /* We cannot hand out queues we don't have */
2913 if ((offset + count) > dev->real_num_tx_queues)
2916 /* Record the mapping */
2917 sb_dev->tc_to_txq[tc].count = count;
2918 sb_dev->tc_to_txq[tc].offset = offset;
2920 /* Provide a way for Tx queue to find the tc_to_txq map or
2921 * XPS map for itself.
2924 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2928 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2930 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2932 /* Do not use a multiqueue device to represent a subordinate channel */
2933 if (netif_is_multiqueue(dev))
2936 /* We allow channels 1 - 32767 to be used for subordinate channels.
2937 * Channel 0 is meant to be "native" mode and used only to represent
2938 * the main root device. We allow writing 0 to reset the device back
2939 * to normal mode after being used as a subordinate channel.
2941 if (channel > S16_MAX)
2944 dev->num_tc = -channel;
2948 EXPORT_SYMBOL(netdev_set_sb_channel);
2951 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2952 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2954 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2959 disabling = txq < dev->real_num_tx_queues;
2961 if (txq < 1 || txq > dev->num_tx_queues)
2964 if (dev->reg_state == NETREG_REGISTERED ||
2965 dev->reg_state == NETREG_UNREGISTERING) {
2968 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2974 netif_setup_tc(dev, txq);
2976 dev_qdisc_change_real_num_tx(dev, txq);
2978 dev->real_num_tx_queues = txq;
2982 qdisc_reset_all_tx_gt(dev, txq);
2984 netif_reset_xps_queues_gt(dev, txq);
2988 dev->real_num_tx_queues = txq;
2993 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2997 * netif_set_real_num_rx_queues - set actual number of RX queues used
2998 * @dev: Network device
2999 * @rxq: Actual number of RX queues
3001 * This must be called either with the rtnl_lock held or before
3002 * registration of the net device. Returns 0 on success, or a
3003 * negative error code. If called before registration, it always
3006 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
3010 if (rxq < 1 || rxq > dev->num_rx_queues)
3013 if (dev->reg_state == NETREG_REGISTERED) {
3016 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
3022 dev->real_num_rx_queues = rxq;
3025 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3029 * netif_get_num_default_rss_queues - default number of RSS queues
3031 * This routine should set an upper limit on the number of RSS queues
3032 * used by default by multiqueue devices.
3034 int netif_get_num_default_rss_queues(void)
3036 return is_kdump_kernel() ?
3037 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
3039 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3041 static void __netif_reschedule(struct Qdisc *q)
3043 struct softnet_data *sd;
3044 unsigned long flags;
3046 local_irq_save(flags);
3047 sd = this_cpu_ptr(&softnet_data);
3048 q->next_sched = NULL;
3049 *sd->output_queue_tailp = q;
3050 sd->output_queue_tailp = &q->next_sched;
3051 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3052 local_irq_restore(flags);
3055 void __netif_schedule(struct Qdisc *q)
3057 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3058 __netif_reschedule(q);
3060 EXPORT_SYMBOL(__netif_schedule);
3062 struct dev_kfree_skb_cb {
3063 enum skb_free_reason reason;
3066 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3068 return (struct dev_kfree_skb_cb *)skb->cb;
3071 void netif_schedule_queue(struct netdev_queue *txq)
3074 if (!netif_xmit_stopped(txq)) {
3075 struct Qdisc *q = rcu_dereference(txq->qdisc);
3077 __netif_schedule(q);
3081 EXPORT_SYMBOL(netif_schedule_queue);
3083 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3085 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3089 q = rcu_dereference(dev_queue->qdisc);
3090 __netif_schedule(q);
3094 EXPORT_SYMBOL(netif_tx_wake_queue);
3096 void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
3098 unsigned long flags;
3103 if (likely(refcount_read(&skb->users) == 1)) {
3105 refcount_set(&skb->users, 0);
3106 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3109 get_kfree_skb_cb(skb)->reason = reason;
3110 local_irq_save(flags);
3111 skb->next = __this_cpu_read(softnet_data.completion_queue);
3112 __this_cpu_write(softnet_data.completion_queue, skb);
3113 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3114 local_irq_restore(flags);
3116 EXPORT_SYMBOL(__dev_kfree_skb_irq);
3118 void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
3120 if (in_irq() || irqs_disabled())
3121 __dev_kfree_skb_irq(skb, reason);
3125 EXPORT_SYMBOL(__dev_kfree_skb_any);
3129 * netif_device_detach - mark device as removed
3130 * @dev: network device
3132 * Mark device as removed from system and therefore no longer available.
3134 void netif_device_detach(struct net_device *dev)
3136 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3137 netif_running(dev)) {
3138 netif_tx_stop_all_queues(dev);
3141 EXPORT_SYMBOL(netif_device_detach);
3144 * netif_device_attach - mark device as attached
3145 * @dev: network device
3147 * Mark device as attached from system and restart if needed.
3149 void netif_device_attach(struct net_device *dev)
3151 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3152 netif_running(dev)) {
3153 netif_tx_wake_all_queues(dev);
3154 __netdev_watchdog_up(dev);
3157 EXPORT_SYMBOL(netif_device_attach);
3160 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3161 * to be used as a distribution range.
3163 static u16 skb_tx_hash(const struct net_device *dev,
3164 const struct net_device *sb_dev,
3165 struct sk_buff *skb)
3169 u16 qcount = dev->real_num_tx_queues;
3172 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3174 qoffset = sb_dev->tc_to_txq[tc].offset;
3175 qcount = sb_dev->tc_to_txq[tc].count;
3176 if (unlikely(!qcount)) {
3177 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3178 sb_dev->name, qoffset, tc);
3180 qcount = dev->real_num_tx_queues;
3184 if (skb_rx_queue_recorded(skb)) {
3185 hash = skb_get_rx_queue(skb);
3186 if (hash >= qoffset)
3188 while (unlikely(hash >= qcount))
3190 return hash + qoffset;
3193 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3196 static void skb_warn_bad_offload(const struct sk_buff *skb)
3198 static const netdev_features_t null_features;
3199 struct net_device *dev = skb->dev;
3200 const char *name = "";
3202 if (!net_ratelimit())
3206 if (dev->dev.parent)
3207 name = dev_driver_string(dev->dev.parent);
3209 name = netdev_name(dev);
3211 skb_dump(KERN_WARNING, skb, false);
3212 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3213 name, dev ? &dev->features : &null_features,
3214 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3218 * Invalidate hardware checksum when packet is to be mangled, and
3219 * complete checksum manually on outgoing path.
3221 int skb_checksum_help(struct sk_buff *skb)
3224 int ret = 0, offset;
3226 if (skb->ip_summed == CHECKSUM_COMPLETE)
3227 goto out_set_summed;
3229 if (unlikely(skb_shinfo(skb)->gso_size)) {
3230 skb_warn_bad_offload(skb);
3234 /* Before computing a checksum, we should make sure no frag could
3235 * be modified by an external entity : checksum could be wrong.
3237 if (skb_has_shared_frag(skb)) {
3238 ret = __skb_linearize(skb);
3243 offset = skb_checksum_start_offset(skb);
3245 if (WARN_ON_ONCE(offset >= skb_headlen(skb)))
3248 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3250 offset += skb->csum_offset;
3251 if (WARN_ON_ONCE(offset + sizeof(__sum16) > skb_headlen(skb)))
3254 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3258 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3260 skb->ip_summed = CHECKSUM_NONE;
3264 EXPORT_SYMBOL(skb_checksum_help);
3266 int skb_crc32c_csum_help(struct sk_buff *skb)
3269 int ret = 0, offset, start;
3271 if (skb->ip_summed != CHECKSUM_PARTIAL)
3274 if (unlikely(skb_is_gso(skb)))
3277 /* Before computing a checksum, we should make sure no frag could
3278 * be modified by an external entity : checksum could be wrong.
3280 if (unlikely(skb_has_shared_frag(skb))) {
3281 ret = __skb_linearize(skb);
3285 start = skb_checksum_start_offset(skb);
3286 offset = start + offsetof(struct sctphdr, checksum);
3287 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3292 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3296 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3297 skb->len - start, ~(__u32)0,
3299 *(__le32 *)(skb->data + offset) = crc32c_csum;
3300 skb->ip_summed = CHECKSUM_NONE;
3301 skb->csum_not_inet = 0;
3306 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3308 __be16 type = skb->protocol;
3310 /* Tunnel gso handlers can set protocol to ethernet. */
3311 if (type == htons(ETH_P_TEB)) {
3314 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3317 eth = (struct ethhdr *)skb->data;
3318 type = eth->h_proto;
3321 return __vlan_get_protocol(skb, type, depth);
3325 * skb_mac_gso_segment - mac layer segmentation handler.
3326 * @skb: buffer to segment
3327 * @features: features for the output path (see dev->features)
3329 struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
3330 netdev_features_t features)
3332 struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
3333 struct packet_offload *ptype;
3334 int vlan_depth = skb->mac_len;
3335 __be16 type = skb_network_protocol(skb, &vlan_depth);
3337 if (unlikely(!type))
3338 return ERR_PTR(-EINVAL);
3340 __skb_pull(skb, vlan_depth);
3343 list_for_each_entry_rcu(ptype, &offload_base, list) {
3344 if (ptype->type == type && ptype->callbacks.gso_segment) {
3345 segs = ptype->callbacks.gso_segment(skb, features);
3351 __skb_push(skb, skb->data - skb_mac_header(skb));
3355 EXPORT_SYMBOL(skb_mac_gso_segment);
3358 /* openvswitch calls this on rx path, so we need a different check.
3360 static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
3363 return skb->ip_summed != CHECKSUM_PARTIAL &&
3364 skb->ip_summed != CHECKSUM_UNNECESSARY;
3366 return skb->ip_summed == CHECKSUM_NONE;
3370 * __skb_gso_segment - Perform segmentation on skb.
3371 * @skb: buffer to segment
3372 * @features: features for the output path (see dev->features)
3373 * @tx_path: whether it is called in TX path
3375 * This function segments the given skb and returns a list of segments.
3377 * It may return NULL if the skb requires no segmentation. This is
3378 * only possible when GSO is used for verifying header integrity.
3380 * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
3382 struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
3383 netdev_features_t features, bool tx_path)
3385 struct sk_buff *segs;
3387 if (unlikely(skb_needs_check(skb, tx_path))) {
3390 /* We're going to init ->check field in TCP or UDP header */
3391 err = skb_cow_head(skb, 0);
3393 return ERR_PTR(err);
3396 /* Only report GSO partial support if it will enable us to
3397 * support segmentation on this frame without needing additional
3400 if (features & NETIF_F_GSO_PARTIAL) {
3401 netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
3402 struct net_device *dev = skb->dev;
3404 partial_features |= dev->features & dev->gso_partial_features;
3405 if (!skb_gso_ok(skb, features | partial_features))
3406 features &= ~NETIF_F_GSO_PARTIAL;
3409 BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
3410 sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
3412 SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
3413 SKB_GSO_CB(skb)->encap_level = 0;
3415 skb_reset_mac_header(skb);
3416 skb_reset_mac_len(skb);
3418 segs = skb_mac_gso_segment(skb, features);
3420 if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
3421 skb_warn_bad_offload(skb);
3425 EXPORT_SYMBOL(__skb_gso_segment);
3427 /* Take action when hardware reception checksum errors are detected. */
3429 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3431 if (net_ratelimit()) {
3432 pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
3433 skb_dump(KERN_ERR, skb, true);
3437 EXPORT_SYMBOL(netdev_rx_csum_fault);
3440 /* XXX: check that highmem exists at all on the given machine. */
3441 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3443 #ifdef CONFIG_HIGHMEM
3446 if (!(dev->features & NETIF_F_HIGHDMA)) {
3447 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3448 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3450 if (PageHighMem(skb_frag_page(frag)))
3458 /* If MPLS offload request, verify we are testing hardware MPLS features
3459 * instead of standard features for the netdev.
3461 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3462 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3463 netdev_features_t features,
3466 if (eth_p_mpls(type))
3467 features &= skb->dev->mpls_features;
3472 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3473 netdev_features_t features,
3480 static netdev_features_t harmonize_features(struct sk_buff *skb,
3481 netdev_features_t features)
3485 type = skb_network_protocol(skb, NULL);
3486 features = net_mpls_features(skb, features, type);
3488 if (skb->ip_summed != CHECKSUM_NONE &&
3489 !can_checksum_protocol(features, type)) {
3490 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3492 if (illegal_highdma(skb->dev, skb))
3493 features &= ~NETIF_F_SG;
3498 netdev_features_t passthru_features_check(struct sk_buff *skb,
3499 struct net_device *dev,
3500 netdev_features_t features)
3504 EXPORT_SYMBOL(passthru_features_check);
3506 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3507 struct net_device *dev,
3508 netdev_features_t features)
3510 return vlan_features_check(skb, features);
3513 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3514 struct net_device *dev,
3515 netdev_features_t features)
3517 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3519 if (gso_segs > dev->gso_max_segs)
3520 return features & ~NETIF_F_GSO_MASK;
3522 /* Support for GSO partial features requires software
3523 * intervention before we can actually process the packets
3524 * so we need to strip support for any partial features now
3525 * and we can pull them back in after we have partially
3526 * segmented the frame.
3528 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3529 features &= ~dev->gso_partial_features;
3531 /* Make sure to clear the IPv4 ID mangling feature if the
3532 * IPv4 header has the potential to be fragmented.
3534 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3535 struct iphdr *iph = skb->encapsulation ?
3536 inner_ip_hdr(skb) : ip_hdr(skb);
3538 if (!(iph->frag_off & htons(IP_DF)))
3539 features &= ~NETIF_F_TSO_MANGLEID;
3545 netdev_features_t netif_skb_features(struct sk_buff *skb)
3547 struct net_device *dev = skb->dev;
3548 netdev_features_t features = dev->features;
3550 if (skb_is_gso(skb))
3551 features = gso_features_check(skb, dev, features);
3553 /* If encapsulation offload request, verify we are testing
3554 * hardware encapsulation features instead of standard
3555 * features for the netdev
3557 if (skb->encapsulation)
3558 features &= dev->hw_enc_features;
3560 if (skb_vlan_tagged(skb))
3561 features = netdev_intersect_features(features,
3562 dev->vlan_features |
3563 NETIF_F_HW_VLAN_CTAG_TX |
3564 NETIF_F_HW_VLAN_STAG_TX);
3566 if (dev->netdev_ops->ndo_features_check)
3567 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3570 features &= dflt_features_check(skb, dev, features);
3572 return harmonize_features(skb, features);
3574 EXPORT_SYMBOL(netif_skb_features);
3576 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3577 struct netdev_queue *txq, bool more)
3582 if (dev_nit_active(dev))
3583 dev_queue_xmit_nit(skb, dev);
3586 PRANDOM_ADD_NOISE(skb, dev, txq, len + jiffies);
3587 trace_net_dev_start_xmit(skb, dev);
3588 rc = netdev_start_xmit(skb, dev, txq, more);
3589 trace_net_dev_xmit(skb, rc, dev, len);
3594 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3595 struct netdev_queue *txq, int *ret)
3597 struct sk_buff *skb = first;
3598 int rc = NETDEV_TX_OK;
3601 struct sk_buff *next = skb->next;
3603 skb_mark_not_on_list(skb);
3604 rc = xmit_one(skb, dev, txq, next != NULL);
3605 if (unlikely(!dev_xmit_complete(rc))) {
3611 if (netif_tx_queue_stopped(txq) && skb) {
3612 rc = NETDEV_TX_BUSY;
3622 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3623 netdev_features_t features)
3625 if (skb_vlan_tag_present(skb) &&
3626 !vlan_hw_offload_capable(features, skb->vlan_proto))
3627 skb = __vlan_hwaccel_push_inside(skb);
3631 int skb_csum_hwoffload_help(struct sk_buff *skb,
3632 const netdev_features_t features)
3634 if (unlikely(skb->csum_not_inet))
3635 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3636 skb_crc32c_csum_help(skb);
3638 return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
3640 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3642 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3644 netdev_features_t features;
3646 features = netif_skb_features(skb);
3647 skb = validate_xmit_vlan(skb, features);
3651 skb = sk_validate_xmit_skb(skb, dev);
3655 if (netif_needs_gso(skb, features)) {
3656 struct sk_buff *segs;
3658 segs = skb_gso_segment(skb, features);
3666 if (skb_needs_linearize(skb, features) &&
3667 __skb_linearize(skb))
3670 /* If packet is not checksummed and device does not
3671 * support checksumming for this protocol, complete
3672 * checksumming here.
3674 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3675 if (skb->encapsulation)
3676 skb_set_inner_transport_header(skb,
3677 skb_checksum_start_offset(skb));
3679 skb_set_transport_header(skb,
3680 skb_checksum_start_offset(skb));
3681 if (skb_csum_hwoffload_help(skb, features))
3686 skb = validate_xmit_xfrm(skb, features, again);
3693 atomic_long_inc(&dev->tx_dropped);
3697 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3699 struct sk_buff *next, *head = NULL, *tail;
3701 for (; skb != NULL; skb = next) {
3703 skb_mark_not_on_list(skb);
3705 /* in case skb wont be segmented, point to itself */
3708 skb = validate_xmit_skb(skb, dev, again);
3716 /* If skb was segmented, skb->prev points to
3717 * the last segment. If not, it still contains skb.
3723 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3725 static void qdisc_pkt_len_init(struct sk_buff *skb)
3727 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3729 qdisc_skb_cb(skb)->pkt_len = skb->len;
3731 /* To get more precise estimation of bytes sent on wire,
3732 * we add to pkt_len the headers size of all segments
3734 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3735 unsigned int hdr_len;
3736 u16 gso_segs = shinfo->gso_segs;
3738 /* mac layer + network layer */
3739 hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
3741 /* + transport layer */
3742 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3743 const struct tcphdr *th;
3744 struct tcphdr _tcphdr;
3746 th = skb_header_pointer(skb, skb_transport_offset(skb),
3747 sizeof(_tcphdr), &_tcphdr);
3749 hdr_len += __tcp_hdrlen(th);
3751 struct udphdr _udphdr;
3753 if (skb_header_pointer(skb, skb_transport_offset(skb),
3754 sizeof(_udphdr), &_udphdr))
3755 hdr_len += sizeof(struct udphdr);
3758 if (shinfo->gso_type & SKB_GSO_DODGY)
3759 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3762 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3766 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3767 struct net_device *dev,
3768 struct netdev_queue *txq)
3770 spinlock_t *root_lock = qdisc_lock(q);
3771 struct sk_buff *to_free = NULL;
3775 qdisc_calculate_pkt_len(skb, q);
3777 if (q->flags & TCQ_F_NOLOCK) {
3778 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3779 if (likely(!netif_xmit_frozen_or_stopped(txq)))
3782 if (unlikely(to_free))
3783 kfree_skb_list(to_free);
3788 * Heuristic to force contended enqueues to serialize on a
3789 * separate lock before trying to get qdisc main lock.
3790 * This permits qdisc->running owner to get the lock more
3791 * often and dequeue packets faster.
3793 contended = qdisc_is_running(q);
3794 if (unlikely(contended))
3795 spin_lock(&q->busylock);
3797 spin_lock(root_lock);
3798 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3799 __qdisc_drop(skb, &to_free);
3801 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3802 qdisc_run_begin(q)) {
3804 * This is a work-conserving queue; there are no old skbs
3805 * waiting to be sent out; and the qdisc is not running -
3806 * xmit the skb directly.
3809 qdisc_bstats_update(q, skb);
3811 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3812 if (unlikely(contended)) {
3813 spin_unlock(&q->busylock);
3820 rc = NET_XMIT_SUCCESS;
3822 rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
3823 if (qdisc_run_begin(q)) {
3824 if (unlikely(contended)) {
3825 spin_unlock(&q->busylock);
3832 spin_unlock(root_lock);
3833 if (unlikely(to_free))
3834 kfree_skb_list(to_free);
3835 if (unlikely(contended))
3836 spin_unlock(&q->busylock);
3840 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3841 static void skb_update_prio(struct sk_buff *skb)
3843 const struct netprio_map *map;
3844 const struct sock *sk;
3845 unsigned int prioidx;
3849 map = rcu_dereference_bh(skb->dev->priomap);
3852 sk = skb_to_full_sk(skb);
3856 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3858 if (prioidx < map->priomap_len)
3859 skb->priority = map->priomap[prioidx];
3862 #define skb_update_prio(skb)
3866 * dev_loopback_xmit - loop back @skb
3867 * @net: network namespace this loopback is happening in
3868 * @sk: sk needed to be a netfilter okfn
3869 * @skb: buffer to transmit
3871 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3873 skb_reset_mac_header(skb);
3874 __skb_pull(skb, skb_network_offset(skb));
3875 skb->pkt_type = PACKET_LOOPBACK;
3876 if (skb->ip_summed == CHECKSUM_NONE)
3877 skb->ip_summed = CHECKSUM_UNNECESSARY;
3878 WARN_ON(!skb_dst(skb));
3883 EXPORT_SYMBOL(dev_loopback_xmit);
3885 #ifdef CONFIG_NET_EGRESS
3886 static struct sk_buff *
3887 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
3889 struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
3890 struct tcf_result cl_res;
3895 /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
3896 qdisc_skb_cb(skb)->mru = 0;
3897 mini_qdisc_bstats_cpu_update(miniq, skb);
3899 switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
3901 case TC_ACT_RECLASSIFY:
3902 skb->tc_index = TC_H_MIN(cl_res.classid);
3905 mini_qdisc_qstats_cpu_drop(miniq);
3906 *ret = NET_XMIT_DROP;
3912 *ret = NET_XMIT_SUCCESS;
3915 case TC_ACT_REDIRECT:
3916 /* No need to push/pop skb's mac_header here on egress! */
3917 skb_do_redirect(skb);
3918 *ret = NET_XMIT_SUCCESS;
3926 #endif /* CONFIG_NET_EGRESS */
3929 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
3930 struct xps_dev_maps *dev_maps, unsigned int tci)
3932 struct xps_map *map;
3933 int queue_index = -1;
3937 tci += netdev_get_prio_tc_map(dev, skb->priority);
3940 map = rcu_dereference(dev_maps->attr_map[tci]);
3943 queue_index = map->queues[0];
3945 queue_index = map->queues[reciprocal_scale(
3946 skb_get_hash(skb), map->len)];
3947 if (unlikely(queue_index >= dev->real_num_tx_queues))
3954 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
3955 struct sk_buff *skb)
3958 struct xps_dev_maps *dev_maps;
3959 struct sock *sk = skb->sk;
3960 int queue_index = -1;
3962 if (!static_key_false(&xps_needed))
3966 if (!static_key_false(&xps_rxqs_needed))
3969 dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
3971 int tci = sk_rx_queue_get(sk);
3973 if (tci >= 0 && tci < dev->num_rx_queues)
3974 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3979 if (queue_index < 0) {
3980 dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
3982 unsigned int tci = skb->sender_cpu - 1;
3984 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
3996 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
3997 struct net_device *sb_dev)
4001 EXPORT_SYMBOL(dev_pick_tx_zero);
4003 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4004 struct net_device *sb_dev)
4006 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4008 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4010 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4011 struct net_device *sb_dev)
4013 struct sock *sk = skb->sk;
4014 int queue_index = sk_tx_queue_get(sk);
4016 sb_dev = sb_dev ? : dev;
4018 if (queue_index < 0 || skb->ooo_okay ||
4019 queue_index >= dev->real_num_tx_queues) {
4020 int new_index = get_xps_queue(dev, sb_dev, skb);
4023 new_index = skb_tx_hash(dev, sb_dev, skb);
4025 if (queue_index != new_index && sk &&
4027 rcu_access_pointer(sk->sk_dst_cache))
4028 sk_tx_queue_set(sk, new_index);
4030 queue_index = new_index;
4035 EXPORT_SYMBOL(netdev_pick_tx);
4037 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4038 struct sk_buff *skb,
4039 struct net_device *sb_dev)
4041 int queue_index = 0;
4044 u32 sender_cpu = skb->sender_cpu - 1;
4046 if (sender_cpu >= (u32)NR_CPUS)
4047 skb->sender_cpu = raw_smp_processor_id() + 1;
4050 if (dev->real_num_tx_queues != 1) {
4051 const struct net_device_ops *ops = dev->netdev_ops;
4053 if (ops->ndo_select_queue)
4054 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4056 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4058 queue_index = netdev_cap_txqueue(dev, queue_index);
4061 skb_set_queue_mapping(skb, queue_index);
4062 return netdev_get_tx_queue(dev, queue_index);
4066 * __dev_queue_xmit - transmit a buffer
4067 * @skb: buffer to transmit
4068 * @sb_dev: suboordinate device used for L2 forwarding offload
4070 * Queue a buffer for transmission to a network device. The caller must
4071 * have set the device and priority and built the buffer before calling
4072 * this function. The function can be called from an interrupt.
4074 * A negative errno code is returned on a failure. A success does not
4075 * guarantee the frame will be transmitted as it may be dropped due
4076 * to congestion or traffic shaping.
4078 * -----------------------------------------------------------------------------------
4079 * I notice this method can also return errors from the queue disciplines,
4080 * including NET_XMIT_DROP, which is a positive value. So, errors can also
4083 * Regardless of the return value, the skb is consumed, so it is currently
4084 * difficult to retry a send to this method. (You can bump the ref count
4085 * before sending to hold a reference for retry if you are careful.)
4087 * When calling this method, interrupts MUST be enabled. This is because
4088 * the BH enable code must have IRQs enabled so that it will not deadlock.
4091 static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4093 struct net_device *dev = skb->dev;
4094 struct netdev_queue *txq;
4099 skb_reset_mac_header(skb);
4100 skb_assert_len(skb);
4102 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4103 __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
4105 /* Disable soft irqs for various locks below. Also
4106 * stops preemption for RCU.
4110 skb_update_prio(skb);
4112 qdisc_pkt_len_init(skb);
4113 #ifdef CONFIG_NET_CLS_ACT
4114 skb->tc_at_ingress = 0;
4115 # ifdef CONFIG_NET_EGRESS
4116 if (static_branch_unlikely(&egress_needed_key)) {
4117 skb = sch_handle_egress(skb, &rc, dev);
4123 /* If device/qdisc don't need skb->dst, release it right now while
4124 * its hot in this cpu cache.
4126 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4131 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4132 q = rcu_dereference_bh(txq->qdisc);
4134 trace_net_dev_queue(skb);
4136 rc = __dev_xmit_skb(skb, q, dev, txq);
4140 /* The device has no queue. Common case for software devices:
4141 * loopback, all the sorts of tunnels...
4143 * Really, it is unlikely that netif_tx_lock protection is necessary
4144 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4146 * However, it is possible, that they rely on protection
4149 * Check this and shot the lock. It is not prone from deadlocks.
4150 *Either shot noqueue qdisc, it is even simpler 8)
4152 if (dev->flags & IFF_UP) {
4153 int cpu = smp_processor_id(); /* ok because BHs are off */
4155 /* Other cpus might concurrently change txq->xmit_lock_owner
4156 * to -1 or to their cpu id, but not to our id.
4158 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4159 if (dev_xmit_recursion())
4160 goto recursion_alert;
4162 skb = validate_xmit_skb(skb, dev, &again);
4166 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4167 HARD_TX_LOCK(dev, txq, cpu);
4169 if (!netif_xmit_stopped(txq)) {
4170 dev_xmit_recursion_inc();
4171 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4172 dev_xmit_recursion_dec();
4173 if (dev_xmit_complete(rc)) {
4174 HARD_TX_UNLOCK(dev, txq);
4178 HARD_TX_UNLOCK(dev, txq);
4179 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4182 /* Recursion is detected! It is possible,
4186 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4192 rcu_read_unlock_bh();
4194 atomic_long_inc(&dev->tx_dropped);
4195 kfree_skb_list(skb);
4198 rcu_read_unlock_bh();
4202 int dev_queue_xmit(struct sk_buff *skb)
4204 return __dev_queue_xmit(skb, NULL);
4206 EXPORT_SYMBOL(dev_queue_xmit);
4208 int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
4210 return __dev_queue_xmit(skb, sb_dev);
4212 EXPORT_SYMBOL(dev_queue_xmit_accel);
4214 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4216 struct net_device *dev = skb->dev;
4217 struct sk_buff *orig_skb = skb;
4218 struct netdev_queue *txq;
4219 int ret = NETDEV_TX_BUSY;
4222 if (unlikely(!netif_running(dev) ||
4223 !netif_carrier_ok(dev)))
4226 skb = validate_xmit_skb_list(skb, dev, &again);
4227 if (skb != orig_skb)
4230 skb_set_queue_mapping(skb, queue_id);
4231 txq = skb_get_tx_queue(dev, skb);
4232 PRANDOM_ADD_NOISE(skb, dev, txq, jiffies);
4236 dev_xmit_recursion_inc();
4237 HARD_TX_LOCK(dev, txq, smp_processor_id());
4238 if (!netif_xmit_frozen_or_drv_stopped(txq))
4239 ret = netdev_start_xmit(skb, dev, txq, false);
4240 HARD_TX_UNLOCK(dev, txq);
4241 dev_xmit_recursion_dec();
4246 atomic_long_inc(&dev->tx_dropped);
4247 kfree_skb_list(skb);
4248 return NET_XMIT_DROP;
4250 EXPORT_SYMBOL(__dev_direct_xmit);
4252 /*************************************************************************
4254 *************************************************************************/
4256 int netdev_max_backlog __read_mostly = 1000;
4257 EXPORT_SYMBOL(netdev_max_backlog);
4259 int netdev_tstamp_prequeue __read_mostly = 1;
4260 int netdev_budget __read_mostly = 300;
4261 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4262 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4263 int weight_p __read_mostly = 64; /* old backlog weight */
4264 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4265 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4266 int dev_rx_weight __read_mostly = 64;
4267 int dev_tx_weight __read_mostly = 64;
4268 /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
4269 int gro_normal_batch __read_mostly = 8;
4271 /* Called with irq disabled */
4272 static inline void ____napi_schedule(struct softnet_data *sd,
4273 struct napi_struct *napi)
4275 list_add_tail(&napi->poll_list, &sd->poll_list);
4276 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4281 /* One global table that all flow-based protocols share. */
4282 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4283 EXPORT_SYMBOL(rps_sock_flow_table);
4284 u32 rps_cpu_mask __read_mostly;
4285 EXPORT_SYMBOL(rps_cpu_mask);
4287 struct static_key_false rps_needed __read_mostly;
4288 EXPORT_SYMBOL(rps_needed);
4289 struct static_key_false rfs_needed __read_mostly;
4290 EXPORT_SYMBOL(rfs_needed);
4292 static struct rps_dev_flow *
4293 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4294 struct rps_dev_flow *rflow, u16 next_cpu)
4296 if (next_cpu < nr_cpu_ids) {
4297 #ifdef CONFIG_RFS_ACCEL
4298 struct netdev_rx_queue *rxqueue;
4299 struct rps_dev_flow_table *flow_table;
4300 struct rps_dev_flow *old_rflow;
4305 /* Should we steer this flow to a different hardware queue? */
4306 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4307 !(dev->features & NETIF_F_NTUPLE))
4309 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4310 if (rxq_index == skb_get_rx_queue(skb))
4313 rxqueue = dev->_rx + rxq_index;
4314 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4317 flow_id = skb_get_hash(skb) & flow_table->mask;
4318 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4319 rxq_index, flow_id);
4323 rflow = &flow_table->flows[flow_id];
4325 if (old_rflow->filter == rflow->filter)
4326 old_rflow->filter = RPS_NO_FILTER;
4330 per_cpu(softnet_data, next_cpu).input_queue_head;
4333 rflow->cpu = next_cpu;
4338 * get_rps_cpu is called from netif_receive_skb and returns the target
4339 * CPU from the RPS map of the receiving queue for a given skb.
4340 * rcu_read_lock must be held on entry.
4342 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4343 struct rps_dev_flow **rflowp)
4345 const struct rps_sock_flow_table *sock_flow_table;
4346 struct netdev_rx_queue *rxqueue = dev->_rx;
4347 struct rps_dev_flow_table *flow_table;
4348 struct rps_map *map;
4353 if (skb_rx_queue_recorded(skb)) {
4354 u16 index = skb_get_rx_queue(skb);
4356 if (unlikely(index >= dev->real_num_rx_queues)) {
4357 WARN_ONCE(dev->real_num_rx_queues > 1,
4358 "%s received packet on queue %u, but number "
4359 "of RX queues is %u\n",
4360 dev->name, index, dev->real_num_rx_queues);
4366 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4368 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4369 map = rcu_dereference(rxqueue->rps_map);
4370 if (!flow_table && !map)
4373 skb_reset_network_header(skb);
4374 hash = skb_get_hash(skb);
4378 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4379 if (flow_table && sock_flow_table) {
4380 struct rps_dev_flow *rflow;
4384 /* First check into global flow table if there is a match */
4385 ident = sock_flow_table->ents[hash & sock_flow_table->mask];
4386 if ((ident ^ hash) & ~rps_cpu_mask)
4389 next_cpu = ident & rps_cpu_mask;
4391 /* OK, now we know there is a match,
4392 * we can look at the local (per receive queue) flow table
4394 rflow = &flow_table->flows[hash & flow_table->mask];
4398 * If the desired CPU (where last recvmsg was done) is
4399 * different from current CPU (one in the rx-queue flow
4400 * table entry), switch if one of the following holds:
4401 * - Current CPU is unset (>= nr_cpu_ids).
4402 * - Current CPU is offline.
4403 * - The current CPU's queue tail has advanced beyond the
4404 * last packet that was enqueued using this table entry.
4405 * This guarantees that all previous packets for the flow
4406 * have been dequeued, thus preserving in order delivery.
4408 if (unlikely(tcpu != next_cpu) &&
4409 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4410 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4411 rflow->last_qtail)) >= 0)) {
4413 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4416 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4426 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4427 if (cpu_online(tcpu)) {
4437 #ifdef CONFIG_RFS_ACCEL
4440 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4441 * @dev: Device on which the filter was set
4442 * @rxq_index: RX queue index
4443 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4444 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4446 * Drivers that implement ndo_rx_flow_steer() should periodically call
4447 * this function for each installed filter and remove the filters for
4448 * which it returns %true.
4450 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4451 u32 flow_id, u16 filter_id)
4453 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4454 struct rps_dev_flow_table *flow_table;
4455 struct rps_dev_flow *rflow;
4460 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4461 if (flow_table && flow_id <= flow_table->mask) {
4462 rflow = &flow_table->flows[flow_id];
4463 cpu = READ_ONCE(rflow->cpu);
4464 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4465 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4466 rflow->last_qtail) <
4467 (int)(10 * flow_table->mask)))
4473 EXPORT_SYMBOL(rps_may_expire_flow);
4475 #endif /* CONFIG_RFS_ACCEL */
4477 /* Called from hardirq (IPI) context */
4478 static void rps_trigger_softirq(void *data)
4480 struct softnet_data *sd = data;
4482 ____napi_schedule(sd, &sd->backlog);
4486 #endif /* CONFIG_RPS */
4489 * Check if this softnet_data structure is another cpu one
4490 * If yes, queue it to our IPI list and return 1
4493 static int rps_ipi_queued(struct softnet_data *sd)
4496 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4499 sd->rps_ipi_next = mysd->rps_ipi_list;
4500 mysd->rps_ipi_list = sd;
4502 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4505 #endif /* CONFIG_RPS */
4509 #ifdef CONFIG_NET_FLOW_LIMIT
4510 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4513 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4515 #ifdef CONFIG_NET_FLOW_LIMIT
4516 struct sd_flow_limit *fl;
4517 struct softnet_data *sd;
4518 unsigned int old_flow, new_flow;
4520 if (qlen < (READ_ONCE(netdev_max_backlog) >> 1))
4523 sd = this_cpu_ptr(&softnet_data);
4526 fl = rcu_dereference(sd->flow_limit);
4528 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4529 old_flow = fl->history[fl->history_head];
4530 fl->history[fl->history_head] = new_flow;
4533 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4535 if (likely(fl->buckets[old_flow]))
4536 fl->buckets[old_flow]--;
4538 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4550 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4551 * queue (may be a remote CPU queue).
4553 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4554 unsigned int *qtail)
4556 struct softnet_data *sd;
4557 unsigned long flags;
4560 sd = &per_cpu(softnet_data, cpu);
4562 local_irq_save(flags);
4565 if (!netif_running(skb->dev))
4567 qlen = skb_queue_len(&sd->input_pkt_queue);
4568 if (qlen <= READ_ONCE(netdev_max_backlog) && !skb_flow_limit(skb, qlen)) {
4571 __skb_queue_tail(&sd->input_pkt_queue, skb);
4572 input_queue_tail_incr_save(sd, qtail);
4574 local_irq_restore(flags);
4575 return NET_RX_SUCCESS;
4578 /* Schedule NAPI for backlog device
4579 * We can use non atomic operation since we own the queue lock
4581 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
4582 if (!rps_ipi_queued(sd))
4583 ____napi_schedule(sd, &sd->backlog);
4592 local_irq_restore(flags);
4594 atomic_long_inc(&skb->dev->rx_dropped);
4599 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4601 struct net_device *dev = skb->dev;
4602 struct netdev_rx_queue *rxqueue;
4606 if (skb_rx_queue_recorded(skb)) {
4607 u16 index = skb_get_rx_queue(skb);
4609 if (unlikely(index >= dev->real_num_rx_queues)) {
4610 WARN_ONCE(dev->real_num_rx_queues > 1,
4611 "%s received packet on queue %u, but number "
4612 "of RX queues is %u\n",
4613 dev->name, index, dev->real_num_rx_queues);
4615 return rxqueue; /* Return first rxqueue */
4622 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4623 struct xdp_buff *xdp,
4624 struct bpf_prog *xdp_prog)
4626 struct netdev_rx_queue *rxqueue;
4627 void *orig_data, *orig_data_end;
4628 u32 metalen, act = XDP_DROP;
4629 __be16 orig_eth_type;
4635 /* Reinjected packets coming from act_mirred or similar should
4636 * not get XDP generic processing.
4638 if (skb_is_redirected(skb))
4641 /* XDP packets must be linear and must have sufficient headroom
4642 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4643 * native XDP provides, thus we need to do it here as well.
4645 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4646 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4647 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4648 int troom = skb->tail + skb->data_len - skb->end;
4650 /* In case we have to go down the path and also linearize,
4651 * then lets do the pskb_expand_head() work just once here.
4653 if (pskb_expand_head(skb,
4654 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4655 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4657 if (skb_linearize(skb))
4661 /* The XDP program wants to see the packet starting at the MAC
4664 mac_len = skb->data - skb_mac_header(skb);
4665 hlen = skb_headlen(skb) + mac_len;
4666 xdp->data = skb->data - mac_len;
4667 xdp->data_meta = xdp->data;
4668 xdp->data_end = xdp->data + hlen;
4669 xdp->data_hard_start = skb->data - skb_headroom(skb);
4671 /* SKB "head" area always have tailroom for skb_shared_info */
4672 xdp->frame_sz = (void *)skb_end_pointer(skb) - xdp->data_hard_start;
4673 xdp->frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4675 orig_data_end = xdp->data_end;
4676 orig_data = xdp->data;
4677 eth = (struct ethhdr *)xdp->data;
4678 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4679 orig_eth_type = eth->h_proto;
4681 rxqueue = netif_get_rxqueue(skb);
4682 xdp->rxq = &rxqueue->xdp_rxq;
4684 act = bpf_prog_run_xdp(xdp_prog, xdp);
4686 /* check if bpf_xdp_adjust_head was used */
4687 off = xdp->data - orig_data;
4690 __skb_pull(skb, off);
4692 __skb_push(skb, -off);
4694 skb->mac_header += off;
4695 skb_reset_network_header(skb);
4698 /* check if bpf_xdp_adjust_tail was used */
4699 off = xdp->data_end - orig_data_end;
4701 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4702 skb->len += off; /* positive on grow, negative on shrink */
4705 /* check if XDP changed eth hdr such SKB needs update */
4706 eth = (struct ethhdr *)xdp->data;
4707 if ((orig_eth_type != eth->h_proto) ||
4708 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4709 __skb_push(skb, ETH_HLEN);
4710 skb->protocol = eth_type_trans(skb, skb->dev);
4716 __skb_push(skb, mac_len);
4719 metalen = xdp->data - xdp->data_meta;
4721 skb_metadata_set(skb, metalen);
4724 bpf_warn_invalid_xdp_action(act);
4727 trace_xdp_exception(skb->dev, xdp_prog, act);
4738 /* When doing generic XDP we have to bypass the qdisc layer and the
4739 * network taps in order to match in-driver-XDP behavior.
4741 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4743 struct net_device *dev = skb->dev;
4744 struct netdev_queue *txq;
4745 bool free_skb = true;
4748 txq = netdev_core_pick_tx(dev, skb, NULL);
4749 cpu = smp_processor_id();
4750 HARD_TX_LOCK(dev, txq, cpu);
4751 if (!netif_xmit_stopped(txq)) {
4752 rc = netdev_start_xmit(skb, dev, txq, 0);
4753 if (dev_xmit_complete(rc))
4756 HARD_TX_UNLOCK(dev, txq);
4758 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4763 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
4765 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
4768 struct xdp_buff xdp;
4772 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
4773 if (act != XDP_PASS) {
4776 err = xdp_do_generic_redirect(skb->dev, skb,
4782 generic_xdp_tx(skb, xdp_prog);
4793 EXPORT_SYMBOL_GPL(do_xdp_generic);
4795 static int netif_rx_internal(struct sk_buff *skb)
4799 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
4801 trace_netif_rx(skb);
4804 if (static_branch_unlikely(&rps_needed)) {
4805 struct rps_dev_flow voidflow, *rflow = &voidflow;
4811 cpu = get_rps_cpu(skb->dev, skb, &rflow);
4813 cpu = smp_processor_id();
4815 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
4824 ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
4831 * netif_rx - post buffer to the network code
4832 * @skb: buffer to post
4834 * This function receives a packet from a device driver and queues it for
4835 * the upper (protocol) levels to process. It always succeeds. The buffer
4836 * may be dropped during processing for congestion control or by the
4840 * NET_RX_SUCCESS (no congestion)
4841 * NET_RX_DROP (packet was dropped)
4845 int netif_rx(struct sk_buff *skb)
4849 trace_netif_rx_entry(skb);
4851 ret = netif_rx_internal(skb);
4852 trace_netif_rx_exit(ret);
4856 EXPORT_SYMBOL(netif_rx);
4858 int netif_rx_ni(struct sk_buff *skb)
4862 trace_netif_rx_ni_entry(skb);
4865 err = netif_rx_internal(skb);
4866 if (local_softirq_pending())
4869 trace_netif_rx_ni_exit(err);
4873 EXPORT_SYMBOL(netif_rx_ni);
4875 int netif_rx_any_context(struct sk_buff *skb)
4878 * If invoked from contexts which do not invoke bottom half
4879 * processing either at return from interrupt or when softrqs are
4880 * reenabled, use netif_rx_ni() which invokes bottomhalf processing
4884 return netif_rx(skb);
4886 return netif_rx_ni(skb);
4888 EXPORT_SYMBOL(netif_rx_any_context);
4890 static __latent_entropy void net_tx_action(struct softirq_action *h)
4892 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
4894 if (sd->completion_queue) {
4895 struct sk_buff *clist;
4897 local_irq_disable();
4898 clist = sd->completion_queue;
4899 sd->completion_queue = NULL;
4903 struct sk_buff *skb = clist;
4905 clist = clist->next;
4907 WARN_ON(refcount_read(&skb->users));
4908 if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
4909 trace_consume_skb(skb);
4911 trace_kfree_skb(skb, net_tx_action);
4913 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
4916 __kfree_skb_defer(skb);
4919 __kfree_skb_flush();
4922 if (sd->output_queue) {
4925 local_irq_disable();
4926 head = sd->output_queue;
4927 sd->output_queue = NULL;
4928 sd->output_queue_tailp = &sd->output_queue;
4934 struct Qdisc *q = head;
4935 spinlock_t *root_lock = NULL;
4937 head = head->next_sched;
4939 /* We need to make sure head->next_sched is read
4940 * before clearing __QDISC_STATE_SCHED
4942 smp_mb__before_atomic();
4944 if (!(q->flags & TCQ_F_NOLOCK)) {
4945 root_lock = qdisc_lock(q);
4946 spin_lock(root_lock);
4947 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
4949 /* There is a synchronize_net() between
4950 * STATE_DEACTIVATED flag being set and
4951 * qdisc_reset()/some_qdisc_is_busy() in
4952 * dev_deactivate(), so we can safely bail out
4953 * early here to avoid data race between
4954 * qdisc_deactivate() and some_qdisc_is_busy()
4955 * for lockless qdisc.
4957 clear_bit(__QDISC_STATE_SCHED, &q->state);
4961 clear_bit(__QDISC_STATE_SCHED, &q->state);
4964 spin_unlock(root_lock);
4970 xfrm_dev_backlog(sd);
4973 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
4974 /* This hook is defined here for ATM LANE */
4975 int (*br_fdb_test_addr_hook)(struct net_device *dev,
4976 unsigned char *addr) __read_mostly;
4977 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
4980 static inline struct sk_buff *
4981 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4982 struct net_device *orig_dev, bool *another)
4984 #ifdef CONFIG_NET_CLS_ACT
4985 struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
4986 struct tcf_result cl_res;
4988 /* If there's at least one ingress present somewhere (so
4989 * we get here via enabled static key), remaining devices
4990 * that are not configured with an ingress qdisc will bail
4997 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5001 qdisc_skb_cb(skb)->pkt_len = skb->len;
5002 qdisc_skb_cb(skb)->mru = 0;
5003 skb->tc_at_ingress = 1;
5004 mini_qdisc_bstats_cpu_update(miniq, skb);
5006 switch (tcf_classify_ingress(skb, miniq->block, miniq->filter_list,
5009 case TC_ACT_RECLASSIFY:
5010 skb->tc_index = TC_H_MIN(cl_res.classid);
5013 mini_qdisc_qstats_cpu_drop(miniq);
5021 case TC_ACT_REDIRECT:
5022 /* skb_mac_header check was done by cls/act_bpf, so
5023 * we can safely push the L2 header back before
5024 * redirecting to another netdev
5026 __skb_push(skb, skb->mac_len);
5027 if (skb_do_redirect(skb) == -EAGAIN) {
5028 __skb_pull(skb, skb->mac_len);
5033 case TC_ACT_CONSUMED:
5038 #endif /* CONFIG_NET_CLS_ACT */
5043 * netdev_is_rx_handler_busy - check if receive handler is registered
5044 * @dev: device to check
5046 * Check if a receive handler is already registered for a given device.
5047 * Return true if there one.
5049 * The caller must hold the rtnl_mutex.
5051 bool netdev_is_rx_handler_busy(struct net_device *dev)
5054 return dev && rtnl_dereference(dev->rx_handler);
5056 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5059 * netdev_rx_handler_register - register receive handler
5060 * @dev: device to register a handler for
5061 * @rx_handler: receive handler to register
5062 * @rx_handler_data: data pointer that is used by rx handler
5064 * Register a receive handler for a device. This handler will then be
5065 * called from __netif_receive_skb. A negative errno code is returned
5068 * The caller must hold the rtnl_mutex.
5070 * For a general description of rx_handler, see enum rx_handler_result.
5072 int netdev_rx_handler_register(struct net_device *dev,
5073 rx_handler_func_t *rx_handler,
5074 void *rx_handler_data)
5076 if (netdev_is_rx_handler_busy(dev))
5079 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5082 /* Note: rx_handler_data must be set before rx_handler */
5083 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5084 rcu_assign_pointer(dev->rx_handler, rx_handler);
5088 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5091 * netdev_rx_handler_unregister - unregister receive handler
5092 * @dev: device to unregister a handler from
5094 * Unregister a receive handler from a device.
5096 * The caller must hold the rtnl_mutex.
5098 void netdev_rx_handler_unregister(struct net_device *dev)
5102 RCU_INIT_POINTER(dev->rx_handler, NULL);
5103 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5104 * section has a guarantee to see a non NULL rx_handler_data
5108 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5110 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5113 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5114 * the special handling of PFMEMALLOC skbs.
5116 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5118 switch (skb->protocol) {
5119 case htons(ETH_P_ARP):
5120 case htons(ETH_P_IP):
5121 case htons(ETH_P_IPV6):
5122 case htons(ETH_P_8021Q):
5123 case htons(ETH_P_8021AD):
5130 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5131 int *ret, struct net_device *orig_dev)
5133 if (nf_hook_ingress_active(skb)) {
5137 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5142 ingress_retval = nf_hook_ingress(skb);
5144 return ingress_retval;
5149 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5150 struct packet_type **ppt_prev)
5152 struct packet_type *ptype, *pt_prev;
5153 rx_handler_func_t *rx_handler;
5154 struct sk_buff *skb = *pskb;
5155 struct net_device *orig_dev;
5156 bool deliver_exact = false;
5157 int ret = NET_RX_DROP;
5160 net_timestamp_check(!READ_ONCE(netdev_tstamp_prequeue), skb);
5162 trace_netif_receive_skb(skb);
5164 orig_dev = skb->dev;
5166 skb_reset_network_header(skb);
5167 if (!skb_transport_header_was_set(skb))
5168 skb_reset_transport_header(skb);
5169 skb_reset_mac_len(skb);
5174 skb->skb_iif = skb->dev->ifindex;
5176 __this_cpu_inc(softnet_data.processed);
5178 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5182 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5185 if (ret2 != XDP_PASS) {
5189 skb_reset_mac_len(skb);
5192 if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5193 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5194 skb = skb_vlan_untag(skb);
5199 if (skb_skip_tc_classify(skb))
5205 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5207 ret = deliver_skb(skb, pt_prev, orig_dev);
5211 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5213 ret = deliver_skb(skb, pt_prev, orig_dev);
5218 #ifdef CONFIG_NET_INGRESS
5219 if (static_branch_unlikely(&ingress_needed_key)) {
5220 bool another = false;
5222 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5229 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5233 skb_reset_redirect(skb);
5235 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5238 if (skb_vlan_tag_present(skb)) {
5240 ret = deliver_skb(skb, pt_prev, orig_dev);
5243 if (vlan_do_receive(&skb))
5245 else if (unlikely(!skb))
5249 rx_handler = rcu_dereference(skb->dev->rx_handler);
5252 ret = deliver_skb(skb, pt_prev, orig_dev);
5255 switch (rx_handler(&skb)) {
5256 case RX_HANDLER_CONSUMED:
5257 ret = NET_RX_SUCCESS;
5259 case RX_HANDLER_ANOTHER:
5261 case RX_HANDLER_EXACT:
5262 deliver_exact = true;
5263 case RX_HANDLER_PASS:
5270 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5272 if (skb_vlan_tag_get_id(skb)) {
5273 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5276 skb->pkt_type = PACKET_OTHERHOST;
5277 } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
5278 skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
5279 /* Outer header is 802.1P with vlan 0, inner header is
5280 * 802.1Q or 802.1AD and vlan_do_receive() above could
5281 * not find vlan dev for vlan id 0.
5283 __vlan_hwaccel_clear_tag(skb);
5284 skb = skb_vlan_untag(skb);
5287 if (vlan_do_receive(&skb))
5288 /* After stripping off 802.1P header with vlan 0
5289 * vlan dev is found for inner header.
5292 else if (unlikely(!skb))
5295 /* We have stripped outer 802.1P vlan 0 header.
5296 * But could not find vlan dev.
5297 * check again for vlan id to set OTHERHOST.
5301 /* Note: we might in the future use prio bits
5302 * and set skb->priority like in vlan_do_receive()
5303 * For the time being, just ignore Priority Code Point
5305 __vlan_hwaccel_clear_tag(skb);
5308 type = skb->protocol;
5310 /* deliver only exact match when indicated */
5311 if (likely(!deliver_exact)) {
5312 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5313 &ptype_base[ntohs(type) &
5317 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5318 &orig_dev->ptype_specific);
5320 if (unlikely(skb->dev != orig_dev)) {
5321 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5322 &skb->dev->ptype_specific);
5326 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5328 *ppt_prev = pt_prev;
5332 atomic_long_inc(&skb->dev->rx_dropped);
5334 atomic_long_inc(&skb->dev->rx_nohandler);
5336 /* Jamal, now you will not able to escape explaining
5337 * me how you were going to use this. :-)
5343 /* The invariant here is that if *ppt_prev is not NULL
5344 * then skb should also be non-NULL.
5346 * Apparently *ppt_prev assignment above holds this invariant due to
5347 * skb dereferencing near it.
5353 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5355 struct net_device *orig_dev = skb->dev;
5356 struct packet_type *pt_prev = NULL;
5359 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5361 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5362 skb->dev, pt_prev, orig_dev);
5367 * netif_receive_skb_core - special purpose version of netif_receive_skb
5368 * @skb: buffer to process
5370 * More direct receive version of netif_receive_skb(). It should
5371 * only be used by callers that have a need to skip RPS and Generic XDP.
5372 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5374 * This function may only be called from softirq context and interrupts
5375 * should be enabled.
5377 * Return values (usually ignored):
5378 * NET_RX_SUCCESS: no congestion
5379 * NET_RX_DROP: packet was dropped
5381 int netif_receive_skb_core(struct sk_buff *skb)
5386 ret = __netif_receive_skb_one_core(skb, false);
5391 EXPORT_SYMBOL(netif_receive_skb_core);
5393 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5394 struct packet_type *pt_prev,
5395 struct net_device *orig_dev)
5397 struct sk_buff *skb, *next;
5401 if (list_empty(head))
5403 if (pt_prev->list_func != NULL)
5404 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5405 ip_list_rcv, head, pt_prev, orig_dev);
5407 list_for_each_entry_safe(skb, next, head, list) {
5408 skb_list_del_init(skb);
5409 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5413 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5415 /* Fast-path assumptions:
5416 * - There is no RX handler.
5417 * - Only one packet_type matches.
5418 * If either of these fails, we will end up doing some per-packet
5419 * processing in-line, then handling the 'last ptype' for the whole
5420 * sublist. This can't cause out-of-order delivery to any single ptype,
5421 * because the 'last ptype' must be constant across the sublist, and all
5422 * other ptypes are handled per-packet.
5424 /* Current (common) ptype of sublist */
5425 struct packet_type *pt_curr = NULL;
5426 /* Current (common) orig_dev of sublist */
5427 struct net_device *od_curr = NULL;
5428 struct list_head sublist;
5429 struct sk_buff *skb, *next;
5431 INIT_LIST_HEAD(&sublist);
5432 list_for_each_entry_safe(skb, next, head, list) {
5433 struct net_device *orig_dev = skb->dev;
5434 struct packet_type *pt_prev = NULL;
5436 skb_list_del_init(skb);
5437 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5440 if (pt_curr != pt_prev || od_curr != orig_dev) {
5441 /* dispatch old sublist */
5442 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5443 /* start new sublist */
5444 INIT_LIST_HEAD(&sublist);
5448 list_add_tail(&skb->list, &sublist);
5451 /* dispatch final sublist */
5452 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5455 static int __netif_receive_skb(struct sk_buff *skb)
5459 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5460 unsigned int noreclaim_flag;
5463 * PFMEMALLOC skbs are special, they should
5464 * - be delivered to SOCK_MEMALLOC sockets only
5465 * - stay away from userspace
5466 * - have bounded memory usage
5468 * Use PF_MEMALLOC as this saves us from propagating the allocation
5469 * context down to all allocation sites.
5471 noreclaim_flag = memalloc_noreclaim_save();
5472 ret = __netif_receive_skb_one_core(skb, true);
5473 memalloc_noreclaim_restore(noreclaim_flag);
5475 ret = __netif_receive_skb_one_core(skb, false);
5480 static void __netif_receive_skb_list(struct list_head *head)
5482 unsigned long noreclaim_flag = 0;
5483 struct sk_buff *skb, *next;
5484 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5486 list_for_each_entry_safe(skb, next, head, list) {
5487 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5488 struct list_head sublist;
5490 /* Handle the previous sublist */
5491 list_cut_before(&sublist, head, &skb->list);
5492 if (!list_empty(&sublist))
5493 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5494 pfmemalloc = !pfmemalloc;
5495 /* See comments in __netif_receive_skb */
5497 noreclaim_flag = memalloc_noreclaim_save();
5499 memalloc_noreclaim_restore(noreclaim_flag);
5502 /* Handle the remaining sublist */
5503 if (!list_empty(head))
5504 __netif_receive_skb_list_core(head, pfmemalloc);
5505 /* Restore pflags */
5507 memalloc_noreclaim_restore(noreclaim_flag);
5510 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5512 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5513 struct bpf_prog *new = xdp->prog;
5519 mutex_lock(&new->aux->used_maps_mutex);
5521 /* generic XDP does not work with DEVMAPs that can
5522 * have a bpf_prog installed on an entry
5524 for (i = 0; i < new->aux->used_map_cnt; i++) {
5525 if (dev_map_can_have_prog(new->aux->used_maps[i]) ||
5526 cpu_map_prog_allowed(new->aux->used_maps[i])) {
5527 mutex_unlock(&new->aux->used_maps_mutex);
5532 mutex_unlock(&new->aux->used_maps_mutex);
5535 switch (xdp->command) {
5536 case XDP_SETUP_PROG:
5537 rcu_assign_pointer(dev->xdp_prog, new);
5542 static_branch_dec(&generic_xdp_needed_key);
5543 } else if (new && !old) {
5544 static_branch_inc(&generic_xdp_needed_key);
5545 dev_disable_lro(dev);
5546 dev_disable_gro_hw(dev);
5558 static int netif_receive_skb_internal(struct sk_buff *skb)
5562 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5564 if (skb_defer_rx_timestamp(skb))
5565 return NET_RX_SUCCESS;
5569 if (static_branch_unlikely(&rps_needed)) {
5570 struct rps_dev_flow voidflow, *rflow = &voidflow;
5571 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5574 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5580 ret = __netif_receive_skb(skb);
5585 static void netif_receive_skb_list_internal(struct list_head *head)
5587 struct sk_buff *skb, *next;
5588 struct list_head sublist;
5590 INIT_LIST_HEAD(&sublist);
5591 list_for_each_entry_safe(skb, next, head, list) {
5592 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5593 skb_list_del_init(skb);
5594 if (!skb_defer_rx_timestamp(skb))
5595 list_add_tail(&skb->list, &sublist);
5597 list_splice_init(&sublist, head);
5601 if (static_branch_unlikely(&rps_needed)) {
5602 list_for_each_entry_safe(skb, next, head, list) {
5603 struct rps_dev_flow voidflow, *rflow = &voidflow;
5604 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5607 /* Will be handled, remove from list */
5608 skb_list_del_init(skb);
5609 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5614 __netif_receive_skb_list(head);
5619 * netif_receive_skb - process receive buffer from network
5620 * @skb: buffer to process
5622 * netif_receive_skb() is the main receive data processing function.
5623 * It always succeeds. The buffer may be dropped during processing
5624 * for congestion control or by the protocol layers.
5626 * This function may only be called from softirq context and interrupts
5627 * should be enabled.
5629 * Return values (usually ignored):
5630 * NET_RX_SUCCESS: no congestion
5631 * NET_RX_DROP: packet was dropped
5633 int netif_receive_skb(struct sk_buff *skb)
5637 trace_netif_receive_skb_entry(skb);
5639 ret = netif_receive_skb_internal(skb);
5640 trace_netif_receive_skb_exit(ret);
5644 EXPORT_SYMBOL(netif_receive_skb);
5647 * netif_receive_skb_list - process many receive buffers from network
5648 * @head: list of skbs to process.
5650 * Since return value of netif_receive_skb() is normally ignored, and
5651 * wouldn't be meaningful for a list, this function returns void.
5653 * This function may only be called from softirq context and interrupts
5654 * should be enabled.
5656 void netif_receive_skb_list(struct list_head *head)
5658 struct sk_buff *skb;
5660 if (list_empty(head))
5662 if (trace_netif_receive_skb_list_entry_enabled()) {
5663 list_for_each_entry(skb, head, list)
5664 trace_netif_receive_skb_list_entry(skb);
5666 netif_receive_skb_list_internal(head);
5667 trace_netif_receive_skb_list_exit(0);
5669 EXPORT_SYMBOL(netif_receive_skb_list);
5671 static DEFINE_PER_CPU(struct work_struct, flush_works);
5673 /* Network device is going away, flush any packets still pending */
5674 static void flush_backlog(struct work_struct *work)
5676 struct sk_buff *skb, *tmp;
5677 struct softnet_data *sd;
5680 sd = this_cpu_ptr(&softnet_data);
5682 local_irq_disable();
5684 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5685 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5686 __skb_unlink(skb, &sd->input_pkt_queue);
5687 dev_kfree_skb_irq(skb);
5688 input_queue_head_incr(sd);
5694 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5695 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5696 __skb_unlink(skb, &sd->process_queue);
5698 input_queue_head_incr(sd);
5704 static bool flush_required(int cpu)
5706 #if IS_ENABLED(CONFIG_RPS)
5707 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5710 local_irq_disable();
5713 /* as insertion into process_queue happens with the rps lock held,
5714 * process_queue access may race only with dequeue
5716 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5717 !skb_queue_empty_lockless(&sd->process_queue);
5723 /* without RPS we can't safely check input_pkt_queue: during a
5724 * concurrent remote skb_queue_splice() we can detect as empty both
5725 * input_pkt_queue and process_queue even if the latter could end-up
5726 * containing a lot of packets.
5731 static void flush_all_backlogs(void)
5733 static cpumask_t flush_cpus;
5736 /* since we are under rtnl lock protection we can use static data
5737 * for the cpumask and avoid allocating on stack the possibly
5744 cpumask_clear(&flush_cpus);
5745 for_each_online_cpu(cpu) {
5746 if (flush_required(cpu)) {
5747 queue_work_on(cpu, system_highpri_wq,
5748 per_cpu_ptr(&flush_works, cpu));
5749 cpumask_set_cpu(cpu, &flush_cpus);
5753 /* we can have in flight packet[s] on the cpus we are not flushing,
5754 * synchronize_net() in unregister_netdevice_many() will take care of
5757 for_each_cpu(cpu, &flush_cpus)
5758 flush_work(per_cpu_ptr(&flush_works, cpu));
5763 /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
5764 static void gro_normal_list(struct napi_struct *napi)
5766 if (!napi->rx_count)
5768 netif_receive_skb_list_internal(&napi->rx_list);
5769 INIT_LIST_HEAD(&napi->rx_list);
5773 /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
5774 * pass the whole batch up to the stack.
5776 static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb, int segs)
5778 list_add_tail(&skb->list, &napi->rx_list);
5779 napi->rx_count += segs;
5780 if (napi->rx_count >= gro_normal_batch)
5781 gro_normal_list(napi);
5784 INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
5785 INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
5786 static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
5788 struct packet_offload *ptype;
5789 __be16 type = skb->protocol;
5790 struct list_head *head = &offload_base;
5793 BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
5795 if (NAPI_GRO_CB(skb)->count == 1) {
5796 skb_shinfo(skb)->gso_size = 0;
5801 list_for_each_entry_rcu(ptype, head, list) {
5802 if (ptype->type != type || !ptype->callbacks.gro_complete)
5805 err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
5806 ipv6_gro_complete, inet_gro_complete,
5813 WARN_ON(&ptype->list == head);
5815 return NET_RX_SUCCESS;
5819 gro_normal_one(napi, skb, NAPI_GRO_CB(skb)->count);
5820 return NET_RX_SUCCESS;
5823 static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
5826 struct list_head *head = &napi->gro_hash[index].list;
5827 struct sk_buff *skb, *p;
5829 list_for_each_entry_safe_reverse(skb, p, head, list) {
5830 if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
5832 skb_list_del_init(skb);
5833 napi_gro_complete(napi, skb);
5834 napi->gro_hash[index].count--;
5837 if (!napi->gro_hash[index].count)
5838 __clear_bit(index, &napi->gro_bitmask);
5841 /* napi->gro_hash[].list contains packets ordered by age.
5842 * youngest packets at the head of it.
5843 * Complete skbs in reverse order to reduce latencies.
5845 void napi_gro_flush(struct napi_struct *napi, bool flush_old)
5847 unsigned long bitmask = napi->gro_bitmask;
5848 unsigned int i, base = ~0U;
5850 while ((i = ffs(bitmask)) != 0) {
5853 __napi_gro_flush_chain(napi, base, flush_old);
5856 EXPORT_SYMBOL(napi_gro_flush);
5858 static struct list_head *gro_list_prepare(struct napi_struct *napi,
5859 struct sk_buff *skb)
5861 unsigned int maclen = skb->dev->hard_header_len;
5862 u32 hash = skb_get_hash_raw(skb);
5863 struct list_head *head;
5866 head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
5867 list_for_each_entry(p, head, list) {
5868 unsigned long diffs;
5870 NAPI_GRO_CB(p)->flush = 0;
5872 if (hash != skb_get_hash_raw(p)) {
5873 NAPI_GRO_CB(p)->same_flow = 0;
5877 diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
5878 diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
5879 if (skb_vlan_tag_present(p))
5880 diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
5881 diffs |= skb_metadata_dst_cmp(p, skb);
5882 diffs |= skb_metadata_differs(p, skb);
5883 if (maclen == ETH_HLEN)
5884 diffs |= compare_ether_header(skb_mac_header(p),
5885 skb_mac_header(skb));
5887 diffs = memcmp(skb_mac_header(p),
5888 skb_mac_header(skb),
5891 diffs |= skb_get_nfct(p) ^ skb_get_nfct(skb);
5892 #if IS_ENABLED(CONFIG_SKB_EXTENSIONS) && IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
5894 struct tc_skb_ext *skb_ext = skb_ext_find(skb, TC_SKB_EXT);
5895 struct tc_skb_ext *p_ext = skb_ext_find(p, TC_SKB_EXT);
5897 diffs |= (!!p_ext) ^ (!!skb_ext);
5898 if (!diffs && unlikely(skb_ext))
5899 diffs |= p_ext->chain ^ skb_ext->chain;
5903 NAPI_GRO_CB(p)->same_flow = !diffs;
5909 static inline void skb_gro_reset_offset(struct sk_buff *skb, u32 nhoff)
5911 const struct skb_shared_info *pinfo = skb_shinfo(skb);
5912 const skb_frag_t *frag0 = &pinfo->frags[0];
5914 NAPI_GRO_CB(skb)->data_offset = 0;
5915 NAPI_GRO_CB(skb)->frag0 = NULL;
5916 NAPI_GRO_CB(skb)->frag0_len = 0;
5918 if (!skb_headlen(skb) && pinfo->nr_frags &&
5919 !PageHighMem(skb_frag_page(frag0)) &&
5920 (!NET_IP_ALIGN || !((skb_frag_off(frag0) + nhoff) & 3))) {
5921 NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
5922 NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
5923 skb_frag_size(frag0),
5924 skb->end - skb->tail);
5928 static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
5930 struct skb_shared_info *pinfo = skb_shinfo(skb);
5932 BUG_ON(skb->end - skb->tail < grow);
5934 memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
5936 skb->data_len -= grow;
5939 skb_frag_off_add(&pinfo->frags[0], grow);
5940 skb_frag_size_sub(&pinfo->frags[0], grow);
5942 if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
5943 skb_frag_unref(skb, 0);
5944 memmove(pinfo->frags, pinfo->frags + 1,
5945 --pinfo->nr_frags * sizeof(pinfo->frags[0]));
5949 static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
5951 struct sk_buff *oldest;
5953 oldest = list_last_entry(head, struct sk_buff, list);
5955 /* We are called with head length >= MAX_GRO_SKBS, so this is
5958 if (WARN_ON_ONCE(!oldest))
5961 /* Do not adjust napi->gro_hash[].count, caller is adding a new
5964 skb_list_del_init(oldest);
5965 napi_gro_complete(napi, oldest);
5968 INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
5970 INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
5972 static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
5974 u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
5975 struct list_head *head = &offload_base;
5976 struct packet_offload *ptype;
5977 __be16 type = skb->protocol;
5978 struct list_head *gro_head;
5979 struct sk_buff *pp = NULL;
5980 enum gro_result ret;
5984 if (netif_elide_gro(skb->dev))
5987 gro_head = gro_list_prepare(napi, skb);
5990 list_for_each_entry_rcu(ptype, head, list) {
5991 if (ptype->type != type || !ptype->callbacks.gro_receive)
5994 skb_set_network_header(skb, skb_gro_offset(skb));
5995 skb_reset_mac_len(skb);
5996 NAPI_GRO_CB(skb)->same_flow = 0;
5997 NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
5998 NAPI_GRO_CB(skb)->free = 0;
5999 NAPI_GRO_CB(skb)->encap_mark = 0;
6000 NAPI_GRO_CB(skb)->recursion_counter = 0;
6001 NAPI_GRO_CB(skb)->is_fou = 0;
6002 NAPI_GRO_CB(skb)->is_atomic = 1;
6003 NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
6005 /* Setup for GRO checksum validation */
6006 switch (skb->ip_summed) {
6007 case CHECKSUM_COMPLETE:
6008 NAPI_GRO_CB(skb)->csum = skb->csum;
6009 NAPI_GRO_CB(skb)->csum_valid = 1;
6010 NAPI_GRO_CB(skb)->csum_cnt = 0;
6012 case CHECKSUM_UNNECESSARY:
6013 NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
6014 NAPI_GRO_CB(skb)->csum_valid = 0;
6017 NAPI_GRO_CB(skb)->csum_cnt = 0;
6018 NAPI_GRO_CB(skb)->csum_valid = 0;
6021 pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
6022 ipv6_gro_receive, inet_gro_receive,
6028 if (&ptype->list == head)
6031 if (PTR_ERR(pp) == -EINPROGRESS) {
6036 same_flow = NAPI_GRO_CB(skb)->same_flow;
6037 ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
6040 skb_list_del_init(pp);
6041 napi_gro_complete(napi, pp);
6042 napi->gro_hash[hash].count--;
6048 if (NAPI_GRO_CB(skb)->flush)
6051 if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
6052 gro_flush_oldest(napi, gro_head);
6054 napi->gro_hash[hash].count++;
6056 NAPI_GRO_CB(skb)->count = 1;
6057 NAPI_GRO_CB(skb)->age = jiffies;
6058 NAPI_GRO_CB(skb)->last = skb;
6059 skb_shinfo(skb)->gso_size = skb_gro_len(skb);
6060 list_add(&skb->list, gro_head);
6064 grow = skb_gro_offset(skb) - skb_headlen(skb);
6066 gro_pull_from_frag0(skb, grow);
6068 if (napi->gro_hash[hash].count) {
6069 if (!test_bit(hash, &napi->gro_bitmask))
6070 __set_bit(hash, &napi->gro_bitmask);
6071 } else if (test_bit(hash, &napi->gro_bitmask)) {
6072 __clear_bit(hash, &napi->gro_bitmask);
6082 struct packet_offload *gro_find_receive_by_type(__be16 type)
6084 struct list_head *offload_head = &offload_base;
6085 struct packet_offload *ptype;
6087 list_for_each_entry_rcu(ptype, offload_head, list) {
6088 if (ptype->type != type || !ptype->callbacks.gro_receive)
6094 EXPORT_SYMBOL(gro_find_receive_by_type);
6096 struct packet_offload *gro_find_complete_by_type(__be16 type)
6098 struct list_head *offload_head = &offload_base;
6099 struct packet_offload *ptype;
6101 list_for_each_entry_rcu(ptype, offload_head, list) {
6102 if (ptype->type != type || !ptype->callbacks.gro_complete)
6108 EXPORT_SYMBOL(gro_find_complete_by_type);
6110 static void napi_skb_free_stolen_head(struct sk_buff *skb)
6114 kmem_cache_free(skbuff_head_cache, skb);
6117 static gro_result_t napi_skb_finish(struct napi_struct *napi,
6118 struct sk_buff *skb,
6123 gro_normal_one(napi, skb, 1);
6130 case GRO_MERGED_FREE:
6131 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6132 napi_skb_free_stolen_head(skb);
6146 gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
6150 skb_mark_napi_id(skb, napi);
6151 trace_napi_gro_receive_entry(skb);
6153 skb_gro_reset_offset(skb, 0);
6155 ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
6156 trace_napi_gro_receive_exit(ret);
6160 EXPORT_SYMBOL(napi_gro_receive);
6162 static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
6164 if (unlikely(skb->pfmemalloc)) {
6168 __skb_pull(skb, skb_headlen(skb));
6169 /* restore the reserve we had after netdev_alloc_skb_ip_align() */
6170 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
6171 __vlan_hwaccel_clear_tag(skb);
6172 skb->dev = napi->dev;
6175 /* eth_type_trans() assumes pkt_type is PACKET_HOST */
6176 skb->pkt_type = PACKET_HOST;
6178 skb->encapsulation = 0;
6179 skb_shinfo(skb)->gso_type = 0;
6180 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6187 struct sk_buff *napi_get_frags(struct napi_struct *napi)
6189 struct sk_buff *skb = napi->skb;
6192 skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
6195 skb_mark_napi_id(skb, napi);
6200 EXPORT_SYMBOL(napi_get_frags);
6202 static gro_result_t napi_frags_finish(struct napi_struct *napi,
6203 struct sk_buff *skb,
6209 __skb_push(skb, ETH_HLEN);
6210 skb->protocol = eth_type_trans(skb, skb->dev);
6211 if (ret == GRO_NORMAL)
6212 gro_normal_one(napi, skb, 1);
6216 napi_reuse_skb(napi, skb);
6219 case GRO_MERGED_FREE:
6220 if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
6221 napi_skb_free_stolen_head(skb);
6223 napi_reuse_skb(napi, skb);
6234 /* Upper GRO stack assumes network header starts at gro_offset=0
6235 * Drivers could call both napi_gro_frags() and napi_gro_receive()
6236 * We copy ethernet header into skb->data to have a common layout.
6238 static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
6240 struct sk_buff *skb = napi->skb;
6241 const struct ethhdr *eth;
6242 unsigned int hlen = sizeof(*eth);
6246 skb_reset_mac_header(skb);
6247 skb_gro_reset_offset(skb, hlen);
6249 if (unlikely(skb_gro_header_hard(skb, hlen))) {
6250 eth = skb_gro_header_slow(skb, hlen, 0);
6251 if (unlikely(!eth)) {
6252 net_warn_ratelimited("%s: dropping impossible skb from %s\n",
6253 __func__, napi->dev->name);
6254 napi_reuse_skb(napi, skb);
6258 eth = (const struct ethhdr *)skb->data;
6259 gro_pull_from_frag0(skb, hlen);
6260 NAPI_GRO_CB(skb)->frag0 += hlen;
6261 NAPI_GRO_CB(skb)->frag0_len -= hlen;
6263 __skb_pull(skb, hlen);
6266 * This works because the only protocols we care about don't require
6268 * We'll fix it up properly in napi_frags_finish()
6270 skb->protocol = eth->h_proto;
6275 gro_result_t napi_gro_frags(struct napi_struct *napi)
6278 struct sk_buff *skb = napi_frags_skb(napi);
6283 trace_napi_gro_frags_entry(skb);
6285 ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
6286 trace_napi_gro_frags_exit(ret);
6290 EXPORT_SYMBOL(napi_gro_frags);
6292 /* Compute the checksum from gro_offset and return the folded value
6293 * after adding in any pseudo checksum.
6295 __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
6300 wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
6302 /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
6303 sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
6304 /* See comments in __skb_checksum_complete(). */
6306 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
6307 !skb->csum_complete_sw)
6308 netdev_rx_csum_fault(skb->dev, skb);
6311 NAPI_GRO_CB(skb)->csum = wsum;
6312 NAPI_GRO_CB(skb)->csum_valid = 1;
6316 EXPORT_SYMBOL(__skb_gro_checksum_complete);
6318 static void net_rps_send_ipi(struct softnet_data *remsd)
6322 struct softnet_data *next = remsd->rps_ipi_next;
6324 if (cpu_online(remsd->cpu))
6325 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6332 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6333 * Note: called with local irq disabled, but exits with local irq enabled.
6335 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6338 struct softnet_data *remsd = sd->rps_ipi_list;
6341 sd->rps_ipi_list = NULL;
6345 /* Send pending IPI's to kick RPS processing on remote cpus. */
6346 net_rps_send_ipi(remsd);
6352 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6355 return sd->rps_ipi_list != NULL;
6361 static int process_backlog(struct napi_struct *napi, int quota)
6363 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6367 /* Check if we have pending ipi, its better to send them now,
6368 * not waiting net_rx_action() end.
6370 if (sd_has_rps_ipi_waiting(sd)) {
6371 local_irq_disable();
6372 net_rps_action_and_irq_enable(sd);
6375 napi->weight = READ_ONCE(dev_rx_weight);
6377 struct sk_buff *skb;
6379 while ((skb = __skb_dequeue(&sd->process_queue))) {
6381 __netif_receive_skb(skb);
6383 input_queue_head_incr(sd);
6384 if (++work >= quota)
6389 local_irq_disable();
6391 if (skb_queue_empty(&sd->input_pkt_queue)) {
6393 * Inline a custom version of __napi_complete().
6394 * only current cpu owns and manipulates this napi,
6395 * and NAPI_STATE_SCHED is the only possible flag set
6397 * We can use a plain write instead of clear_bit(),
6398 * and we dont need an smp_mb() memory barrier.
6403 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6404 &sd->process_queue);
6414 * __napi_schedule - schedule for receive
6415 * @n: entry to schedule
6417 * The entry's receive function will be scheduled to run.
6418 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6420 void __napi_schedule(struct napi_struct *n)
6422 unsigned long flags;
6424 local_irq_save(flags);
6425 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6426 local_irq_restore(flags);
6428 EXPORT_SYMBOL(__napi_schedule);
6431 * napi_schedule_prep - check if napi can be scheduled
6434 * Test if NAPI routine is already running, and if not mark
6435 * it as running. This is used as a condition variable to
6436 * insure only one NAPI poll instance runs. We also make
6437 * sure there is no pending NAPI disable.
6439 bool napi_schedule_prep(struct napi_struct *n)
6441 unsigned long val, new;
6444 val = READ_ONCE(n->state);
6445 if (unlikely(val & NAPIF_STATE_DISABLE))
6447 new = val | NAPIF_STATE_SCHED;
6449 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6450 * This was suggested by Alexander Duyck, as compiler
6451 * emits better code than :
6452 * if (val & NAPIF_STATE_SCHED)
6453 * new |= NAPIF_STATE_MISSED;
6455 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6457 } while (cmpxchg(&n->state, val, new) != val);
6459 return !(val & NAPIF_STATE_SCHED);
6461 EXPORT_SYMBOL(napi_schedule_prep);
6464 * __napi_schedule_irqoff - schedule for receive
6465 * @n: entry to schedule
6467 * Variant of __napi_schedule() assuming hard irqs are masked.
6469 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6470 * because the interrupt disabled assumption might not be true
6471 * due to force-threaded interrupts and spinlock substitution.
6473 void __napi_schedule_irqoff(struct napi_struct *n)
6475 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6476 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6480 EXPORT_SYMBOL(__napi_schedule_irqoff);
6482 bool napi_complete_done(struct napi_struct *n, int work_done)
6484 unsigned long flags, val, new, timeout = 0;
6488 * 1) Don't let napi dequeue from the cpu poll list
6489 * just in case its running on a different cpu.
6490 * 2) If we are busy polling, do nothing here, we have
6491 * the guarantee we will be called later.
6493 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6494 NAPIF_STATE_IN_BUSY_POLL)))
6499 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6500 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6502 if (n->defer_hard_irqs_count > 0) {
6503 n->defer_hard_irqs_count--;
6504 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6508 if (n->gro_bitmask) {
6509 /* When the NAPI instance uses a timeout and keeps postponing
6510 * it, we need to bound somehow the time packets are kept in
6513 napi_gro_flush(n, !!timeout);
6518 if (unlikely(!list_empty(&n->poll_list))) {
6519 /* If n->poll_list is not empty, we need to mask irqs */
6520 local_irq_save(flags);
6521 list_del_init(&n->poll_list);
6522 local_irq_restore(flags);
6526 val = READ_ONCE(n->state);
6528 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6530 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
6532 /* If STATE_MISSED was set, leave STATE_SCHED set,
6533 * because we will call napi->poll() one more time.
6534 * This C code was suggested by Alexander Duyck to help gcc.
6536 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6538 } while (cmpxchg(&n->state, val, new) != val);
6540 if (unlikely(val & NAPIF_STATE_MISSED)) {
6546 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6547 HRTIMER_MODE_REL_PINNED);
6550 EXPORT_SYMBOL(napi_complete_done);
6552 /* must be called under rcu_read_lock(), as we dont take a reference */
6553 static struct napi_struct *napi_by_id(unsigned int napi_id)
6555 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6556 struct napi_struct *napi;
6558 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6559 if (napi->napi_id == napi_id)
6565 #if defined(CONFIG_NET_RX_BUSY_POLL)
6567 #define BUSY_POLL_BUDGET 8
6569 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
6573 /* Busy polling means there is a high chance device driver hard irq
6574 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6575 * set in napi_schedule_prep().
6576 * Since we are about to call napi->poll() once more, we can safely
6577 * clear NAPI_STATE_MISSED.
6579 * Note: x86 could use a single "lock and ..." instruction
6580 * to perform these two clear_bit()
6582 clear_bit(NAPI_STATE_MISSED, &napi->state);
6583 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6587 /* All we really want here is to re-enable device interrupts.
6588 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6590 rc = napi->poll(napi, BUSY_POLL_BUDGET);
6591 /* We can't gro_normal_list() here, because napi->poll() might have
6592 * rearmed the napi (napi_complete_done()) in which case it could
6593 * already be running on another CPU.
6595 trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
6596 netpoll_poll_unlock(have_poll_lock);
6597 if (rc == BUSY_POLL_BUDGET) {
6598 /* As the whole budget was spent, we still own the napi so can
6599 * safely handle the rx_list.
6601 gro_normal_list(napi);
6602 __napi_schedule(napi);
6607 void napi_busy_loop(unsigned int napi_id,
6608 bool (*loop_end)(void *, unsigned long),
6611 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6612 int (*napi_poll)(struct napi_struct *napi, int budget);
6613 void *have_poll_lock = NULL;
6614 struct napi_struct *napi;
6621 napi = napi_by_id(napi_id);
6631 unsigned long val = READ_ONCE(napi->state);
6633 /* If multiple threads are competing for this napi,
6634 * we avoid dirtying napi->state as much as we can.
6636 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6637 NAPIF_STATE_IN_BUSY_POLL))
6639 if (cmpxchg(&napi->state, val,
6640 val | NAPIF_STATE_IN_BUSY_POLL |
6641 NAPIF_STATE_SCHED) != val)
6643 have_poll_lock = netpoll_poll_lock(napi);
6644 napi_poll = napi->poll;
6646 work = napi_poll(napi, BUSY_POLL_BUDGET);
6647 trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
6648 gro_normal_list(napi);
6651 __NET_ADD_STATS(dev_net(napi->dev),
6652 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6655 if (!loop_end || loop_end(loop_end_arg, start_time))
6658 if (unlikely(need_resched())) {
6660 busy_poll_stop(napi, have_poll_lock);
6664 if (loop_end(loop_end_arg, start_time))
6671 busy_poll_stop(napi, have_poll_lock);
6676 EXPORT_SYMBOL(napi_busy_loop);
6678 #endif /* CONFIG_NET_RX_BUSY_POLL */
6680 static void napi_hash_add(struct napi_struct *napi)
6682 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6685 spin_lock(&napi_hash_lock);
6687 /* 0..NR_CPUS range is reserved for sender_cpu use */
6689 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6690 napi_gen_id = MIN_NAPI_ID;
6691 } while (napi_by_id(napi_gen_id));
6692 napi->napi_id = napi_gen_id;
6694 hlist_add_head_rcu(&napi->napi_hash_node,
6695 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6697 spin_unlock(&napi_hash_lock);
6700 /* Warning : caller is responsible to make sure rcu grace period
6701 * is respected before freeing memory containing @napi
6703 static void napi_hash_del(struct napi_struct *napi)
6705 spin_lock(&napi_hash_lock);
6707 hlist_del_init_rcu(&napi->napi_hash_node);
6709 spin_unlock(&napi_hash_lock);
6712 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6714 struct napi_struct *napi;
6716 napi = container_of(timer, struct napi_struct, timer);
6718 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6719 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6721 if (!napi_disable_pending(napi) &&
6722 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
6723 __napi_schedule_irqoff(napi);
6725 return HRTIMER_NORESTART;
6728 static void init_gro_hash(struct napi_struct *napi)
6732 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6733 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6734 napi->gro_hash[i].count = 0;
6736 napi->gro_bitmask = 0;
6739 void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
6740 int (*poll)(struct napi_struct *, int), int weight)
6742 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6745 INIT_LIST_HEAD(&napi->poll_list);
6746 INIT_HLIST_NODE(&napi->napi_hash_node);
6747 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6748 napi->timer.function = napi_watchdog;
6749 init_gro_hash(napi);
6751 INIT_LIST_HEAD(&napi->rx_list);
6754 if (weight > NAPI_POLL_WEIGHT)
6755 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6757 napi->weight = weight;
6759 #ifdef CONFIG_NETPOLL
6760 napi->poll_owner = -1;
6762 set_bit(NAPI_STATE_SCHED, &napi->state);
6763 set_bit(NAPI_STATE_NPSVC, &napi->state);
6764 list_add_rcu(&napi->dev_list, &dev->napi_list);
6765 napi_hash_add(napi);
6767 EXPORT_SYMBOL(netif_napi_add);
6769 void napi_disable(struct napi_struct *n)
6772 set_bit(NAPI_STATE_DISABLE, &n->state);
6774 while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
6776 while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
6779 hrtimer_cancel(&n->timer);
6781 clear_bit(NAPI_STATE_DISABLE, &n->state);
6783 EXPORT_SYMBOL(napi_disable);
6785 static void flush_gro_hash(struct napi_struct *napi)
6789 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6790 struct sk_buff *skb, *n;
6792 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6794 napi->gro_hash[i].count = 0;
6798 /* Must be called in process context */
6799 void __netif_napi_del(struct napi_struct *napi)
6801 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6804 napi_hash_del(napi);
6805 list_del_rcu(&napi->dev_list);
6806 napi_free_frags(napi);
6808 flush_gro_hash(napi);
6809 napi->gro_bitmask = 0;
6811 EXPORT_SYMBOL(__netif_napi_del);
6813 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6818 list_del_init(&n->poll_list);
6820 have = netpoll_poll_lock(n);
6824 /* This NAPI_STATE_SCHED test is for avoiding a race
6825 * with netpoll's poll_napi(). Only the entity which
6826 * obtains the lock and sees NAPI_STATE_SCHED set will
6827 * actually make the ->poll() call. Therefore we avoid
6828 * accidentally calling ->poll() when NAPI is not scheduled.
6831 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6832 work = n->poll(n, weight);
6833 trace_napi_poll(n, work, weight);
6836 if (unlikely(work > weight))
6837 pr_err_once("NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6838 n->poll, work, weight);
6840 if (likely(work < weight))
6843 /* Drivers must not modify the NAPI state if they
6844 * consume the entire weight. In such cases this code
6845 * still "owns" the NAPI instance and therefore can
6846 * move the instance around on the list at-will.
6848 if (unlikely(napi_disable_pending(n))) {
6853 if (n->gro_bitmask) {
6854 /* flush too old packets
6855 * If HZ < 1000, flush all packets.
6857 napi_gro_flush(n, HZ >= 1000);
6862 /* Some drivers may have called napi_schedule
6863 * prior to exhausting their budget.
6865 if (unlikely(!list_empty(&n->poll_list))) {
6866 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6867 n->dev ? n->dev->name : "backlog");
6871 list_add_tail(&n->poll_list, repoll);
6874 netpoll_poll_unlock(have);
6879 static __latent_entropy void net_rx_action(struct softirq_action *h)
6881 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6882 unsigned long time_limit = jiffies +
6883 usecs_to_jiffies(READ_ONCE(netdev_budget_usecs));
6884 int budget = READ_ONCE(netdev_budget);
6888 local_irq_disable();
6889 list_splice_init(&sd->poll_list, &list);
6893 struct napi_struct *n;
6895 if (list_empty(&list)) {
6896 if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
6901 n = list_first_entry(&list, struct napi_struct, poll_list);
6902 budget -= napi_poll(n, &repoll);
6904 /* If softirq window is exhausted then punt.
6905 * Allow this to run for 2 jiffies since which will allow
6906 * an average latency of 1.5/HZ.
6908 if (unlikely(budget <= 0 ||
6909 time_after_eq(jiffies, time_limit))) {
6915 local_irq_disable();
6917 list_splice_tail_init(&sd->poll_list, &list);
6918 list_splice_tail(&repoll, &list);
6919 list_splice(&list, &sd->poll_list);
6920 if (!list_empty(&sd->poll_list))
6921 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6923 net_rps_action_and_irq_enable(sd);
6925 __kfree_skb_flush();
6928 struct netdev_adjacent {
6929 struct net_device *dev;
6931 /* upper master flag, there can only be one master device per list */
6934 /* lookup ignore flag */
6937 /* counter for the number of times this device was added to us */
6940 /* private field for the users */
6943 struct list_head list;
6944 struct rcu_head rcu;
6947 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6948 struct list_head *adj_list)
6950 struct netdev_adjacent *adj;
6952 list_for_each_entry(adj, adj_list, list) {
6953 if (adj->dev == adj_dev)
6959 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6960 struct netdev_nested_priv *priv)
6962 struct net_device *dev = (struct net_device *)priv->data;
6964 return upper_dev == dev;
6968 * netdev_has_upper_dev - Check if device is linked to an upper device
6970 * @upper_dev: upper device to check
6972 * Find out if a device is linked to specified upper device and return true
6973 * in case it is. Note that this checks only immediate upper device,
6974 * not through a complete stack of devices. The caller must hold the RTNL lock.
6976 bool netdev_has_upper_dev(struct net_device *dev,
6977 struct net_device *upper_dev)
6979 struct netdev_nested_priv priv = {
6980 .data = (void *)upper_dev,
6985 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6988 EXPORT_SYMBOL(netdev_has_upper_dev);
6991 * netdev_has_upper_dev_all - Check if device is linked to an upper device
6993 * @upper_dev: upper device to check
6995 * Find out if a device is linked to specified upper device and return true
6996 * in case it is. Note that this checks the entire upper device chain.
6997 * The caller must hold rcu lock.
7000 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
7001 struct net_device *upper_dev)
7003 struct netdev_nested_priv priv = {
7004 .data = (void *)upper_dev,
7007 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7010 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
7013 * netdev_has_any_upper_dev - Check if device is linked to some device
7016 * Find out if a device is linked to an upper device and return true in case
7017 * it is. The caller must hold the RTNL lock.
7019 bool netdev_has_any_upper_dev(struct net_device *dev)
7023 return !list_empty(&dev->adj_list.upper);
7025 EXPORT_SYMBOL(netdev_has_any_upper_dev);
7028 * netdev_master_upper_dev_get - Get master upper device
7031 * Find a master upper device and return pointer to it or NULL in case
7032 * it's not there. The caller must hold the RTNL lock.
7034 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
7036 struct netdev_adjacent *upper;
7040 if (list_empty(&dev->adj_list.upper))
7043 upper = list_first_entry(&dev->adj_list.upper,
7044 struct netdev_adjacent, list);
7045 if (likely(upper->master))
7049 EXPORT_SYMBOL(netdev_master_upper_dev_get);
7051 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
7053 struct netdev_adjacent *upper;
7057 if (list_empty(&dev->adj_list.upper))
7060 upper = list_first_entry(&dev->adj_list.upper,
7061 struct netdev_adjacent, list);
7062 if (likely(upper->master) && !upper->ignore)
7068 * netdev_has_any_lower_dev - Check if device is linked to some device
7071 * Find out if a device is linked to a lower device and return true in case
7072 * it is. The caller must hold the RTNL lock.
7074 static bool netdev_has_any_lower_dev(struct net_device *dev)
7078 return !list_empty(&dev->adj_list.lower);
7081 void *netdev_adjacent_get_private(struct list_head *adj_list)
7083 struct netdev_adjacent *adj;
7085 adj = list_entry(adj_list, struct netdev_adjacent, list);
7087 return adj->private;
7089 EXPORT_SYMBOL(netdev_adjacent_get_private);
7092 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7094 * @iter: list_head ** of the current position
7096 * Gets the next device from the dev's upper list, starting from iter
7097 * position. The caller must hold RCU read lock.
7099 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7100 struct list_head **iter)
7102 struct netdev_adjacent *upper;
7104 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7106 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7108 if (&upper->list == &dev->adj_list.upper)
7111 *iter = &upper->list;
7115 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7117 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7118 struct list_head **iter,
7121 struct netdev_adjacent *upper;
7123 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7125 if (&upper->list == &dev->adj_list.upper)
7128 *iter = &upper->list;
7129 *ignore = upper->ignore;
7134 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7135 struct list_head **iter)
7137 struct netdev_adjacent *upper;
7139 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7141 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7143 if (&upper->list == &dev->adj_list.upper)
7146 *iter = &upper->list;
7151 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7152 int (*fn)(struct net_device *dev,
7153 struct netdev_nested_priv *priv),
7154 struct netdev_nested_priv *priv)
7156 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7157 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7162 iter = &dev->adj_list.upper;
7166 ret = fn(now, priv);
7173 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7180 niter = &udev->adj_list.upper;
7181 dev_stack[cur] = now;
7182 iter_stack[cur++] = iter;
7189 next = dev_stack[--cur];
7190 niter = iter_stack[cur];
7200 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7201 int (*fn)(struct net_device *dev,
7202 struct netdev_nested_priv *priv),
7203 struct netdev_nested_priv *priv)
7205 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7206 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7210 iter = &dev->adj_list.upper;
7214 ret = fn(now, priv);
7221 udev = netdev_next_upper_dev_rcu(now, &iter);
7226 niter = &udev->adj_list.upper;
7227 dev_stack[cur] = now;
7228 iter_stack[cur++] = iter;
7235 next = dev_stack[--cur];
7236 niter = iter_stack[cur];
7245 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7247 static bool __netdev_has_upper_dev(struct net_device *dev,
7248 struct net_device *upper_dev)
7250 struct netdev_nested_priv priv = {
7252 .data = (void *)upper_dev,
7257 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7262 * netdev_lower_get_next_private - Get the next ->private from the
7263 * lower neighbour list
7265 * @iter: list_head ** of the current position
7267 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7268 * list, starting from iter position. The caller must hold either hold the
7269 * RTNL lock or its own locking that guarantees that the neighbour lower
7270 * list will remain unchanged.
7272 void *netdev_lower_get_next_private(struct net_device *dev,
7273 struct list_head **iter)
7275 struct netdev_adjacent *lower;
7277 lower = list_entry(*iter, struct netdev_adjacent, list);
7279 if (&lower->list == &dev->adj_list.lower)
7282 *iter = lower->list.next;
7284 return lower->private;
7286 EXPORT_SYMBOL(netdev_lower_get_next_private);
7289 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7290 * lower neighbour list, RCU
7293 * @iter: list_head ** of the current position
7295 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7296 * list, starting from iter position. The caller must hold RCU read lock.
7298 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7299 struct list_head **iter)
7301 struct netdev_adjacent *lower;
7303 WARN_ON_ONCE(!rcu_read_lock_held());
7305 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7307 if (&lower->list == &dev->adj_list.lower)
7310 *iter = &lower->list;
7312 return lower->private;
7314 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7317 * netdev_lower_get_next - Get the next device from the lower neighbour
7320 * @iter: list_head ** of the current position
7322 * Gets the next netdev_adjacent from the dev's lower neighbour
7323 * list, starting from iter position. The caller must hold RTNL lock or
7324 * its own locking that guarantees that the neighbour lower
7325 * list will remain unchanged.
7327 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7329 struct netdev_adjacent *lower;
7331 lower = list_entry(*iter, struct netdev_adjacent, list);
7333 if (&lower->list == &dev->adj_list.lower)
7336 *iter = lower->list.next;
7340 EXPORT_SYMBOL(netdev_lower_get_next);
7342 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7343 struct list_head **iter)
7345 struct netdev_adjacent *lower;
7347 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7349 if (&lower->list == &dev->adj_list.lower)
7352 *iter = &lower->list;
7357 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7358 struct list_head **iter,
7361 struct netdev_adjacent *lower;
7363 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7365 if (&lower->list == &dev->adj_list.lower)
7368 *iter = &lower->list;
7369 *ignore = lower->ignore;
7374 int netdev_walk_all_lower_dev(struct net_device *dev,
7375 int (*fn)(struct net_device *dev,
7376 struct netdev_nested_priv *priv),
7377 struct netdev_nested_priv *priv)
7379 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7380 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7384 iter = &dev->adj_list.lower;
7388 ret = fn(now, priv);
7395 ldev = netdev_next_lower_dev(now, &iter);
7400 niter = &ldev->adj_list.lower;
7401 dev_stack[cur] = now;
7402 iter_stack[cur++] = iter;
7409 next = dev_stack[--cur];
7410 niter = iter_stack[cur];
7419 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7421 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7422 int (*fn)(struct net_device *dev,
7423 struct netdev_nested_priv *priv),
7424 struct netdev_nested_priv *priv)
7426 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7427 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7432 iter = &dev->adj_list.lower;
7436 ret = fn(now, priv);
7443 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7450 niter = &ldev->adj_list.lower;
7451 dev_stack[cur] = now;
7452 iter_stack[cur++] = iter;
7459 next = dev_stack[--cur];
7460 niter = iter_stack[cur];
7470 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7471 struct list_head **iter)
7473 struct netdev_adjacent *lower;
7475 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7476 if (&lower->list == &dev->adj_list.lower)
7479 *iter = &lower->list;
7483 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7485 static u8 __netdev_upper_depth(struct net_device *dev)
7487 struct net_device *udev;
7488 struct list_head *iter;
7492 for (iter = &dev->adj_list.upper,
7493 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7495 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7498 if (max_depth < udev->upper_level)
7499 max_depth = udev->upper_level;
7505 static u8 __netdev_lower_depth(struct net_device *dev)
7507 struct net_device *ldev;
7508 struct list_head *iter;
7512 for (iter = &dev->adj_list.lower,
7513 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7515 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7518 if (max_depth < ldev->lower_level)
7519 max_depth = ldev->lower_level;
7525 static int __netdev_update_upper_level(struct net_device *dev,
7526 struct netdev_nested_priv *__unused)
7528 dev->upper_level = __netdev_upper_depth(dev) + 1;
7532 static int __netdev_update_lower_level(struct net_device *dev,
7533 struct netdev_nested_priv *priv)
7535 dev->lower_level = __netdev_lower_depth(dev) + 1;
7537 #ifdef CONFIG_LOCKDEP
7541 if (priv->flags & NESTED_SYNC_IMM)
7542 dev->nested_level = dev->lower_level - 1;
7543 if (priv->flags & NESTED_SYNC_TODO)
7544 net_unlink_todo(dev);
7549 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7550 int (*fn)(struct net_device *dev,
7551 struct netdev_nested_priv *priv),
7552 struct netdev_nested_priv *priv)
7554 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7555 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7559 iter = &dev->adj_list.lower;
7563 ret = fn(now, priv);
7570 ldev = netdev_next_lower_dev_rcu(now, &iter);
7575 niter = &ldev->adj_list.lower;
7576 dev_stack[cur] = now;
7577 iter_stack[cur++] = iter;
7584 next = dev_stack[--cur];
7585 niter = iter_stack[cur];
7594 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7597 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7598 * lower neighbour list, RCU
7602 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7603 * list. The caller must hold RCU read lock.
7605 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7607 struct netdev_adjacent *lower;
7609 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7610 struct netdev_adjacent, list);
7612 return lower->private;
7615 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7618 * netdev_master_upper_dev_get_rcu - Get master upper device
7621 * Find a master upper device and return pointer to it or NULL in case
7622 * it's not there. The caller must hold the RCU read lock.
7624 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7626 struct netdev_adjacent *upper;
7628 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7629 struct netdev_adjacent, list);
7630 if (upper && likely(upper->master))
7634 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7636 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7637 struct net_device *adj_dev,
7638 struct list_head *dev_list)
7640 char linkname[IFNAMSIZ+7];
7642 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7643 "upper_%s" : "lower_%s", adj_dev->name);
7644 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7647 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7649 struct list_head *dev_list)
7651 char linkname[IFNAMSIZ+7];
7653 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7654 "upper_%s" : "lower_%s", name);
7655 sysfs_remove_link(&(dev->dev.kobj), linkname);
7658 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7659 struct net_device *adj_dev,
7660 struct list_head *dev_list)
7662 return (dev_list == &dev->adj_list.upper ||
7663 dev_list == &dev->adj_list.lower) &&
7664 net_eq(dev_net(dev), dev_net(adj_dev));
7667 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7668 struct net_device *adj_dev,
7669 struct list_head *dev_list,
7670 void *private, bool master)
7672 struct netdev_adjacent *adj;
7675 adj = __netdev_find_adj(adj_dev, dev_list);
7679 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7680 dev->name, adj_dev->name, adj->ref_nr);
7685 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7690 adj->master = master;
7692 adj->private = private;
7693 adj->ignore = false;
7696 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7697 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7699 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7700 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7705 /* Ensure that master link is always the first item in list. */
7707 ret = sysfs_create_link(&(dev->dev.kobj),
7708 &(adj_dev->dev.kobj), "master");
7710 goto remove_symlinks;
7712 list_add_rcu(&adj->list, dev_list);
7714 list_add_tail_rcu(&adj->list, dev_list);
7720 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7721 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7729 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7730 struct net_device *adj_dev,
7732 struct list_head *dev_list)
7734 struct netdev_adjacent *adj;
7736 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7737 dev->name, adj_dev->name, ref_nr);
7739 adj = __netdev_find_adj(adj_dev, dev_list);
7742 pr_err("Adjacency does not exist for device %s from %s\n",
7743 dev->name, adj_dev->name);
7748 if (adj->ref_nr > ref_nr) {
7749 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7750 dev->name, adj_dev->name, ref_nr,
7751 adj->ref_nr - ref_nr);
7752 adj->ref_nr -= ref_nr;
7757 sysfs_remove_link(&(dev->dev.kobj), "master");
7759 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7760 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7762 list_del_rcu(&adj->list);
7763 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7764 adj_dev->name, dev->name, adj_dev->name);
7766 kfree_rcu(adj, rcu);
7769 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7770 struct net_device *upper_dev,
7771 struct list_head *up_list,
7772 struct list_head *down_list,
7773 void *private, bool master)
7777 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7782 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7785 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7792 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7793 struct net_device *upper_dev,
7795 struct list_head *up_list,
7796 struct list_head *down_list)
7798 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7799 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7802 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7803 struct net_device *upper_dev,
7804 void *private, bool master)
7806 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7807 &dev->adj_list.upper,
7808 &upper_dev->adj_list.lower,
7812 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7813 struct net_device *upper_dev)
7815 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7816 &dev->adj_list.upper,
7817 &upper_dev->adj_list.lower);
7820 static int __netdev_upper_dev_link(struct net_device *dev,
7821 struct net_device *upper_dev, bool master,
7822 void *upper_priv, void *upper_info,
7823 struct netdev_nested_priv *priv,
7824 struct netlink_ext_ack *extack)
7826 struct netdev_notifier_changeupper_info changeupper_info = {
7831 .upper_dev = upper_dev,
7834 .upper_info = upper_info,
7836 struct net_device *master_dev;
7841 if (dev == upper_dev)
7844 /* To prevent loops, check if dev is not upper device to upper_dev. */
7845 if (__netdev_has_upper_dev(upper_dev, dev))
7848 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7852 if (__netdev_has_upper_dev(dev, upper_dev))
7855 master_dev = __netdev_master_upper_dev_get(dev);
7857 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7860 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7861 &changeupper_info.info);
7862 ret = notifier_to_errno(ret);
7866 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7871 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7872 &changeupper_info.info);
7873 ret = notifier_to_errno(ret);
7877 __netdev_update_upper_level(dev, NULL);
7878 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7880 __netdev_update_lower_level(upper_dev, priv);
7881 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7887 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7893 * netdev_upper_dev_link - Add a link to the upper device
7895 * @upper_dev: new upper device
7896 * @extack: netlink extended ack
7898 * Adds a link to device which is upper to this one. The caller must hold
7899 * the RTNL lock. On a failure a negative errno code is returned.
7900 * On success the reference counts are adjusted and the function
7903 int netdev_upper_dev_link(struct net_device *dev,
7904 struct net_device *upper_dev,
7905 struct netlink_ext_ack *extack)
7907 struct netdev_nested_priv priv = {
7908 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7912 return __netdev_upper_dev_link(dev, upper_dev, false,
7913 NULL, NULL, &priv, extack);
7915 EXPORT_SYMBOL(netdev_upper_dev_link);
7918 * netdev_master_upper_dev_link - Add a master link to the upper device
7920 * @upper_dev: new upper device
7921 * @upper_priv: upper device private
7922 * @upper_info: upper info to be passed down via notifier
7923 * @extack: netlink extended ack
7925 * Adds a link to device which is upper to this one. In this case, only
7926 * one master upper device can be linked, although other non-master devices
7927 * might be linked as well. The caller must hold the RTNL lock.
7928 * On a failure a negative errno code is returned. On success the reference
7929 * counts are adjusted and the function returns zero.
7931 int netdev_master_upper_dev_link(struct net_device *dev,
7932 struct net_device *upper_dev,
7933 void *upper_priv, void *upper_info,
7934 struct netlink_ext_ack *extack)
7936 struct netdev_nested_priv priv = {
7937 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7941 return __netdev_upper_dev_link(dev, upper_dev, true,
7942 upper_priv, upper_info, &priv, extack);
7944 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7946 static void __netdev_upper_dev_unlink(struct net_device *dev,
7947 struct net_device *upper_dev,
7948 struct netdev_nested_priv *priv)
7950 struct netdev_notifier_changeupper_info changeupper_info = {
7954 .upper_dev = upper_dev,
7960 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7962 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7963 &changeupper_info.info);
7965 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7967 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7968 &changeupper_info.info);
7970 __netdev_update_upper_level(dev, NULL);
7971 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7973 __netdev_update_lower_level(upper_dev, priv);
7974 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7979 * netdev_upper_dev_unlink - Removes a link to upper device
7981 * @upper_dev: new upper device
7983 * Removes a link to device which is upper to this one. The caller must hold
7986 void netdev_upper_dev_unlink(struct net_device *dev,
7987 struct net_device *upper_dev)
7989 struct netdev_nested_priv priv = {
7990 .flags = NESTED_SYNC_TODO,
7994 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7996 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7998 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7999 struct net_device *lower_dev,
8002 struct netdev_adjacent *adj;
8004 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
8008 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
8013 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
8014 struct net_device *lower_dev)
8016 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
8019 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
8020 struct net_device *lower_dev)
8022 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
8025 int netdev_adjacent_change_prepare(struct net_device *old_dev,
8026 struct net_device *new_dev,
8027 struct net_device *dev,
8028 struct netlink_ext_ack *extack)
8030 struct netdev_nested_priv priv = {
8039 if (old_dev && new_dev != old_dev)
8040 netdev_adjacent_dev_disable(dev, old_dev);
8041 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
8044 if (old_dev && new_dev != old_dev)
8045 netdev_adjacent_dev_enable(dev, old_dev);
8051 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
8053 void netdev_adjacent_change_commit(struct net_device *old_dev,
8054 struct net_device *new_dev,
8055 struct net_device *dev)
8057 struct netdev_nested_priv priv = {
8058 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8062 if (!new_dev || !old_dev)
8065 if (new_dev == old_dev)
8068 netdev_adjacent_dev_enable(dev, old_dev);
8069 __netdev_upper_dev_unlink(old_dev, dev, &priv);
8071 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8073 void netdev_adjacent_change_abort(struct net_device *old_dev,
8074 struct net_device *new_dev,
8075 struct net_device *dev)
8077 struct netdev_nested_priv priv = {
8085 if (old_dev && new_dev != old_dev)
8086 netdev_adjacent_dev_enable(dev, old_dev);
8088 __netdev_upper_dev_unlink(new_dev, dev, &priv);
8090 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8093 * netdev_bonding_info_change - Dispatch event about slave change
8095 * @bonding_info: info to dispatch
8097 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8098 * The caller must hold the RTNL lock.
8100 void netdev_bonding_info_change(struct net_device *dev,
8101 struct netdev_bonding_info *bonding_info)
8103 struct netdev_notifier_bonding_info info = {
8107 memcpy(&info.bonding_info, bonding_info,
8108 sizeof(struct netdev_bonding_info));
8109 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8112 EXPORT_SYMBOL(netdev_bonding_info_change);
8115 * netdev_get_xmit_slave - Get the xmit slave of master device
8118 * @all_slaves: assume all the slaves are active
8120 * The reference counters are not incremented so the caller must be
8121 * careful with locks. The caller must hold RCU lock.
8122 * %NULL is returned if no slave is found.
8125 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8126 struct sk_buff *skb,
8129 const struct net_device_ops *ops = dev->netdev_ops;
8131 if (!ops->ndo_get_xmit_slave)
8133 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8135 EXPORT_SYMBOL(netdev_get_xmit_slave);
8137 static void netdev_adjacent_add_links(struct net_device *dev)
8139 struct netdev_adjacent *iter;
8141 struct net *net = dev_net(dev);
8143 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8144 if (!net_eq(net, dev_net(iter->dev)))
8146 netdev_adjacent_sysfs_add(iter->dev, dev,
8147 &iter->dev->adj_list.lower);
8148 netdev_adjacent_sysfs_add(dev, iter->dev,
8149 &dev->adj_list.upper);
8152 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8153 if (!net_eq(net, dev_net(iter->dev)))
8155 netdev_adjacent_sysfs_add(iter->dev, dev,
8156 &iter->dev->adj_list.upper);
8157 netdev_adjacent_sysfs_add(dev, iter->dev,
8158 &dev->adj_list.lower);
8162 static void netdev_adjacent_del_links(struct net_device *dev)
8164 struct netdev_adjacent *iter;
8166 struct net *net = dev_net(dev);
8168 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8169 if (!net_eq(net, dev_net(iter->dev)))
8171 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8172 &iter->dev->adj_list.lower);
8173 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8174 &dev->adj_list.upper);
8177 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8178 if (!net_eq(net, dev_net(iter->dev)))
8180 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8181 &iter->dev->adj_list.upper);
8182 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8183 &dev->adj_list.lower);
8187 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8189 struct netdev_adjacent *iter;
8191 struct net *net = dev_net(dev);
8193 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8194 if (!net_eq(net, dev_net(iter->dev)))
8196 netdev_adjacent_sysfs_del(iter->dev, oldname,
8197 &iter->dev->adj_list.lower);
8198 netdev_adjacent_sysfs_add(iter->dev, dev,
8199 &iter->dev->adj_list.lower);
8202 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8203 if (!net_eq(net, dev_net(iter->dev)))
8205 netdev_adjacent_sysfs_del(iter->dev, oldname,
8206 &iter->dev->adj_list.upper);
8207 netdev_adjacent_sysfs_add(iter->dev, dev,
8208 &iter->dev->adj_list.upper);
8212 void *netdev_lower_dev_get_private(struct net_device *dev,
8213 struct net_device *lower_dev)
8215 struct netdev_adjacent *lower;
8219 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8223 return lower->private;
8225 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8229 * netdev_lower_change - Dispatch event about lower device state change
8230 * @lower_dev: device
8231 * @lower_state_info: state to dispatch
8233 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8234 * The caller must hold the RTNL lock.
8236 void netdev_lower_state_changed(struct net_device *lower_dev,
8237 void *lower_state_info)
8239 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8240 .info.dev = lower_dev,
8244 changelowerstate_info.lower_state_info = lower_state_info;
8245 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8246 &changelowerstate_info.info);
8248 EXPORT_SYMBOL(netdev_lower_state_changed);
8250 static void dev_change_rx_flags(struct net_device *dev, int flags)
8252 const struct net_device_ops *ops = dev->netdev_ops;
8254 if (ops->ndo_change_rx_flags)
8255 ops->ndo_change_rx_flags(dev, flags);
8258 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8260 unsigned int old_flags = dev->flags;
8266 dev->flags |= IFF_PROMISC;
8267 dev->promiscuity += inc;
8268 if (dev->promiscuity == 0) {
8271 * If inc causes overflow, untouch promisc and return error.
8274 dev->flags &= ~IFF_PROMISC;
8276 dev->promiscuity -= inc;
8277 pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
8282 if (dev->flags != old_flags) {
8283 pr_info("device %s %s promiscuous mode\n",
8285 dev->flags & IFF_PROMISC ? "entered" : "left");
8286 if (audit_enabled) {
8287 current_uid_gid(&uid, &gid);
8288 audit_log(audit_context(), GFP_ATOMIC,
8289 AUDIT_ANOM_PROMISCUOUS,
8290 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8291 dev->name, (dev->flags & IFF_PROMISC),
8292 (old_flags & IFF_PROMISC),
8293 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8294 from_kuid(&init_user_ns, uid),
8295 from_kgid(&init_user_ns, gid),
8296 audit_get_sessionid(current));
8299 dev_change_rx_flags(dev, IFF_PROMISC);
8302 __dev_notify_flags(dev, old_flags, IFF_PROMISC);
8307 * dev_set_promiscuity - update promiscuity count on a device
8311 * Add or remove promiscuity from a device. While the count in the device
8312 * remains above zero the interface remains promiscuous. Once it hits zero
8313 * the device reverts back to normal filtering operation. A negative inc
8314 * value is used to drop promiscuity on the device.
8315 * Return 0 if successful or a negative errno code on error.
8317 int dev_set_promiscuity(struct net_device *dev, int inc)
8319 unsigned int old_flags = dev->flags;
8322 err = __dev_set_promiscuity(dev, inc, true);
8325 if (dev->flags != old_flags)
8326 dev_set_rx_mode(dev);
8329 EXPORT_SYMBOL(dev_set_promiscuity);
8331 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8333 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8337 dev->flags |= IFF_ALLMULTI;
8338 dev->allmulti += inc;
8339 if (dev->allmulti == 0) {
8342 * If inc causes overflow, untouch allmulti and return error.
8345 dev->flags &= ~IFF_ALLMULTI;
8347 dev->allmulti -= inc;
8348 pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
8353 if (dev->flags ^ old_flags) {
8354 dev_change_rx_flags(dev, IFF_ALLMULTI);
8355 dev_set_rx_mode(dev);
8357 __dev_notify_flags(dev, old_flags,
8358 dev->gflags ^ old_gflags);
8364 * dev_set_allmulti - update allmulti count on a device
8368 * Add or remove reception of all multicast frames to a device. While the
8369 * count in the device remains above zero the interface remains listening
8370 * to all interfaces. Once it hits zero the device reverts back to normal
8371 * filtering operation. A negative @inc value is used to drop the counter
8372 * when releasing a resource needing all multicasts.
8373 * Return 0 if successful or a negative errno code on error.
8376 int dev_set_allmulti(struct net_device *dev, int inc)
8378 return __dev_set_allmulti(dev, inc, true);
8380 EXPORT_SYMBOL(dev_set_allmulti);
8383 * Upload unicast and multicast address lists to device and
8384 * configure RX filtering. When the device doesn't support unicast
8385 * filtering it is put in promiscuous mode while unicast addresses
8388 void __dev_set_rx_mode(struct net_device *dev)
8390 const struct net_device_ops *ops = dev->netdev_ops;
8392 /* dev_open will call this function so the list will stay sane. */
8393 if (!(dev->flags&IFF_UP))
8396 if (!netif_device_present(dev))
8399 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8400 /* Unicast addresses changes may only happen under the rtnl,
8401 * therefore calling __dev_set_promiscuity here is safe.
8403 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8404 __dev_set_promiscuity(dev, 1, false);
8405 dev->uc_promisc = true;
8406 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8407 __dev_set_promiscuity(dev, -1, false);
8408 dev->uc_promisc = false;
8412 if (ops->ndo_set_rx_mode)
8413 ops->ndo_set_rx_mode(dev);
8416 void dev_set_rx_mode(struct net_device *dev)
8418 netif_addr_lock_bh(dev);
8419 __dev_set_rx_mode(dev);
8420 netif_addr_unlock_bh(dev);
8424 * dev_get_flags - get flags reported to userspace
8427 * Get the combination of flag bits exported through APIs to userspace.
8429 unsigned int dev_get_flags(const struct net_device *dev)
8433 flags = (dev->flags & ~(IFF_PROMISC |
8438 (dev->gflags & (IFF_PROMISC |
8441 if (netif_running(dev)) {
8442 if (netif_oper_up(dev))
8443 flags |= IFF_RUNNING;
8444 if (netif_carrier_ok(dev))
8445 flags |= IFF_LOWER_UP;
8446 if (netif_dormant(dev))
8447 flags |= IFF_DORMANT;
8452 EXPORT_SYMBOL(dev_get_flags);
8454 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8455 struct netlink_ext_ack *extack)
8457 unsigned int old_flags = dev->flags;
8463 * Set the flags on our device.
8466 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8467 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8469 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8473 * Load in the correct multicast list now the flags have changed.
8476 if ((old_flags ^ flags) & IFF_MULTICAST)
8477 dev_change_rx_flags(dev, IFF_MULTICAST);
8479 dev_set_rx_mode(dev);
8482 * Have we downed the interface. We handle IFF_UP ourselves
8483 * according to user attempts to set it, rather than blindly
8488 if ((old_flags ^ flags) & IFF_UP) {
8489 if (old_flags & IFF_UP)
8492 ret = __dev_open(dev, extack);
8495 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8496 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8497 unsigned int old_flags = dev->flags;
8499 dev->gflags ^= IFF_PROMISC;
8501 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8502 if (dev->flags != old_flags)
8503 dev_set_rx_mode(dev);
8506 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8507 * is important. Some (broken) drivers set IFF_PROMISC, when
8508 * IFF_ALLMULTI is requested not asking us and not reporting.
8510 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8511 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8513 dev->gflags ^= IFF_ALLMULTI;
8514 __dev_set_allmulti(dev, inc, false);
8520 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8521 unsigned int gchanges)
8523 unsigned int changes = dev->flags ^ old_flags;
8526 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
8528 if (changes & IFF_UP) {
8529 if (dev->flags & IFF_UP)
8530 call_netdevice_notifiers(NETDEV_UP, dev);
8532 call_netdevice_notifiers(NETDEV_DOWN, dev);
8535 if (dev->flags & IFF_UP &&
8536 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8537 struct netdev_notifier_change_info change_info = {
8541 .flags_changed = changes,
8544 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8549 * dev_change_flags - change device settings
8551 * @flags: device state flags
8552 * @extack: netlink extended ack
8554 * Change settings on device based state flags. The flags are
8555 * in the userspace exported format.
8557 int dev_change_flags(struct net_device *dev, unsigned int flags,
8558 struct netlink_ext_ack *extack)
8561 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8563 ret = __dev_change_flags(dev, flags, extack);
8567 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8568 __dev_notify_flags(dev, old_flags, changes);
8571 EXPORT_SYMBOL(dev_change_flags);
8573 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8575 const struct net_device_ops *ops = dev->netdev_ops;
8577 if (ops->ndo_change_mtu)
8578 return ops->ndo_change_mtu(dev, new_mtu);
8580 /* Pairs with all the lockless reads of dev->mtu in the stack */
8581 WRITE_ONCE(dev->mtu, new_mtu);
8584 EXPORT_SYMBOL(__dev_set_mtu);
8586 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8587 struct netlink_ext_ack *extack)
8589 /* MTU must be positive, and in range */
8590 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8591 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8595 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8596 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8603 * dev_set_mtu_ext - Change maximum transfer unit
8605 * @new_mtu: new transfer unit
8606 * @extack: netlink extended ack
8608 * Change the maximum transfer size of the network device.
8610 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8611 struct netlink_ext_ack *extack)
8615 if (new_mtu == dev->mtu)
8618 err = dev_validate_mtu(dev, new_mtu, extack);
8622 if (!netif_device_present(dev))
8625 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8626 err = notifier_to_errno(err);
8630 orig_mtu = dev->mtu;
8631 err = __dev_set_mtu(dev, new_mtu);
8634 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8636 err = notifier_to_errno(err);
8638 /* setting mtu back and notifying everyone again,
8639 * so that they have a chance to revert changes.
8641 __dev_set_mtu(dev, orig_mtu);
8642 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8649 int dev_set_mtu(struct net_device *dev, int new_mtu)
8651 struct netlink_ext_ack extack;
8654 memset(&extack, 0, sizeof(extack));
8655 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8656 if (err && extack._msg)
8657 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8660 EXPORT_SYMBOL(dev_set_mtu);
8663 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8665 * @new_len: new tx queue length
8667 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8669 unsigned int orig_len = dev->tx_queue_len;
8672 if (new_len != (unsigned int)new_len)
8675 if (new_len != orig_len) {
8676 dev->tx_queue_len = new_len;
8677 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8678 res = notifier_to_errno(res);
8681 res = dev_qdisc_change_tx_queue_len(dev);
8689 netdev_err(dev, "refused to change device tx_queue_len\n");
8690 dev->tx_queue_len = orig_len;
8695 * dev_set_group - Change group this device belongs to
8697 * @new_group: group this device should belong to
8699 void dev_set_group(struct net_device *dev, int new_group)
8701 dev->group = new_group;
8703 EXPORT_SYMBOL(dev_set_group);
8706 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8708 * @addr: new address
8709 * @extack: netlink extended ack
8711 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8712 struct netlink_ext_ack *extack)
8714 struct netdev_notifier_pre_changeaddr_info info = {
8716 .info.extack = extack,
8721 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8722 return notifier_to_errno(rc);
8724 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8727 * dev_set_mac_address - Change Media Access Control Address
8730 * @extack: netlink extended ack
8732 * Change the hardware (MAC) address of the device
8734 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8735 struct netlink_ext_ack *extack)
8737 const struct net_device_ops *ops = dev->netdev_ops;
8740 if (!ops->ndo_set_mac_address)
8742 if (sa->sa_family != dev->type)
8744 if (!netif_device_present(dev))
8746 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8749 err = ops->ndo_set_mac_address(dev, sa);
8752 dev->addr_assign_type = NET_ADDR_SET;
8753 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8754 add_device_randomness(dev->dev_addr, dev->addr_len);
8757 EXPORT_SYMBOL(dev_set_mac_address);
8759 static DECLARE_RWSEM(dev_addr_sem);
8761 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8762 struct netlink_ext_ack *extack)
8766 down_write(&dev_addr_sem);
8767 ret = dev_set_mac_address(dev, sa, extack);
8768 up_write(&dev_addr_sem);
8771 EXPORT_SYMBOL(dev_set_mac_address_user);
8773 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8775 size_t size = sizeof(sa->sa_data);
8776 struct net_device *dev;
8779 down_read(&dev_addr_sem);
8782 dev = dev_get_by_name_rcu(net, dev_name);
8788 memset(sa->sa_data, 0, size);
8790 memcpy(sa->sa_data, dev->dev_addr,
8791 min_t(size_t, size, dev->addr_len));
8792 sa->sa_family = dev->type;
8796 up_read(&dev_addr_sem);
8799 EXPORT_SYMBOL(dev_get_mac_address);
8802 * dev_change_carrier - Change device carrier
8804 * @new_carrier: new value
8806 * Change device carrier
8808 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8810 const struct net_device_ops *ops = dev->netdev_ops;
8812 if (!ops->ndo_change_carrier)
8814 if (!netif_device_present(dev))
8816 return ops->ndo_change_carrier(dev, new_carrier);
8818 EXPORT_SYMBOL(dev_change_carrier);
8821 * dev_get_phys_port_id - Get device physical port ID
8825 * Get device physical port ID
8827 int dev_get_phys_port_id(struct net_device *dev,
8828 struct netdev_phys_item_id *ppid)
8830 const struct net_device_ops *ops = dev->netdev_ops;
8832 if (!ops->ndo_get_phys_port_id)
8834 return ops->ndo_get_phys_port_id(dev, ppid);
8836 EXPORT_SYMBOL(dev_get_phys_port_id);
8839 * dev_get_phys_port_name - Get device physical port name
8842 * @len: limit of bytes to copy to name
8844 * Get device physical port name
8846 int dev_get_phys_port_name(struct net_device *dev,
8847 char *name, size_t len)
8849 const struct net_device_ops *ops = dev->netdev_ops;
8852 if (ops->ndo_get_phys_port_name) {
8853 err = ops->ndo_get_phys_port_name(dev, name, len);
8854 if (err != -EOPNOTSUPP)
8857 return devlink_compat_phys_port_name_get(dev, name, len);
8859 EXPORT_SYMBOL(dev_get_phys_port_name);
8862 * dev_get_port_parent_id - Get the device's port parent identifier
8863 * @dev: network device
8864 * @ppid: pointer to a storage for the port's parent identifier
8865 * @recurse: allow/disallow recursion to lower devices
8867 * Get the devices's port parent identifier
8869 int dev_get_port_parent_id(struct net_device *dev,
8870 struct netdev_phys_item_id *ppid,
8873 const struct net_device_ops *ops = dev->netdev_ops;
8874 struct netdev_phys_item_id first = { };
8875 struct net_device *lower_dev;
8876 struct list_head *iter;
8879 if (ops->ndo_get_port_parent_id) {
8880 err = ops->ndo_get_port_parent_id(dev, ppid);
8881 if (err != -EOPNOTSUPP)
8885 err = devlink_compat_switch_id_get(dev, ppid);
8886 if (!err || err != -EOPNOTSUPP)
8892 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8893 err = dev_get_port_parent_id(lower_dev, ppid, recurse);
8898 else if (memcmp(&first, ppid, sizeof(*ppid)))
8904 EXPORT_SYMBOL(dev_get_port_parent_id);
8907 * netdev_port_same_parent_id - Indicate if two network devices have
8908 * the same port parent identifier
8909 * @a: first network device
8910 * @b: second network device
8912 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
8914 struct netdev_phys_item_id a_id = { };
8915 struct netdev_phys_item_id b_id = { };
8917 if (dev_get_port_parent_id(a, &a_id, true) ||
8918 dev_get_port_parent_id(b, &b_id, true))
8921 return netdev_phys_item_id_same(&a_id, &b_id);
8923 EXPORT_SYMBOL(netdev_port_same_parent_id);
8926 * dev_change_proto_down - update protocol port state information
8928 * @proto_down: new value
8930 * This info can be used by switch drivers to set the phys state of the
8933 int dev_change_proto_down(struct net_device *dev, bool proto_down)
8935 const struct net_device_ops *ops = dev->netdev_ops;
8937 if (!ops->ndo_change_proto_down)
8939 if (!netif_device_present(dev))
8941 return ops->ndo_change_proto_down(dev, proto_down);
8943 EXPORT_SYMBOL(dev_change_proto_down);
8946 * dev_change_proto_down_generic - generic implementation for
8947 * ndo_change_proto_down that sets carrier according to
8951 * @proto_down: new value
8953 int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
8956 netif_carrier_off(dev);
8958 netif_carrier_on(dev);
8959 dev->proto_down = proto_down;
8962 EXPORT_SYMBOL(dev_change_proto_down_generic);
8965 * dev_change_proto_down_reason - proto down reason
8968 * @mask: proto down mask
8969 * @value: proto down value
8971 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
8977 dev->proto_down_reason = value;
8979 for_each_set_bit(b, &mask, 32) {
8980 if (value & (1 << b))
8981 dev->proto_down_reason |= BIT(b);
8983 dev->proto_down_reason &= ~BIT(b);
8987 EXPORT_SYMBOL(dev_change_proto_down_reason);
8989 struct bpf_xdp_link {
8990 struct bpf_link link;
8991 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
8995 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
8997 if (flags & XDP_FLAGS_HW_MODE)
8999 if (flags & XDP_FLAGS_DRV_MODE)
9000 return XDP_MODE_DRV;
9001 if (flags & XDP_FLAGS_SKB_MODE)
9002 return XDP_MODE_SKB;
9003 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9006 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9010 return generic_xdp_install;
9013 return dev->netdev_ops->ndo_bpf;
9019 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9020 enum bpf_xdp_mode mode)
9022 return dev->xdp_state[mode].link;
9025 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9026 enum bpf_xdp_mode mode)
9028 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9031 return link->link.prog;
9032 return dev->xdp_state[mode].prog;
9035 static u8 dev_xdp_prog_count(struct net_device *dev)
9040 for (i = 0; i < __MAX_XDP_MODE; i++)
9041 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9046 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9048 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9050 return prog ? prog->aux->id : 0;
9053 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9054 struct bpf_xdp_link *link)
9056 dev->xdp_state[mode].link = link;
9057 dev->xdp_state[mode].prog = NULL;
9060 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9061 struct bpf_prog *prog)
9063 dev->xdp_state[mode].link = NULL;
9064 dev->xdp_state[mode].prog = prog;
9067 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9068 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9069 u32 flags, struct bpf_prog *prog)
9071 struct netdev_bpf xdp;
9074 memset(&xdp, 0, sizeof(xdp));
9075 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9076 xdp.extack = extack;
9080 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9081 * "moved" into driver), so they don't increment it on their own, but
9082 * they do decrement refcnt when program is detached or replaced.
9083 * Given net_device also owns link/prog, we need to bump refcnt here
9084 * to prevent drivers from underflowing it.
9088 err = bpf_op(dev, &xdp);
9095 if (mode != XDP_MODE_HW)
9096 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9101 static void dev_xdp_uninstall(struct net_device *dev)
9103 struct bpf_xdp_link *link;
9104 struct bpf_prog *prog;
9105 enum bpf_xdp_mode mode;
9110 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9111 prog = dev_xdp_prog(dev, mode);
9115 bpf_op = dev_xdp_bpf_op(dev, mode);
9119 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9121 /* auto-detach link from net device */
9122 link = dev_xdp_link(dev, mode);
9128 dev_xdp_set_link(dev, mode, NULL);
9132 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9133 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9134 struct bpf_prog *old_prog, u32 flags)
9136 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9137 struct bpf_prog *cur_prog;
9138 enum bpf_xdp_mode mode;
9144 /* either link or prog attachment, never both */
9145 if (link && (new_prog || old_prog))
9147 /* link supports only XDP mode flags */
9148 if (link && (flags & ~XDP_FLAGS_MODES)) {
9149 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9152 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9153 if (num_modes > 1) {
9154 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9157 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9158 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9159 NL_SET_ERR_MSG(extack,
9160 "More than one program loaded, unset mode is ambiguous");
9163 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9164 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9165 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9169 mode = dev_xdp_mode(dev, flags);
9170 /* can't replace attached link */
9171 if (dev_xdp_link(dev, mode)) {
9172 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9176 cur_prog = dev_xdp_prog(dev, mode);
9177 /* can't replace attached prog with link */
9178 if (link && cur_prog) {
9179 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9182 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9183 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9187 /* put effective new program into new_prog */
9189 new_prog = link->link.prog;
9192 bool offload = mode == XDP_MODE_HW;
9193 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9194 ? XDP_MODE_DRV : XDP_MODE_SKB;
9196 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9197 NL_SET_ERR_MSG(extack, "XDP program already attached");
9200 if (!offload && dev_xdp_prog(dev, other_mode)) {
9201 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9204 if (!offload && bpf_prog_is_dev_bound(new_prog->aux)) {
9205 NL_SET_ERR_MSG(extack, "Using device-bound program without HW_MODE flag is not supported");
9208 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9209 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9212 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9213 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9218 /* don't call drivers if the effective program didn't change */
9219 if (new_prog != cur_prog) {
9220 bpf_op = dev_xdp_bpf_op(dev, mode);
9222 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9226 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9232 dev_xdp_set_link(dev, mode, link);
9234 dev_xdp_set_prog(dev, mode, new_prog);
9236 bpf_prog_put(cur_prog);
9241 static int dev_xdp_attach_link(struct net_device *dev,
9242 struct netlink_ext_ack *extack,
9243 struct bpf_xdp_link *link)
9245 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9248 static int dev_xdp_detach_link(struct net_device *dev,
9249 struct netlink_ext_ack *extack,
9250 struct bpf_xdp_link *link)
9252 enum bpf_xdp_mode mode;
9257 mode = dev_xdp_mode(dev, link->flags);
9258 if (dev_xdp_link(dev, mode) != link)
9261 bpf_op = dev_xdp_bpf_op(dev, mode);
9262 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9263 dev_xdp_set_link(dev, mode, NULL);
9267 static void bpf_xdp_link_release(struct bpf_link *link)
9269 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9273 /* if racing with net_device's tear down, xdp_link->dev might be
9274 * already NULL, in which case link was already auto-detached
9276 if (xdp_link->dev) {
9277 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9278 xdp_link->dev = NULL;
9284 static int bpf_xdp_link_detach(struct bpf_link *link)
9286 bpf_xdp_link_release(link);
9290 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9292 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9297 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9298 struct seq_file *seq)
9300 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9305 ifindex = xdp_link->dev->ifindex;
9308 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9311 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9312 struct bpf_link_info *info)
9314 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9319 ifindex = xdp_link->dev->ifindex;
9322 info->xdp.ifindex = ifindex;
9326 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9327 struct bpf_prog *old_prog)
9329 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9330 enum bpf_xdp_mode mode;
9336 /* link might have been auto-released already, so fail */
9337 if (!xdp_link->dev) {
9342 if (old_prog && link->prog != old_prog) {
9346 old_prog = link->prog;
9347 if (old_prog->type != new_prog->type ||
9348 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9353 if (old_prog == new_prog) {
9354 /* no-op, don't disturb drivers */
9355 bpf_prog_put(new_prog);
9359 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9360 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9361 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9362 xdp_link->flags, new_prog);
9366 old_prog = xchg(&link->prog, new_prog);
9367 bpf_prog_put(old_prog);
9374 static const struct bpf_link_ops bpf_xdp_link_lops = {
9375 .release = bpf_xdp_link_release,
9376 .dealloc = bpf_xdp_link_dealloc,
9377 .detach = bpf_xdp_link_detach,
9378 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9379 .fill_link_info = bpf_xdp_link_fill_link_info,
9380 .update_prog = bpf_xdp_link_update,
9383 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9385 struct net *net = current->nsproxy->net_ns;
9386 struct bpf_link_primer link_primer;
9387 struct bpf_xdp_link *link;
9388 struct net_device *dev;
9392 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9398 link = kzalloc(sizeof(*link), GFP_USER);
9404 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9406 link->flags = attr->link_create.flags;
9408 err = bpf_link_prime(&link->link, &link_primer);
9414 err = dev_xdp_attach_link(dev, NULL, link);
9419 bpf_link_cleanup(&link_primer);
9423 fd = bpf_link_settle(&link_primer);
9424 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9437 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9439 * @extack: netlink extended ack
9440 * @fd: new program fd or negative value to clear
9441 * @expected_fd: old program fd that userspace expects to replace or clear
9442 * @flags: xdp-related flags
9444 * Set or clear a bpf program for a device
9446 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9447 int fd, int expected_fd, u32 flags)
9449 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9450 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9456 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9457 mode != XDP_MODE_SKB);
9458 if (IS_ERR(new_prog))
9459 return PTR_ERR(new_prog);
9462 if (expected_fd >= 0) {
9463 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9464 mode != XDP_MODE_SKB);
9465 if (IS_ERR(old_prog)) {
9466 err = PTR_ERR(old_prog);
9472 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9475 if (err && new_prog)
9476 bpf_prog_put(new_prog);
9478 bpf_prog_put(old_prog);
9483 * dev_new_index - allocate an ifindex
9484 * @net: the applicable net namespace
9486 * Returns a suitable unique value for a new device interface
9487 * number. The caller must hold the rtnl semaphore or the
9488 * dev_base_lock to be sure it remains unique.
9490 static int dev_new_index(struct net *net)
9492 int ifindex = net->ifindex;
9497 if (!__dev_get_by_index(net, ifindex))
9498 return net->ifindex = ifindex;
9502 /* Delayed registration/unregisteration */
9503 static LIST_HEAD(net_todo_list);
9504 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9506 static void net_set_todo(struct net_device *dev)
9508 list_add_tail(&dev->todo_list, &net_todo_list);
9509 dev_net(dev)->dev_unreg_count++;
9512 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9513 struct net_device *upper, netdev_features_t features)
9515 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9516 netdev_features_t feature;
9519 for_each_netdev_feature(upper_disables, feature_bit) {
9520 feature = __NETIF_F_BIT(feature_bit);
9521 if (!(upper->wanted_features & feature)
9522 && (features & feature)) {
9523 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9524 &feature, upper->name);
9525 features &= ~feature;
9532 static void netdev_sync_lower_features(struct net_device *upper,
9533 struct net_device *lower, netdev_features_t features)
9535 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9536 netdev_features_t feature;
9539 for_each_netdev_feature(upper_disables, feature_bit) {
9540 feature = __NETIF_F_BIT(feature_bit);
9541 if (!(features & feature) && (lower->features & feature)) {
9542 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9543 &feature, lower->name);
9544 lower->wanted_features &= ~feature;
9545 __netdev_update_features(lower);
9547 if (unlikely(lower->features & feature))
9548 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9549 &feature, lower->name);
9551 netdev_features_change(lower);
9556 static netdev_features_t netdev_fix_features(struct net_device *dev,
9557 netdev_features_t features)
9559 /* Fix illegal checksum combinations */
9560 if ((features & NETIF_F_HW_CSUM) &&
9561 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9562 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9563 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9566 /* TSO requires that SG is present as well. */
9567 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9568 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9569 features &= ~NETIF_F_ALL_TSO;
9572 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9573 !(features & NETIF_F_IP_CSUM)) {
9574 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9575 features &= ~NETIF_F_TSO;
9576 features &= ~NETIF_F_TSO_ECN;
9579 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9580 !(features & NETIF_F_IPV6_CSUM)) {
9581 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9582 features &= ~NETIF_F_TSO6;
9585 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9586 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9587 features &= ~NETIF_F_TSO_MANGLEID;
9589 /* TSO ECN requires that TSO is present as well. */
9590 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9591 features &= ~NETIF_F_TSO_ECN;
9593 /* Software GSO depends on SG. */
9594 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9595 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9596 features &= ~NETIF_F_GSO;
9599 /* GSO partial features require GSO partial be set */
9600 if ((features & dev->gso_partial_features) &&
9601 !(features & NETIF_F_GSO_PARTIAL)) {
9603 "Dropping partially supported GSO features since no GSO partial.\n");
9604 features &= ~dev->gso_partial_features;
9607 if (!(features & NETIF_F_RXCSUM)) {
9608 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9609 * successfully merged by hardware must also have the
9610 * checksum verified by hardware. If the user does not
9611 * want to enable RXCSUM, logically, we should disable GRO_HW.
9613 if (features & NETIF_F_GRO_HW) {
9614 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9615 features &= ~NETIF_F_GRO_HW;
9619 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9620 if (features & NETIF_F_RXFCS) {
9621 if (features & NETIF_F_LRO) {
9622 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9623 features &= ~NETIF_F_LRO;
9626 if (features & NETIF_F_GRO_HW) {
9627 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9628 features &= ~NETIF_F_GRO_HW;
9632 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9633 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9634 features &= ~NETIF_F_HW_TLS_RX;
9640 int __netdev_update_features(struct net_device *dev)
9642 struct net_device *upper, *lower;
9643 netdev_features_t features;
9644 struct list_head *iter;
9649 features = netdev_get_wanted_features(dev);
9651 if (dev->netdev_ops->ndo_fix_features)
9652 features = dev->netdev_ops->ndo_fix_features(dev, features);
9654 /* driver might be less strict about feature dependencies */
9655 features = netdev_fix_features(dev, features);
9657 /* some features can't be enabled if they're off on an upper device */
9658 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9659 features = netdev_sync_upper_features(dev, upper, features);
9661 if (dev->features == features)
9664 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9665 &dev->features, &features);
9667 if (dev->netdev_ops->ndo_set_features)
9668 err = dev->netdev_ops->ndo_set_features(dev, features);
9672 if (unlikely(err < 0)) {
9674 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9675 err, &features, &dev->features);
9676 /* return non-0 since some features might have changed and
9677 * it's better to fire a spurious notification than miss it
9683 /* some features must be disabled on lower devices when disabled
9684 * on an upper device (think: bonding master or bridge)
9686 netdev_for_each_lower_dev(dev, lower, iter)
9687 netdev_sync_lower_features(dev, lower, features);
9690 netdev_features_t diff = features ^ dev->features;
9692 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9693 /* udp_tunnel_{get,drop}_rx_info both need
9694 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9695 * device, or they won't do anything.
9696 * Thus we need to update dev->features
9697 * *before* calling udp_tunnel_get_rx_info,
9698 * but *after* calling udp_tunnel_drop_rx_info.
9700 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9701 dev->features = features;
9702 udp_tunnel_get_rx_info(dev);
9704 udp_tunnel_drop_rx_info(dev);
9708 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9709 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9710 dev->features = features;
9711 err |= vlan_get_rx_ctag_filter_info(dev);
9713 vlan_drop_rx_ctag_filter_info(dev);
9717 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9718 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9719 dev->features = features;
9720 err |= vlan_get_rx_stag_filter_info(dev);
9722 vlan_drop_rx_stag_filter_info(dev);
9726 dev->features = features;
9729 return err < 0 ? 0 : 1;
9733 * netdev_update_features - recalculate device features
9734 * @dev: the device to check
9736 * Recalculate dev->features set and send notifications if it
9737 * has changed. Should be called after driver or hardware dependent
9738 * conditions might have changed that influence the features.
9740 void netdev_update_features(struct net_device *dev)
9742 if (__netdev_update_features(dev))
9743 netdev_features_change(dev);
9745 EXPORT_SYMBOL(netdev_update_features);
9748 * netdev_change_features - recalculate device features
9749 * @dev: the device to check
9751 * Recalculate dev->features set and send notifications even
9752 * if they have not changed. Should be called instead of
9753 * netdev_update_features() if also dev->vlan_features might
9754 * have changed to allow the changes to be propagated to stacked
9757 void netdev_change_features(struct net_device *dev)
9759 __netdev_update_features(dev);
9760 netdev_features_change(dev);
9762 EXPORT_SYMBOL(netdev_change_features);
9765 * netif_stacked_transfer_operstate - transfer operstate
9766 * @rootdev: the root or lower level device to transfer state from
9767 * @dev: the device to transfer operstate to
9769 * Transfer operational state from root to device. This is normally
9770 * called when a stacking relationship exists between the root
9771 * device and the device(a leaf device).
9773 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9774 struct net_device *dev)
9776 if (rootdev->operstate == IF_OPER_DORMANT)
9777 netif_dormant_on(dev);
9779 netif_dormant_off(dev);
9781 if (rootdev->operstate == IF_OPER_TESTING)
9782 netif_testing_on(dev);
9784 netif_testing_off(dev);
9786 if (netif_carrier_ok(rootdev))
9787 netif_carrier_on(dev);
9789 netif_carrier_off(dev);
9791 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9793 static int netif_alloc_rx_queues(struct net_device *dev)
9795 unsigned int i, count = dev->num_rx_queues;
9796 struct netdev_rx_queue *rx;
9797 size_t sz = count * sizeof(*rx);
9802 rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9808 for (i = 0; i < count; i++) {
9811 /* XDP RX-queue setup */
9812 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
9819 /* Rollback successful reg's and free other resources */
9821 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9827 static void netif_free_rx_queues(struct net_device *dev)
9829 unsigned int i, count = dev->num_rx_queues;
9831 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9835 for (i = 0; i < count; i++)
9836 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9841 static void netdev_init_one_queue(struct net_device *dev,
9842 struct netdev_queue *queue, void *_unused)
9844 /* Initialize queue lock */
9845 spin_lock_init(&queue->_xmit_lock);
9846 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9847 queue->xmit_lock_owner = -1;
9848 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9851 dql_init(&queue->dql, HZ);
9855 static void netif_free_tx_queues(struct net_device *dev)
9860 static int netif_alloc_netdev_queues(struct net_device *dev)
9862 unsigned int count = dev->num_tx_queues;
9863 struct netdev_queue *tx;
9864 size_t sz = count * sizeof(*tx);
9866 if (count < 1 || count > 0xffff)
9869 tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
9875 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
9876 spin_lock_init(&dev->tx_global_lock);
9881 void netif_tx_stop_all_queues(struct net_device *dev)
9885 for (i = 0; i < dev->num_tx_queues; i++) {
9886 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
9888 netif_tx_stop_queue(txq);
9891 EXPORT_SYMBOL(netif_tx_stop_all_queues);
9894 * register_netdevice - register a network device
9895 * @dev: device to register
9897 * Take a completed network device structure and add it to the kernel
9898 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
9899 * chain. 0 is returned on success. A negative errno code is returned
9900 * on a failure to set up the device, or if the name is a duplicate.
9902 * Callers must hold the rtnl semaphore. You may want
9903 * register_netdev() instead of this.
9906 * The locking appears insufficient to guarantee two parallel registers
9907 * will not get the same name.
9910 int register_netdevice(struct net_device *dev)
9913 struct net *net = dev_net(dev);
9915 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
9916 NETDEV_FEATURE_COUNT);
9917 BUG_ON(dev_boot_phase);
9922 /* When net_device's are persistent, this will be fatal. */
9923 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
9926 ret = ethtool_check_ops(dev->ethtool_ops);
9930 spin_lock_init(&dev->addr_list_lock);
9931 netdev_set_addr_lockdep_class(dev);
9933 ret = dev_get_valid_name(net, dev, dev->name);
9938 dev->name_node = netdev_name_node_head_alloc(dev);
9939 if (!dev->name_node)
9942 /* Init, if this function is available */
9943 if (dev->netdev_ops->ndo_init) {
9944 ret = dev->netdev_ops->ndo_init(dev);
9952 if (((dev->hw_features | dev->features) &
9953 NETIF_F_HW_VLAN_CTAG_FILTER) &&
9954 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
9955 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
9956 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
9963 dev->ifindex = dev_new_index(net);
9964 else if (__dev_get_by_index(net, dev->ifindex))
9967 /* Transfer changeable features to wanted_features and enable
9968 * software offloads (GSO and GRO).
9970 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
9971 dev->features |= NETIF_F_SOFT_FEATURES;
9973 if (dev->netdev_ops->ndo_udp_tunnel_add) {
9974 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9975 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
9978 dev->wanted_features = dev->features & dev->hw_features;
9980 if (!(dev->flags & IFF_LOOPBACK))
9981 dev->hw_features |= NETIF_F_NOCACHE_COPY;
9983 /* If IPv4 TCP segmentation offload is supported we should also
9984 * allow the device to enable segmenting the frame with the option
9985 * of ignoring a static IP ID value. This doesn't enable the
9986 * feature itself but allows the user to enable it later.
9988 if (dev->hw_features & NETIF_F_TSO)
9989 dev->hw_features |= NETIF_F_TSO_MANGLEID;
9990 if (dev->vlan_features & NETIF_F_TSO)
9991 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
9992 if (dev->mpls_features & NETIF_F_TSO)
9993 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
9994 if (dev->hw_enc_features & NETIF_F_TSO)
9995 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9997 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
9999 dev->vlan_features |= NETIF_F_HIGHDMA;
10001 /* Make NETIF_F_SG inheritable to tunnel devices.
10003 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10005 /* Make NETIF_F_SG inheritable to MPLS.
10007 dev->mpls_features |= NETIF_F_SG;
10009 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10010 ret = notifier_to_errno(ret);
10014 ret = netdev_register_kobject(dev);
10016 dev->reg_state = NETREG_UNREGISTERED;
10019 dev->reg_state = NETREG_REGISTERED;
10021 __netdev_update_features(dev);
10024 * Default initial state at registry is that the
10025 * device is present.
10028 set_bit(__LINK_STATE_PRESENT, &dev->state);
10030 linkwatch_init_dev(dev);
10032 dev_init_scheduler(dev);
10034 list_netdevice(dev);
10035 add_device_randomness(dev->dev_addr, dev->addr_len);
10037 /* If the device has permanent device address, driver should
10038 * set dev_addr and also addr_assign_type should be set to
10039 * NET_ADDR_PERM (default value).
10041 if (dev->addr_assign_type == NET_ADDR_PERM)
10042 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10044 /* Notify protocols, that a new device appeared. */
10045 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10046 ret = notifier_to_errno(ret);
10048 /* Expect explicit free_netdev() on failure */
10049 dev->needs_free_netdev = false;
10050 unregister_netdevice_queue(dev, NULL);
10054 * Prevent userspace races by waiting until the network
10055 * device is fully setup before sending notifications.
10057 if (!dev->rtnl_link_ops ||
10058 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10059 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10065 if (dev->netdev_ops->ndo_uninit)
10066 dev->netdev_ops->ndo_uninit(dev);
10067 if (dev->priv_destructor)
10068 dev->priv_destructor(dev);
10070 netdev_name_node_free(dev->name_node);
10073 EXPORT_SYMBOL(register_netdevice);
10076 * init_dummy_netdev - init a dummy network device for NAPI
10077 * @dev: device to init
10079 * This takes a network device structure and initialize the minimum
10080 * amount of fields so it can be used to schedule NAPI polls without
10081 * registering a full blown interface. This is to be used by drivers
10082 * that need to tie several hardware interfaces to a single NAPI
10083 * poll scheduler due to HW limitations.
10085 int init_dummy_netdev(struct net_device *dev)
10087 /* Clear everything. Note we don't initialize spinlocks
10088 * are they aren't supposed to be taken by any of the
10089 * NAPI code and this dummy netdev is supposed to be
10090 * only ever used for NAPI polls
10092 memset(dev, 0, sizeof(struct net_device));
10094 /* make sure we BUG if trying to hit standard
10095 * register/unregister code path
10097 dev->reg_state = NETREG_DUMMY;
10099 /* NAPI wants this */
10100 INIT_LIST_HEAD(&dev->napi_list);
10102 /* a dummy interface is started by default */
10103 set_bit(__LINK_STATE_PRESENT, &dev->state);
10104 set_bit(__LINK_STATE_START, &dev->state);
10106 /* napi_busy_loop stats accounting wants this */
10107 dev_net_set(dev, &init_net);
10109 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10110 * because users of this 'device' dont need to change
10116 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10120 * register_netdev - register a network device
10121 * @dev: device to register
10123 * Take a completed network device structure and add it to the kernel
10124 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10125 * chain. 0 is returned on success. A negative errno code is returned
10126 * on a failure to set up the device, or if the name is a duplicate.
10128 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10129 * and expands the device name if you passed a format string to
10132 int register_netdev(struct net_device *dev)
10136 if (rtnl_lock_killable())
10138 err = register_netdevice(dev);
10142 EXPORT_SYMBOL(register_netdev);
10144 int netdev_refcnt_read(const struct net_device *dev)
10148 for_each_possible_cpu(i)
10149 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10152 EXPORT_SYMBOL(netdev_refcnt_read);
10154 #define WAIT_REFS_MIN_MSECS 1
10155 #define WAIT_REFS_MAX_MSECS 250
10157 * netdev_wait_allrefs - wait until all references are gone.
10158 * @dev: target net_device
10160 * This is called when unregistering network devices.
10162 * Any protocol or device that holds a reference should register
10163 * for netdevice notification, and cleanup and put back the
10164 * reference if they receive an UNREGISTER event.
10165 * We can get stuck here if buggy protocols don't correctly
10168 static void netdev_wait_allrefs(struct net_device *dev)
10170 unsigned long rebroadcast_time, warning_time;
10171 int wait = 0, refcnt;
10173 linkwatch_forget_dev(dev);
10175 rebroadcast_time = warning_time = jiffies;
10176 refcnt = netdev_refcnt_read(dev);
10178 while (refcnt != 0) {
10179 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10182 /* Rebroadcast unregister notification */
10183 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10189 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10191 /* We must not have linkwatch events
10192 * pending on unregister. If this
10193 * happens, we simply run the queue
10194 * unscheduled, resulting in a noop
10197 linkwatch_run_queue();
10202 rebroadcast_time = jiffies;
10207 wait = WAIT_REFS_MIN_MSECS;
10210 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10213 refcnt = netdev_refcnt_read(dev);
10215 if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
10216 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10217 dev->name, refcnt);
10218 warning_time = jiffies;
10223 /* The sequence is:
10227 * register_netdevice(x1);
10228 * register_netdevice(x2);
10230 * unregister_netdevice(y1);
10231 * unregister_netdevice(y2);
10237 * We are invoked by rtnl_unlock().
10238 * This allows us to deal with problems:
10239 * 1) We can delete sysfs objects which invoke hotplug
10240 * without deadlocking with linkwatch via keventd.
10241 * 2) Since we run with the RTNL semaphore not held, we can sleep
10242 * safely in order to wait for the netdev refcnt to drop to zero.
10244 * We must not return until all unregister events added during
10245 * the interval the lock was held have been completed.
10247 void netdev_run_todo(void)
10249 struct list_head list;
10250 #ifdef CONFIG_LOCKDEP
10251 struct list_head unlink_list;
10253 list_replace_init(&net_unlink_list, &unlink_list);
10255 while (!list_empty(&unlink_list)) {
10256 struct net_device *dev = list_first_entry(&unlink_list,
10259 list_del_init(&dev->unlink_list);
10260 dev->nested_level = dev->lower_level - 1;
10264 /* Snapshot list, allow later requests */
10265 list_replace_init(&net_todo_list, &list);
10270 /* Wait for rcu callbacks to finish before next phase */
10271 if (!list_empty(&list))
10274 while (!list_empty(&list)) {
10275 struct net_device *dev
10276 = list_first_entry(&list, struct net_device, todo_list);
10277 list_del(&dev->todo_list);
10279 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10280 pr_err("network todo '%s' but state %d\n",
10281 dev->name, dev->reg_state);
10286 dev->reg_state = NETREG_UNREGISTERED;
10288 netdev_wait_allrefs(dev);
10291 BUG_ON(netdev_refcnt_read(dev));
10292 BUG_ON(!list_empty(&dev->ptype_all));
10293 BUG_ON(!list_empty(&dev->ptype_specific));
10294 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10295 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10296 #if IS_ENABLED(CONFIG_DECNET)
10297 WARN_ON(dev->dn_ptr);
10299 if (dev->priv_destructor)
10300 dev->priv_destructor(dev);
10301 if (dev->needs_free_netdev)
10304 /* Report a network device has been unregistered */
10306 dev_net(dev)->dev_unreg_count--;
10308 wake_up(&netdev_unregistering_wq);
10310 /* Free network device */
10311 kobject_put(&dev->dev.kobj);
10315 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10316 * all the same fields in the same order as net_device_stats, with only
10317 * the type differing, but rtnl_link_stats64 may have additional fields
10318 * at the end for newer counters.
10320 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10321 const struct net_device_stats *netdev_stats)
10323 #if BITS_PER_LONG == 64
10324 BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
10325 memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
10326 /* zero out counters that only exist in rtnl_link_stats64 */
10327 memset((char *)stats64 + sizeof(*netdev_stats), 0,
10328 sizeof(*stats64) - sizeof(*netdev_stats));
10330 size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
10331 const unsigned long *src = (const unsigned long *)netdev_stats;
10332 u64 *dst = (u64 *)stats64;
10334 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10335 for (i = 0; i < n; i++)
10337 /* zero out counters that only exist in rtnl_link_stats64 */
10338 memset((char *)stats64 + n * sizeof(u64), 0,
10339 sizeof(*stats64) - n * sizeof(u64));
10342 EXPORT_SYMBOL(netdev_stats_to_stats64);
10345 * dev_get_stats - get network device statistics
10346 * @dev: device to get statistics from
10347 * @storage: place to store stats
10349 * Get network statistics from device. Return @storage.
10350 * The device driver may provide its own method by setting
10351 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10352 * otherwise the internal statistics structure is used.
10354 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10355 struct rtnl_link_stats64 *storage)
10357 const struct net_device_ops *ops = dev->netdev_ops;
10359 if (ops->ndo_get_stats64) {
10360 memset(storage, 0, sizeof(*storage));
10361 ops->ndo_get_stats64(dev, storage);
10362 } else if (ops->ndo_get_stats) {
10363 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10365 netdev_stats_to_stats64(storage, &dev->stats);
10367 storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
10368 storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
10369 storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
10372 EXPORT_SYMBOL(dev_get_stats);
10375 * dev_fetch_sw_netstats - get per-cpu network device statistics
10376 * @s: place to store stats
10377 * @netstats: per-cpu network stats to read from
10379 * Read per-cpu network statistics and populate the related fields in @s.
10381 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10382 const struct pcpu_sw_netstats __percpu *netstats)
10386 for_each_possible_cpu(cpu) {
10387 const struct pcpu_sw_netstats *stats;
10388 struct pcpu_sw_netstats tmp;
10389 unsigned int start;
10391 stats = per_cpu_ptr(netstats, cpu);
10393 start = u64_stats_fetch_begin_irq(&stats->syncp);
10394 tmp.rx_packets = stats->rx_packets;
10395 tmp.rx_bytes = stats->rx_bytes;
10396 tmp.tx_packets = stats->tx_packets;
10397 tmp.tx_bytes = stats->tx_bytes;
10398 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
10400 s->rx_packets += tmp.rx_packets;
10401 s->rx_bytes += tmp.rx_bytes;
10402 s->tx_packets += tmp.tx_packets;
10403 s->tx_bytes += tmp.tx_bytes;
10406 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10408 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10410 struct netdev_queue *queue = dev_ingress_queue(dev);
10412 #ifdef CONFIG_NET_CLS_ACT
10415 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10418 netdev_init_one_queue(dev, queue, NULL);
10419 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10420 queue->qdisc_sleeping = &noop_qdisc;
10421 rcu_assign_pointer(dev->ingress_queue, queue);
10426 static const struct ethtool_ops default_ethtool_ops;
10428 void netdev_set_default_ethtool_ops(struct net_device *dev,
10429 const struct ethtool_ops *ops)
10431 if (dev->ethtool_ops == &default_ethtool_ops)
10432 dev->ethtool_ops = ops;
10434 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10436 void netdev_freemem(struct net_device *dev)
10438 char *addr = (char *)dev - dev->padded;
10444 * alloc_netdev_mqs - allocate network device
10445 * @sizeof_priv: size of private data to allocate space for
10446 * @name: device name format string
10447 * @name_assign_type: origin of device name
10448 * @setup: callback to initialize device
10449 * @txqs: the number of TX subqueues to allocate
10450 * @rxqs: the number of RX subqueues to allocate
10452 * Allocates a struct net_device with private data area for driver use
10453 * and performs basic initialization. Also allocates subqueue structs
10454 * for each queue on the device.
10456 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10457 unsigned char name_assign_type,
10458 void (*setup)(struct net_device *),
10459 unsigned int txqs, unsigned int rxqs)
10461 struct net_device *dev;
10462 unsigned int alloc_size;
10463 struct net_device *p;
10465 BUG_ON(strlen(name) >= sizeof(dev->name));
10468 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10473 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10477 alloc_size = sizeof(struct net_device);
10479 /* ensure 32-byte alignment of private area */
10480 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10481 alloc_size += sizeof_priv;
10483 /* ensure 32-byte alignment of whole construct */
10484 alloc_size += NETDEV_ALIGN - 1;
10486 p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
10490 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10491 dev->padded = (char *)dev - (char *)p;
10493 dev->pcpu_refcnt = alloc_percpu(int);
10494 if (!dev->pcpu_refcnt)
10497 if (dev_addr_init(dev))
10503 dev_net_set(dev, &init_net);
10505 dev->gso_max_size = GSO_MAX_SIZE;
10506 dev->gso_max_segs = GSO_MAX_SEGS;
10507 dev->upper_level = 1;
10508 dev->lower_level = 1;
10509 #ifdef CONFIG_LOCKDEP
10510 dev->nested_level = 0;
10511 INIT_LIST_HEAD(&dev->unlink_list);
10514 INIT_LIST_HEAD(&dev->napi_list);
10515 INIT_LIST_HEAD(&dev->unreg_list);
10516 INIT_LIST_HEAD(&dev->close_list);
10517 INIT_LIST_HEAD(&dev->link_watch_list);
10518 INIT_LIST_HEAD(&dev->adj_list.upper);
10519 INIT_LIST_HEAD(&dev->adj_list.lower);
10520 INIT_LIST_HEAD(&dev->ptype_all);
10521 INIT_LIST_HEAD(&dev->ptype_specific);
10522 INIT_LIST_HEAD(&dev->net_notifier_list);
10523 #ifdef CONFIG_NET_SCHED
10524 hash_init(dev->qdisc_hash);
10526 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10529 if (!dev->tx_queue_len) {
10530 dev->priv_flags |= IFF_NO_QUEUE;
10531 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10534 dev->num_tx_queues = txqs;
10535 dev->real_num_tx_queues = txqs;
10536 if (netif_alloc_netdev_queues(dev))
10539 dev->num_rx_queues = rxqs;
10540 dev->real_num_rx_queues = rxqs;
10541 if (netif_alloc_rx_queues(dev))
10544 strcpy(dev->name, name);
10545 dev->name_assign_type = name_assign_type;
10546 dev->group = INIT_NETDEV_GROUP;
10547 if (!dev->ethtool_ops)
10548 dev->ethtool_ops = &default_ethtool_ops;
10550 nf_hook_ingress_init(dev);
10559 free_percpu(dev->pcpu_refcnt);
10561 netdev_freemem(dev);
10564 EXPORT_SYMBOL(alloc_netdev_mqs);
10567 * free_netdev - free network device
10570 * This function does the last stage of destroying an allocated device
10571 * interface. The reference to the device object is released. If this
10572 * is the last reference then it will be freed.Must be called in process
10575 void free_netdev(struct net_device *dev)
10577 struct napi_struct *p, *n;
10581 /* When called immediately after register_netdevice() failed the unwind
10582 * handling may still be dismantling the device. Handle that case by
10583 * deferring the free.
10585 if (dev->reg_state == NETREG_UNREGISTERING) {
10587 dev->needs_free_netdev = true;
10591 netif_free_tx_queues(dev);
10592 netif_free_rx_queues(dev);
10594 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10596 /* Flush device addresses */
10597 dev_addr_flush(dev);
10599 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10602 free_percpu(dev->pcpu_refcnt);
10603 dev->pcpu_refcnt = NULL;
10604 free_percpu(dev->xdp_bulkq);
10605 dev->xdp_bulkq = NULL;
10607 /* Compatibility with error handling in drivers */
10608 if (dev->reg_state == NETREG_UNINITIALIZED) {
10609 netdev_freemem(dev);
10613 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10614 dev->reg_state = NETREG_RELEASED;
10616 /* will free via device release */
10617 put_device(&dev->dev);
10619 EXPORT_SYMBOL(free_netdev);
10622 * synchronize_net - Synchronize with packet receive processing
10624 * Wait for packets currently being received to be done.
10625 * Does not block later packets from starting.
10627 void synchronize_net(void)
10630 if (rtnl_is_locked())
10631 synchronize_rcu_expedited();
10635 EXPORT_SYMBOL(synchronize_net);
10638 * unregister_netdevice_queue - remove device from the kernel
10642 * This function shuts down a device interface and removes it
10643 * from the kernel tables.
10644 * If head not NULL, device is queued to be unregistered later.
10646 * Callers must hold the rtnl semaphore. You may want
10647 * unregister_netdev() instead of this.
10650 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10655 list_move_tail(&dev->unreg_list, head);
10659 list_add(&dev->unreg_list, &single);
10660 unregister_netdevice_many(&single);
10663 EXPORT_SYMBOL(unregister_netdevice_queue);
10666 * unregister_netdevice_many - unregister many devices
10667 * @head: list of devices
10669 * Note: As most callers use a stack allocated list_head,
10670 * we force a list_del() to make sure stack wont be corrupted later.
10672 void unregister_netdevice_many(struct list_head *head)
10674 struct net_device *dev, *tmp;
10675 LIST_HEAD(close_head);
10677 BUG_ON(dev_boot_phase);
10680 if (list_empty(head))
10683 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10684 /* Some devices call without registering
10685 * for initialization unwind. Remove those
10686 * devices and proceed with the remaining.
10688 if (dev->reg_state == NETREG_UNINITIALIZED) {
10689 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10693 list_del(&dev->unreg_list);
10696 dev->dismantle = true;
10697 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10700 /* If device is running, close it first. */
10701 list_for_each_entry(dev, head, unreg_list)
10702 list_add_tail(&dev->close_list, &close_head);
10703 dev_close_many(&close_head, true);
10705 list_for_each_entry(dev, head, unreg_list) {
10706 /* And unlink it from device chain. */
10707 unlist_netdevice(dev);
10709 dev->reg_state = NETREG_UNREGISTERING;
10711 flush_all_backlogs();
10715 list_for_each_entry(dev, head, unreg_list) {
10716 struct sk_buff *skb = NULL;
10718 /* Shutdown queueing discipline. */
10721 dev_xdp_uninstall(dev);
10723 /* Notify protocols, that we are about to destroy
10724 * this device. They should clean all the things.
10726 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10728 if (!dev->rtnl_link_ops ||
10729 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10730 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10731 GFP_KERNEL, NULL, 0);
10734 * Flush the unicast and multicast chains
10739 netdev_name_node_alt_flush(dev);
10740 netdev_name_node_free(dev->name_node);
10742 if (dev->netdev_ops->ndo_uninit)
10743 dev->netdev_ops->ndo_uninit(dev);
10746 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
10748 /* Notifier chain MUST detach us all upper devices. */
10749 WARN_ON(netdev_has_any_upper_dev(dev));
10750 WARN_ON(netdev_has_any_lower_dev(dev));
10752 /* Remove entries from kobject tree */
10753 netdev_unregister_kobject(dev);
10755 /* Remove XPS queueing entries */
10756 netif_reset_xps_queues_gt(dev, 0);
10762 list_for_each_entry(dev, head, unreg_list) {
10769 EXPORT_SYMBOL(unregister_netdevice_many);
10772 * unregister_netdev - remove device from the kernel
10775 * This function shuts down a device interface and removes it
10776 * from the kernel tables.
10778 * This is just a wrapper for unregister_netdevice that takes
10779 * the rtnl semaphore. In general you want to use this and not
10780 * unregister_netdevice.
10782 void unregister_netdev(struct net_device *dev)
10785 unregister_netdevice(dev);
10788 EXPORT_SYMBOL(unregister_netdev);
10791 * dev_change_net_namespace - move device to different nethost namespace
10793 * @net: network namespace
10794 * @pat: If not NULL name pattern to try if the current device name
10795 * is already taken in the destination network namespace.
10797 * This function shuts down a device interface and moves it
10798 * to a new network namespace. On success 0 is returned, on
10799 * a failure a netagive errno code is returned.
10801 * Callers must hold the rtnl semaphore.
10804 int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
10806 struct net *net_old = dev_net(dev);
10807 int err, new_nsid, new_ifindex;
10811 /* Don't allow namespace local devices to be moved. */
10813 if (dev->features & NETIF_F_NETNS_LOCAL)
10816 /* Ensure the device has been registrered */
10817 if (dev->reg_state != NETREG_REGISTERED)
10820 /* Get out if there is nothing todo */
10822 if (net_eq(net_old, net))
10825 /* Pick the destination device name, and ensure
10826 * we can use it in the destination network namespace.
10829 if (__dev_get_by_name(net, dev->name)) {
10830 /* We get here if we can't use the current device name */
10833 err = dev_get_valid_name(net, dev, pat);
10839 * And now a mini version of register_netdevice unregister_netdevice.
10842 /* If device is running close it first. */
10845 /* And unlink it from device chain */
10846 unlist_netdevice(dev);
10850 /* Shutdown queueing discipline. */
10853 /* Notify protocols, that we are about to destroy
10854 * this device. They should clean all the things.
10856 * Note that dev->reg_state stays at NETREG_REGISTERED.
10857 * This is wanted because this way 8021q and macvlan know
10858 * the device is just moving and can keep their slaves up.
10860 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10863 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
10864 /* If there is an ifindex conflict assign a new one */
10865 if (__dev_get_by_index(net, dev->ifindex))
10866 new_ifindex = dev_new_index(net);
10868 new_ifindex = dev->ifindex;
10870 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
10874 * Flush the unicast and multicast chains
10879 /* Send a netdev-removed uevent to the old namespace */
10880 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
10881 netdev_adjacent_del_links(dev);
10883 /* Move per-net netdevice notifiers that are following the netdevice */
10884 move_netdevice_notifiers_dev_net(dev, net);
10886 /* Actually switch the network namespace */
10887 dev_net_set(dev, net);
10888 dev->ifindex = new_ifindex;
10890 /* Send a netdev-add uevent to the new namespace */
10891 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
10892 netdev_adjacent_add_links(dev);
10894 /* Fixup kobjects */
10895 err = device_rename(&dev->dev, dev->name);
10898 /* Adapt owner in case owning user namespace of target network
10899 * namespace is different from the original one.
10901 err = netdev_change_owner(dev, net_old, net);
10904 /* Add the device back in the hashes */
10905 list_netdevice(dev);
10907 /* Notify protocols, that a new device appeared. */
10908 call_netdevice_notifiers(NETDEV_REGISTER, dev);
10911 * Prevent userspace races by waiting until the network
10912 * device is fully setup before sending notifications.
10914 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
10921 EXPORT_SYMBOL_GPL(dev_change_net_namespace);
10923 static int dev_cpu_dead(unsigned int oldcpu)
10925 struct sk_buff **list_skb;
10926 struct sk_buff *skb;
10928 struct softnet_data *sd, *oldsd, *remsd = NULL;
10930 local_irq_disable();
10931 cpu = smp_processor_id();
10932 sd = &per_cpu(softnet_data, cpu);
10933 oldsd = &per_cpu(softnet_data, oldcpu);
10935 /* Find end of our completion_queue. */
10936 list_skb = &sd->completion_queue;
10938 list_skb = &(*list_skb)->next;
10939 /* Append completion queue from offline CPU. */
10940 *list_skb = oldsd->completion_queue;
10941 oldsd->completion_queue = NULL;
10943 /* Append output queue from offline CPU. */
10944 if (oldsd->output_queue) {
10945 *sd->output_queue_tailp = oldsd->output_queue;
10946 sd->output_queue_tailp = oldsd->output_queue_tailp;
10947 oldsd->output_queue = NULL;
10948 oldsd->output_queue_tailp = &oldsd->output_queue;
10950 /* Append NAPI poll list from offline CPU, with one exception :
10951 * process_backlog() must be called by cpu owning percpu backlog.
10952 * We properly handle process_queue & input_pkt_queue later.
10954 while (!list_empty(&oldsd->poll_list)) {
10955 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
10956 struct napi_struct,
10959 list_del_init(&napi->poll_list);
10960 if (napi->poll == process_backlog)
10963 ____napi_schedule(sd, napi);
10966 raise_softirq_irqoff(NET_TX_SOFTIRQ);
10967 local_irq_enable();
10970 remsd = oldsd->rps_ipi_list;
10971 oldsd->rps_ipi_list = NULL;
10973 /* send out pending IPI's on offline CPU */
10974 net_rps_send_ipi(remsd);
10976 /* Process offline CPU's input_pkt_queue */
10977 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
10979 input_queue_head_incr(oldsd);
10981 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
10983 input_queue_head_incr(oldsd);
10990 * netdev_increment_features - increment feature set by one
10991 * @all: current feature set
10992 * @one: new feature set
10993 * @mask: mask feature set
10995 * Computes a new feature set after adding a device with feature set
10996 * @one to the master device with current feature set @all. Will not
10997 * enable anything that is off in @mask. Returns the new feature set.
10999 netdev_features_t netdev_increment_features(netdev_features_t all,
11000 netdev_features_t one, netdev_features_t mask)
11002 if (mask & NETIF_F_HW_CSUM)
11003 mask |= NETIF_F_CSUM_MASK;
11004 mask |= NETIF_F_VLAN_CHALLENGED;
11006 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11007 all &= one | ~NETIF_F_ALL_FOR_ALL;
11009 /* If one device supports hw checksumming, set for all. */
11010 if (all & NETIF_F_HW_CSUM)
11011 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11015 EXPORT_SYMBOL(netdev_increment_features);
11017 static struct hlist_head * __net_init netdev_create_hash(void)
11020 struct hlist_head *hash;
11022 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11024 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11025 INIT_HLIST_HEAD(&hash[i]);
11030 /* Initialize per network namespace state */
11031 static int __net_init netdev_init(struct net *net)
11033 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11034 8 * sizeof_field(struct napi_struct, gro_bitmask));
11036 if (net != &init_net)
11037 INIT_LIST_HEAD(&net->dev_base_head);
11039 net->dev_name_head = netdev_create_hash();
11040 if (net->dev_name_head == NULL)
11043 net->dev_index_head = netdev_create_hash();
11044 if (net->dev_index_head == NULL)
11047 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11052 kfree(net->dev_name_head);
11058 * netdev_drivername - network driver for the device
11059 * @dev: network device
11061 * Determine network driver for device.
11063 const char *netdev_drivername(const struct net_device *dev)
11065 const struct device_driver *driver;
11066 const struct device *parent;
11067 const char *empty = "";
11069 parent = dev->dev.parent;
11073 driver = parent->driver;
11074 if (driver && driver->name)
11075 return driver->name;
11079 static void __netdev_printk(const char *level, const struct net_device *dev,
11080 struct va_format *vaf)
11082 if (dev && dev->dev.parent) {
11083 dev_printk_emit(level[1] - '0',
11086 dev_driver_string(dev->dev.parent),
11087 dev_name(dev->dev.parent),
11088 netdev_name(dev), netdev_reg_state(dev),
11091 printk("%s%s%s: %pV",
11092 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11094 printk("%s(NULL net_device): %pV", level, vaf);
11098 void netdev_printk(const char *level, const struct net_device *dev,
11099 const char *format, ...)
11101 struct va_format vaf;
11104 va_start(args, format);
11109 __netdev_printk(level, dev, &vaf);
11113 EXPORT_SYMBOL(netdev_printk);
11115 #define define_netdev_printk_level(func, level) \
11116 void func(const struct net_device *dev, const char *fmt, ...) \
11118 struct va_format vaf; \
11121 va_start(args, fmt); \
11126 __netdev_printk(level, dev, &vaf); \
11130 EXPORT_SYMBOL(func);
11132 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11133 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11134 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11135 define_netdev_printk_level(netdev_err, KERN_ERR);
11136 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11137 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11138 define_netdev_printk_level(netdev_info, KERN_INFO);
11140 static void __net_exit netdev_exit(struct net *net)
11142 kfree(net->dev_name_head);
11143 kfree(net->dev_index_head);
11144 if (net != &init_net)
11145 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11148 static struct pernet_operations __net_initdata netdev_net_ops = {
11149 .init = netdev_init,
11150 .exit = netdev_exit,
11153 static void __net_exit default_device_exit(struct net *net)
11155 struct net_device *dev, *aux;
11157 * Push all migratable network devices back to the
11158 * initial network namespace
11161 for_each_netdev_safe(net, dev, aux) {
11163 char fb_name[IFNAMSIZ];
11165 /* Ignore unmoveable devices (i.e. loopback) */
11166 if (dev->features & NETIF_F_NETNS_LOCAL)
11169 /* Leave virtual devices for the generic cleanup */
11170 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11173 /* Push remaining network devices to init_net */
11174 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11175 if (__dev_get_by_name(&init_net, fb_name))
11176 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11177 err = dev_change_net_namespace(dev, &init_net, fb_name);
11179 pr_emerg("%s: failed to move %s to init_net: %d\n",
11180 __func__, dev->name, err);
11187 static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
11189 /* Return with the rtnl_lock held when there are no network
11190 * devices unregistering in any network namespace in net_list.
11193 bool unregistering;
11194 DEFINE_WAIT_FUNC(wait, woken_wake_function);
11196 add_wait_queue(&netdev_unregistering_wq, &wait);
11198 unregistering = false;
11200 list_for_each_entry(net, net_list, exit_list) {
11201 if (net->dev_unreg_count > 0) {
11202 unregistering = true;
11206 if (!unregistering)
11210 wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
11212 remove_wait_queue(&netdev_unregistering_wq, &wait);
11215 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11217 /* At exit all network devices most be removed from a network
11218 * namespace. Do this in the reverse order of registration.
11219 * Do this across as many network namespaces as possible to
11220 * improve batching efficiency.
11222 struct net_device *dev;
11224 LIST_HEAD(dev_kill_list);
11226 /* To prevent network device cleanup code from dereferencing
11227 * loopback devices or network devices that have been freed
11228 * wait here for all pending unregistrations to complete,
11229 * before unregistring the loopback device and allowing the
11230 * network namespace be freed.
11232 * The netdev todo list containing all network devices
11233 * unregistrations that happen in default_device_exit_batch
11234 * will run in the rtnl_unlock() at the end of
11235 * default_device_exit_batch.
11237 rtnl_lock_unregistering(net_list);
11238 list_for_each_entry(net, net_list, exit_list) {
11239 for_each_netdev_reverse(net, dev) {
11240 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11241 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11243 unregister_netdevice_queue(dev, &dev_kill_list);
11246 unregister_netdevice_many(&dev_kill_list);
11250 static struct pernet_operations __net_initdata default_device_ops = {
11251 .exit = default_device_exit,
11252 .exit_batch = default_device_exit_batch,
11256 * Initialize the DEV module. At boot time this walks the device list and
11257 * unhooks any devices that fail to initialise (normally hardware not
11258 * present) and leaves us with a valid list of present and active devices.
11263 * This is called single threaded during boot, so no need
11264 * to take the rtnl semaphore.
11266 static int __init net_dev_init(void)
11268 int i, rc = -ENOMEM;
11270 BUG_ON(!dev_boot_phase);
11272 if (dev_proc_init())
11275 if (netdev_kobject_init())
11278 INIT_LIST_HEAD(&ptype_all);
11279 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11280 INIT_LIST_HEAD(&ptype_base[i]);
11282 INIT_LIST_HEAD(&offload_base);
11284 if (register_pernet_subsys(&netdev_net_ops))
11288 * Initialise the packet receive queues.
11291 for_each_possible_cpu(i) {
11292 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11293 struct softnet_data *sd = &per_cpu(softnet_data, i);
11295 INIT_WORK(flush, flush_backlog);
11297 skb_queue_head_init(&sd->input_pkt_queue);
11298 skb_queue_head_init(&sd->process_queue);
11299 #ifdef CONFIG_XFRM_OFFLOAD
11300 skb_queue_head_init(&sd->xfrm_backlog);
11302 INIT_LIST_HEAD(&sd->poll_list);
11303 sd->output_queue_tailp = &sd->output_queue;
11305 sd->csd.func = rps_trigger_softirq;
11310 init_gro_hash(&sd->backlog);
11311 sd->backlog.poll = process_backlog;
11312 sd->backlog.weight = weight_p;
11315 dev_boot_phase = 0;
11317 /* The loopback device is special if any other network devices
11318 * is present in a network namespace the loopback device must
11319 * be present. Since we now dynamically allocate and free the
11320 * loopback device ensure this invariant is maintained by
11321 * keeping the loopback device as the first device on the
11322 * list of network devices. Ensuring the loopback devices
11323 * is the first device that appears and the last network device
11326 if (register_pernet_device(&loopback_net_ops))
11329 if (register_pernet_device(&default_device_ops))
11332 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11333 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11335 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11336 NULL, dev_cpu_dead);
11343 subsys_initcall(net_dev_init);