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/bitmap.h>
73 #include <linux/capability.h>
74 #include <linux/cpu.h>
75 #include <linux/types.h>
76 #include <linux/kernel.h>
77 #include <linux/hash.h>
78 #include <linux/slab.h>
79 #include <linux/sched.h>
80 #include <linux/sched/mm.h>
81 #include <linux/mutex.h>
82 #include <linux/rwsem.h>
83 #include <linux/string.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/errno.h>
88 #include <linux/interrupt.h>
89 #include <linux/if_ether.h>
90 #include <linux/netdevice.h>
91 #include <linux/etherdevice.h>
92 #include <linux/ethtool.h>
93 #include <linux/skbuff.h>
94 #include <linux/kthread.h>
95 #include <linux/bpf.h>
96 #include <linux/bpf_trace.h>
97 #include <net/net_namespace.h>
99 #include <net/busy_poll.h>
100 #include <linux/rtnetlink.h>
101 #include <linux/stat.h>
104 #include <net/dst_metadata.h>
106 #include <net/pkt_sched.h>
107 #include <net/pkt_cls.h>
108 #include <net/checksum.h>
109 #include <net/xfrm.h>
111 #include <linux/highmem.h>
112 #include <linux/init.h>
113 #include <linux/module.h>
114 #include <linux/netpoll.h>
115 #include <linux/rcupdate.h>
116 #include <linux/delay.h>
117 #include <net/iw_handler.h>
118 #include <asm/current.h>
119 #include <linux/audit.h>
120 #include <linux/dmaengine.h>
121 #include <linux/err.h>
122 #include <linux/ctype.h>
123 #include <linux/if_arp.h>
124 #include <linux/if_vlan.h>
125 #include <linux/ip.h>
127 #include <net/mpls.h>
128 #include <linux/ipv6.h>
129 #include <linux/in.h>
130 #include <linux/jhash.h>
131 #include <linux/random.h>
132 #include <trace/events/napi.h>
133 #include <trace/events/net.h>
134 #include <trace/events/skb.h>
135 #include <trace/events/qdisc.h>
136 #include <trace/events/xdp.h>
137 #include <linux/inetdevice.h>
138 #include <linux/cpu_rmap.h>
139 #include <linux/static_key.h>
140 #include <linux/hashtable.h>
141 #include <linux/vmalloc.h>
142 #include <linux/if_macvlan.h>
143 #include <linux/errqueue.h>
144 #include <linux/hrtimer.h>
145 #include <linux/netfilter_netdev.h>
146 #include <linux/crash_dump.h>
147 #include <linux/sctp.h>
148 #include <net/udp_tunnel.h>
149 #include <linux/net_namespace.h>
150 #include <linux/indirect_call_wrapper.h>
151 #include <net/devlink.h>
152 #include <linux/pm_runtime.h>
153 #include <linux/prandom.h>
154 #include <linux/once_lite.h>
155 #include <net/netdev_rx_queue.h>
158 #include "net-sysfs.h"
160 static DEFINE_SPINLOCK(ptype_lock);
161 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
162 struct list_head ptype_all __read_mostly; /* Taps */
164 static int netif_rx_internal(struct sk_buff *skb);
165 static int call_netdevice_notifiers_extack(unsigned long val,
166 struct net_device *dev,
167 struct netlink_ext_ack *extack);
168 static struct napi_struct *napi_by_id(unsigned int napi_id);
171 * The @dev_base_head list is protected by @dev_base_lock and the rtnl
174 * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
176 * Writers must hold the rtnl semaphore while they loop through the
177 * dev_base_head list, and hold dev_base_lock for writing when they do the
178 * actual updates. This allows pure readers to access the list even
179 * while a writer is preparing to update it.
181 * To put it another way, dev_base_lock is held for writing only to
182 * protect against pure readers; the rtnl semaphore provides the
183 * protection against other writers.
185 * See, for example usages, register_netdevice() and
186 * unregister_netdevice(), which must be called with the rtnl
189 DEFINE_RWLOCK(dev_base_lock);
190 EXPORT_SYMBOL(dev_base_lock);
192 static DEFINE_MUTEX(ifalias_mutex);
194 /* protects napi_hash addition/deletion and napi_gen_id */
195 static DEFINE_SPINLOCK(napi_hash_lock);
197 static unsigned int napi_gen_id = NR_CPUS;
198 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
200 static DECLARE_RWSEM(devnet_rename_sem);
202 static inline void dev_base_seq_inc(struct net *net)
204 while (++net->dev_base_seq == 0)
208 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
210 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
212 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
215 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
217 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
220 static inline void rps_lock_irqsave(struct softnet_data *sd,
221 unsigned long *flags)
223 if (IS_ENABLED(CONFIG_RPS))
224 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
225 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
226 local_irq_save(*flags);
229 static inline void rps_lock_irq_disable(struct softnet_data *sd)
231 if (IS_ENABLED(CONFIG_RPS))
232 spin_lock_irq(&sd->input_pkt_queue.lock);
233 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
237 static inline void rps_unlock_irq_restore(struct softnet_data *sd,
238 unsigned long *flags)
240 if (IS_ENABLED(CONFIG_RPS))
241 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
242 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
243 local_irq_restore(*flags);
246 static inline void rps_unlock_irq_enable(struct softnet_data *sd)
248 if (IS_ENABLED(CONFIG_RPS))
249 spin_unlock_irq(&sd->input_pkt_queue.lock);
250 else if (!IS_ENABLED(CONFIG_PREEMPT_RT))
254 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
257 struct netdev_name_node *name_node;
259 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
262 INIT_HLIST_NODE(&name_node->hlist);
263 name_node->dev = dev;
264 name_node->name = name;
268 static struct netdev_name_node *
269 netdev_name_node_head_alloc(struct net_device *dev)
271 struct netdev_name_node *name_node;
273 name_node = netdev_name_node_alloc(dev, dev->name);
276 INIT_LIST_HEAD(&name_node->list);
280 static void netdev_name_node_free(struct netdev_name_node *name_node)
285 static void netdev_name_node_add(struct net *net,
286 struct netdev_name_node *name_node)
288 hlist_add_head_rcu(&name_node->hlist,
289 dev_name_hash(net, name_node->name));
292 static void netdev_name_node_del(struct netdev_name_node *name_node)
294 hlist_del_rcu(&name_node->hlist);
297 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
300 struct hlist_head *head = dev_name_hash(net, name);
301 struct netdev_name_node *name_node;
303 hlist_for_each_entry(name_node, head, hlist)
304 if (!strcmp(name_node->name, name))
309 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
312 struct hlist_head *head = dev_name_hash(net, name);
313 struct netdev_name_node *name_node;
315 hlist_for_each_entry_rcu(name_node, head, hlist)
316 if (!strcmp(name_node->name, name))
321 bool netdev_name_in_use(struct net *net, const char *name)
323 return netdev_name_node_lookup(net, name);
325 EXPORT_SYMBOL(netdev_name_in_use);
327 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
329 struct netdev_name_node *name_node;
330 struct net *net = dev_net(dev);
332 name_node = netdev_name_node_lookup(net, name);
335 name_node = netdev_name_node_alloc(dev, name);
338 netdev_name_node_add(net, name_node);
339 /* The node that holds dev->name acts as a head of per-device list. */
340 list_add_tail(&name_node->list, &dev->name_node->list);
345 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
347 list_del(&name_node->list);
348 netdev_name_node_del(name_node);
349 kfree(name_node->name);
350 netdev_name_node_free(name_node);
353 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
355 struct netdev_name_node *name_node;
356 struct net *net = dev_net(dev);
358 name_node = netdev_name_node_lookup(net, name);
361 /* lookup might have found our primary name or a name belonging
364 if (name_node == dev->name_node || name_node->dev != dev)
367 __netdev_name_node_alt_destroy(name_node);
372 static void netdev_name_node_alt_flush(struct net_device *dev)
374 struct netdev_name_node *name_node, *tmp;
376 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
377 __netdev_name_node_alt_destroy(name_node);
380 /* Device list insertion */
381 static void list_netdevice(struct net_device *dev)
383 struct net *net = dev_net(dev);
387 write_lock(&dev_base_lock);
388 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
389 netdev_name_node_add(net, dev->name_node);
390 hlist_add_head_rcu(&dev->index_hlist,
391 dev_index_hash(net, dev->ifindex));
392 write_unlock(&dev_base_lock);
393 /* We reserved the ifindex, this can't fail */
394 WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL));
396 dev_base_seq_inc(net);
399 /* Device list removal
400 * caller must respect a RCU grace period before freeing/reusing dev
402 static void unlist_netdevice(struct net_device *dev, bool lock)
404 struct net *net = dev_net(dev);
408 xa_erase(&net->dev_by_index, dev->ifindex);
410 /* Unlink dev from the device chain */
412 write_lock(&dev_base_lock);
413 list_del_rcu(&dev->dev_list);
414 netdev_name_node_del(dev->name_node);
415 hlist_del_rcu(&dev->index_hlist);
417 write_unlock(&dev_base_lock);
419 dev_base_seq_inc(dev_net(dev));
426 static RAW_NOTIFIER_HEAD(netdev_chain);
429 * Device drivers call our routines to queue packets here. We empty the
430 * queue in the local softnet handler.
433 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
434 EXPORT_PER_CPU_SYMBOL(softnet_data);
436 #ifdef CONFIG_LOCKDEP
438 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
439 * according to dev->type
441 static const unsigned short netdev_lock_type[] = {
442 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
443 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
444 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
445 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
446 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
447 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
448 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
449 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
450 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
451 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
452 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
453 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
454 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
455 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
456 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
458 static const char *const netdev_lock_name[] = {
459 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
460 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
461 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
462 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
463 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
464 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
465 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
466 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
467 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
468 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
469 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
470 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
471 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
472 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
473 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
475 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
476 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
478 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
482 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
483 if (netdev_lock_type[i] == dev_type)
485 /* the last key is used by default */
486 return ARRAY_SIZE(netdev_lock_type) - 1;
489 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
490 unsigned short dev_type)
494 i = netdev_lock_pos(dev_type);
495 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
496 netdev_lock_name[i]);
499 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
503 i = netdev_lock_pos(dev->type);
504 lockdep_set_class_and_name(&dev->addr_list_lock,
505 &netdev_addr_lock_key[i],
506 netdev_lock_name[i]);
509 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
510 unsigned short dev_type)
514 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
519 /*******************************************************************************
521 * Protocol management and registration routines
523 *******************************************************************************/
527 * Add a protocol ID to the list. Now that the input handler is
528 * smarter we can dispense with all the messy stuff that used to be
531 * BEWARE!!! Protocol handlers, mangling input packets,
532 * MUST BE last in hash buckets and checking protocol handlers
533 * MUST start from promiscuous ptype_all chain in net_bh.
534 * It is true now, do not change it.
535 * Explanation follows: if protocol handler, mangling packet, will
536 * be the first on list, it is not able to sense, that packet
537 * is cloned and should be copied-on-write, so that it will
538 * change it and subsequent readers will get broken packet.
542 static inline struct list_head *ptype_head(const struct packet_type *pt)
544 if (pt->type == htons(ETH_P_ALL))
545 return pt->dev ? &pt->dev->ptype_all : &ptype_all;
547 return pt->dev ? &pt->dev->ptype_specific :
548 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
552 * dev_add_pack - add packet handler
553 * @pt: packet type declaration
555 * Add a protocol handler to the networking stack. The passed &packet_type
556 * is linked into kernel lists and may not be freed until it has been
557 * removed from the kernel lists.
559 * This call does not sleep therefore it can not
560 * guarantee all CPU's that are in middle of receiving packets
561 * will see the new packet type (until the next received packet).
564 void dev_add_pack(struct packet_type *pt)
566 struct list_head *head = ptype_head(pt);
568 spin_lock(&ptype_lock);
569 list_add_rcu(&pt->list, head);
570 spin_unlock(&ptype_lock);
572 EXPORT_SYMBOL(dev_add_pack);
575 * __dev_remove_pack - remove packet handler
576 * @pt: packet type declaration
578 * Remove a protocol handler that was previously added to the kernel
579 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
580 * from the kernel lists and can be freed or reused once this function
583 * The packet type might still be in use by receivers
584 * and must not be freed until after all the CPU's have gone
585 * through a quiescent state.
587 void __dev_remove_pack(struct packet_type *pt)
589 struct list_head *head = ptype_head(pt);
590 struct packet_type *pt1;
592 spin_lock(&ptype_lock);
594 list_for_each_entry(pt1, head, list) {
596 list_del_rcu(&pt->list);
601 pr_warn("dev_remove_pack: %p not found\n", pt);
603 spin_unlock(&ptype_lock);
605 EXPORT_SYMBOL(__dev_remove_pack);
608 * dev_remove_pack - remove packet handler
609 * @pt: packet type declaration
611 * Remove a protocol handler that was previously added to the kernel
612 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
613 * from the kernel lists and can be freed or reused once this function
616 * This call sleeps to guarantee that no CPU is looking at the packet
619 void dev_remove_pack(struct packet_type *pt)
621 __dev_remove_pack(pt);
625 EXPORT_SYMBOL(dev_remove_pack);
628 /*******************************************************************************
630 * Device Interface Subroutines
632 *******************************************************************************/
635 * dev_get_iflink - get 'iflink' value of a interface
636 * @dev: targeted interface
638 * Indicates the ifindex the interface is linked to.
639 * Physical interfaces have the same 'ifindex' and 'iflink' values.
642 int dev_get_iflink(const struct net_device *dev)
644 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
645 return dev->netdev_ops->ndo_get_iflink(dev);
649 EXPORT_SYMBOL(dev_get_iflink);
652 * dev_fill_metadata_dst - Retrieve tunnel egress information.
653 * @dev: targeted interface
656 * For better visibility of tunnel traffic OVS needs to retrieve
657 * egress tunnel information for a packet. Following API allows
658 * user to get this info.
660 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
662 struct ip_tunnel_info *info;
664 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
667 info = skb_tunnel_info_unclone(skb);
670 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
673 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
675 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
677 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
679 int k = stack->num_paths++;
681 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
684 return &stack->path[k];
687 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
688 struct net_device_path_stack *stack)
690 const struct net_device *last_dev;
691 struct net_device_path_ctx ctx = {
694 struct net_device_path *path;
697 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
698 stack->num_paths = 0;
699 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
701 path = dev_fwd_path(stack);
705 memset(path, 0, sizeof(struct net_device_path));
706 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
710 if (WARN_ON_ONCE(last_dev == ctx.dev))
717 path = dev_fwd_path(stack);
720 path->type = DEV_PATH_ETHERNET;
725 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
728 * __dev_get_by_name - find a device by its name
729 * @net: the applicable net namespace
730 * @name: name to find
732 * Find an interface by name. Must be called under RTNL semaphore
733 * or @dev_base_lock. If the name is found a pointer to the device
734 * is returned. If the name is not found then %NULL is returned. The
735 * reference counters are not incremented so the caller must be
736 * careful with locks.
739 struct net_device *__dev_get_by_name(struct net *net, const char *name)
741 struct netdev_name_node *node_name;
743 node_name = netdev_name_node_lookup(net, name);
744 return node_name ? node_name->dev : NULL;
746 EXPORT_SYMBOL(__dev_get_by_name);
749 * dev_get_by_name_rcu - find a device by its name
750 * @net: the applicable net namespace
751 * @name: name to find
753 * Find an interface by name.
754 * If the name is found a pointer to the device is returned.
755 * If the name is not found then %NULL is returned.
756 * The reference counters are not incremented so the caller must be
757 * careful with locks. The caller must hold RCU lock.
760 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
762 struct netdev_name_node *node_name;
764 node_name = netdev_name_node_lookup_rcu(net, name);
765 return node_name ? node_name->dev : NULL;
767 EXPORT_SYMBOL(dev_get_by_name_rcu);
769 /* Deprecated for new users, call netdev_get_by_name() instead */
770 struct net_device *dev_get_by_name(struct net *net, const char *name)
772 struct net_device *dev;
775 dev = dev_get_by_name_rcu(net, name);
780 EXPORT_SYMBOL(dev_get_by_name);
783 * netdev_get_by_name() - find a device by its name
784 * @net: the applicable net namespace
785 * @name: name to find
786 * @tracker: tracking object for the acquired reference
787 * @gfp: allocation flags for the tracker
789 * Find an interface by name. This can be called from any
790 * context and does its own locking. The returned handle has
791 * the usage count incremented and the caller must use netdev_put() to
792 * release it when it is no longer needed. %NULL is returned if no
793 * matching device is found.
795 struct net_device *netdev_get_by_name(struct net *net, const char *name,
796 netdevice_tracker *tracker, gfp_t gfp)
798 struct net_device *dev;
800 dev = dev_get_by_name(net, name);
802 netdev_tracker_alloc(dev, tracker, gfp);
805 EXPORT_SYMBOL(netdev_get_by_name);
808 * __dev_get_by_index - find a device by its ifindex
809 * @net: the applicable net namespace
810 * @ifindex: index of device
812 * Search for an interface by index. Returns %NULL if the device
813 * is not found or a pointer to the device. The device has not
814 * had its reference counter increased so the caller must be careful
815 * about locking. The caller must hold either the RTNL semaphore
819 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
821 struct net_device *dev;
822 struct hlist_head *head = dev_index_hash(net, ifindex);
824 hlist_for_each_entry(dev, head, index_hlist)
825 if (dev->ifindex == ifindex)
830 EXPORT_SYMBOL(__dev_get_by_index);
833 * dev_get_by_index_rcu - find a device by its ifindex
834 * @net: the applicable net namespace
835 * @ifindex: index of device
837 * Search for an interface by index. Returns %NULL if the device
838 * is not found or a pointer to the device. The device has not
839 * had its reference counter increased so the caller must be careful
840 * about locking. The caller must hold RCU lock.
843 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
845 struct net_device *dev;
846 struct hlist_head *head = dev_index_hash(net, ifindex);
848 hlist_for_each_entry_rcu(dev, head, index_hlist)
849 if (dev->ifindex == ifindex)
854 EXPORT_SYMBOL(dev_get_by_index_rcu);
856 /* Deprecated for new users, call netdev_get_by_index() instead */
857 struct net_device *dev_get_by_index(struct net *net, int ifindex)
859 struct net_device *dev;
862 dev = dev_get_by_index_rcu(net, ifindex);
867 EXPORT_SYMBOL(dev_get_by_index);
870 * netdev_get_by_index() - find a device by its ifindex
871 * @net: the applicable net namespace
872 * @ifindex: index of device
873 * @tracker: tracking object for the acquired reference
874 * @gfp: allocation flags for the tracker
876 * Search for an interface by index. Returns NULL if the device
877 * is not found or a pointer to the device. The device returned has
878 * had a reference added and the pointer is safe until the user calls
879 * netdev_put() to indicate they have finished with it.
881 struct net_device *netdev_get_by_index(struct net *net, int ifindex,
882 netdevice_tracker *tracker, gfp_t gfp)
884 struct net_device *dev;
886 dev = dev_get_by_index(net, ifindex);
888 netdev_tracker_alloc(dev, tracker, gfp);
891 EXPORT_SYMBOL(netdev_get_by_index);
894 * dev_get_by_napi_id - find a device by napi_id
895 * @napi_id: ID of the NAPI struct
897 * Search for an interface by NAPI ID. Returns %NULL if the device
898 * is not found or a pointer to the device. The device has not had
899 * its reference counter increased so the caller must be careful
900 * about locking. The caller must hold RCU lock.
903 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
905 struct napi_struct *napi;
907 WARN_ON_ONCE(!rcu_read_lock_held());
909 if (napi_id < MIN_NAPI_ID)
912 napi = napi_by_id(napi_id);
914 return napi ? napi->dev : NULL;
916 EXPORT_SYMBOL(dev_get_by_napi_id);
919 * netdev_get_name - get a netdevice name, knowing its ifindex.
920 * @net: network namespace
921 * @name: a pointer to the buffer where the name will be stored.
922 * @ifindex: the ifindex of the interface to get the name from.
924 int netdev_get_name(struct net *net, char *name, int ifindex)
926 struct net_device *dev;
929 down_read(&devnet_rename_sem);
932 dev = dev_get_by_index_rcu(net, ifindex);
938 strcpy(name, dev->name);
943 up_read(&devnet_rename_sem);
948 * dev_getbyhwaddr_rcu - find a device by its hardware address
949 * @net: the applicable net namespace
950 * @type: media type of device
951 * @ha: hardware address
953 * Search for an interface by MAC address. Returns NULL if the device
954 * is not found or a pointer to the device.
955 * The caller must hold RCU or RTNL.
956 * The returned device has not had its ref count increased
957 * and the caller must therefore be careful about locking
961 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
964 struct net_device *dev;
966 for_each_netdev_rcu(net, dev)
967 if (dev->type == type &&
968 !memcmp(dev->dev_addr, ha, dev->addr_len))
973 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
975 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
977 struct net_device *dev, *ret = NULL;
980 for_each_netdev_rcu(net, dev)
981 if (dev->type == type) {
989 EXPORT_SYMBOL(dev_getfirstbyhwtype);
992 * __dev_get_by_flags - find any device with given flags
993 * @net: the applicable net namespace
994 * @if_flags: IFF_* values
995 * @mask: bitmask of bits in if_flags to check
997 * Search for any interface with the given flags. Returns NULL if a device
998 * is not found or a pointer to the device. Must be called inside
999 * rtnl_lock(), and result refcount is unchanged.
1002 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1003 unsigned short mask)
1005 struct net_device *dev, *ret;
1010 for_each_netdev(net, dev) {
1011 if (((dev->flags ^ if_flags) & mask) == 0) {
1018 EXPORT_SYMBOL(__dev_get_by_flags);
1021 * dev_valid_name - check if name is okay for network device
1022 * @name: name string
1024 * Network device names need to be valid file names to
1025 * allow sysfs to work. We also disallow any kind of
1028 bool dev_valid_name(const char *name)
1032 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1034 if (!strcmp(name, ".") || !strcmp(name, ".."))
1038 if (*name == '/' || *name == ':' || isspace(*name))
1044 EXPORT_SYMBOL(dev_valid_name);
1047 * __dev_alloc_name - allocate a name for a device
1048 * @net: network namespace to allocate the device name in
1049 * @name: name format string
1050 * @buf: scratch buffer and result name string
1052 * Passed a format string - eg "lt%d" it will try and find a suitable
1053 * id. It scans list of devices to build up a free map, then chooses
1054 * the first empty slot. The caller must hold the dev_base or rtnl lock
1055 * while allocating the name and adding the device in order to avoid
1057 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1058 * Returns the number of the unit assigned or a negative errno code.
1061 static int __dev_alloc_name(struct net *net, const char *name, char *buf)
1065 const int max_netdevices = 8*PAGE_SIZE;
1066 unsigned long *inuse;
1067 struct net_device *d;
1069 if (!dev_valid_name(name))
1072 p = strchr(name, '%');
1075 * Verify the string as this thing may have come from
1076 * the user. There must be either one "%d" and no other "%"
1079 if (p[1] != 'd' || strchr(p + 2, '%'))
1082 /* Use one page as a bit array of possible slots */
1083 inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
1087 for_each_netdev(net, d) {
1088 struct netdev_name_node *name_node;
1089 list_for_each_entry(name_node, &d->name_node->list, list) {
1090 if (!sscanf(name_node->name, name, &i))
1092 if (i < 0 || i >= max_netdevices)
1095 /* avoid cases where sscanf is not exact inverse of printf */
1096 snprintf(buf, IFNAMSIZ, name, i);
1097 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1098 __set_bit(i, inuse);
1100 if (!sscanf(d->name, name, &i))
1102 if (i < 0 || i >= max_netdevices)
1105 /* avoid cases where sscanf is not exact inverse of printf */
1106 snprintf(buf, IFNAMSIZ, name, i);
1107 if (!strncmp(buf, d->name, IFNAMSIZ))
1108 __set_bit(i, inuse);
1111 i = find_first_zero_bit(inuse, max_netdevices);
1115 snprintf(buf, IFNAMSIZ, name, i);
1116 if (!netdev_name_in_use(net, buf))
1119 /* It is possible to run out of possible slots
1120 * when the name is long and there isn't enough space left
1121 * for the digits, or if all bits are used.
1126 static int dev_alloc_name_ns(struct net *net,
1127 struct net_device *dev,
1134 ret = __dev_alloc_name(net, name, buf);
1136 strscpy(dev->name, buf, IFNAMSIZ);
1141 * dev_alloc_name - allocate a name for a device
1143 * @name: name format string
1145 * Passed a format string - eg "lt%d" it will try and find a suitable
1146 * id. It scans list of devices to build up a free map, then chooses
1147 * the first empty slot. The caller must hold the dev_base or rtnl lock
1148 * while allocating the name and adding the device in order to avoid
1150 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1151 * Returns the number of the unit assigned or a negative errno code.
1154 int dev_alloc_name(struct net_device *dev, const char *name)
1156 return dev_alloc_name_ns(dev_net(dev), dev, name);
1158 EXPORT_SYMBOL(dev_alloc_name);
1160 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1165 if (!dev_valid_name(name))
1168 if (strchr(name, '%'))
1169 return dev_alloc_name_ns(net, dev, name);
1170 else if (netdev_name_in_use(net, name))
1172 else if (dev->name != name)
1173 strscpy(dev->name, name, IFNAMSIZ);
1179 * dev_change_name - change name of a device
1181 * @newname: name (or format string) must be at least IFNAMSIZ
1183 * Change name of a device, can pass format strings "eth%d".
1186 int dev_change_name(struct net_device *dev, const char *newname)
1188 unsigned char old_assign_type;
1189 char oldname[IFNAMSIZ];
1195 BUG_ON(!dev_net(dev));
1199 down_write(&devnet_rename_sem);
1201 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1202 up_write(&devnet_rename_sem);
1206 memcpy(oldname, dev->name, IFNAMSIZ);
1208 err = dev_get_valid_name(net, dev, newname);
1210 up_write(&devnet_rename_sem);
1214 if (oldname[0] && !strchr(oldname, '%'))
1215 netdev_info(dev, "renamed from %s%s\n", oldname,
1216 dev->flags & IFF_UP ? " (while UP)" : "");
1218 old_assign_type = dev->name_assign_type;
1219 dev->name_assign_type = NET_NAME_RENAMED;
1222 ret = device_rename(&dev->dev, dev->name);
1224 memcpy(dev->name, oldname, IFNAMSIZ);
1225 dev->name_assign_type = old_assign_type;
1226 up_write(&devnet_rename_sem);
1230 up_write(&devnet_rename_sem);
1232 netdev_adjacent_rename_links(dev, oldname);
1234 write_lock(&dev_base_lock);
1235 netdev_name_node_del(dev->name_node);
1236 write_unlock(&dev_base_lock);
1240 write_lock(&dev_base_lock);
1241 netdev_name_node_add(net, dev->name_node);
1242 write_unlock(&dev_base_lock);
1244 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1245 ret = notifier_to_errno(ret);
1248 /* err >= 0 after dev_alloc_name() or stores the first errno */
1251 down_write(&devnet_rename_sem);
1252 memcpy(dev->name, oldname, IFNAMSIZ);
1253 memcpy(oldname, newname, IFNAMSIZ);
1254 dev->name_assign_type = old_assign_type;
1255 old_assign_type = NET_NAME_RENAMED;
1258 netdev_err(dev, "name change rollback failed: %d\n",
1267 * dev_set_alias - change ifalias of a device
1269 * @alias: name up to IFALIASZ
1270 * @len: limit of bytes to copy from info
1272 * Set ifalias for a device,
1274 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1276 struct dev_ifalias *new_alias = NULL;
1278 if (len >= IFALIASZ)
1282 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1286 memcpy(new_alias->ifalias, alias, len);
1287 new_alias->ifalias[len] = 0;
1290 mutex_lock(&ifalias_mutex);
1291 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1292 mutex_is_locked(&ifalias_mutex));
1293 mutex_unlock(&ifalias_mutex);
1296 kfree_rcu(new_alias, rcuhead);
1300 EXPORT_SYMBOL(dev_set_alias);
1303 * dev_get_alias - get ifalias of a device
1305 * @name: buffer to store name of ifalias
1306 * @len: size of buffer
1308 * get ifalias for a device. Caller must make sure dev cannot go
1309 * away, e.g. rcu read lock or own a reference count to device.
1311 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1313 const struct dev_ifalias *alias;
1317 alias = rcu_dereference(dev->ifalias);
1319 ret = snprintf(name, len, "%s", alias->ifalias);
1326 * netdev_features_change - device changes features
1327 * @dev: device to cause notification
1329 * Called to indicate a device has changed features.
1331 void netdev_features_change(struct net_device *dev)
1333 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1335 EXPORT_SYMBOL(netdev_features_change);
1338 * netdev_state_change - device changes state
1339 * @dev: device to cause notification
1341 * Called to indicate a device has changed state. This function calls
1342 * the notifier chains for netdev_chain and sends a NEWLINK message
1343 * to the routing socket.
1345 void netdev_state_change(struct net_device *dev)
1347 if (dev->flags & IFF_UP) {
1348 struct netdev_notifier_change_info change_info = {
1352 call_netdevice_notifiers_info(NETDEV_CHANGE,
1354 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1357 EXPORT_SYMBOL(netdev_state_change);
1360 * __netdev_notify_peers - notify network peers about existence of @dev,
1361 * to be called when rtnl lock is already held.
1362 * @dev: network device
1364 * Generate traffic such that interested network peers are aware of
1365 * @dev, such as by generating a gratuitous ARP. This may be used when
1366 * a device wants to inform the rest of the network about some sort of
1367 * reconfiguration such as a failover event or virtual machine
1370 void __netdev_notify_peers(struct net_device *dev)
1373 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1374 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1376 EXPORT_SYMBOL(__netdev_notify_peers);
1379 * netdev_notify_peers - notify network peers about existence of @dev
1380 * @dev: network device
1382 * Generate traffic such that interested network peers are aware of
1383 * @dev, such as by generating a gratuitous ARP. This may be used when
1384 * a device wants to inform the rest of the network about some sort of
1385 * reconfiguration such as a failover event or virtual machine
1388 void netdev_notify_peers(struct net_device *dev)
1391 __netdev_notify_peers(dev);
1394 EXPORT_SYMBOL(netdev_notify_peers);
1396 static int napi_threaded_poll(void *data);
1398 static int napi_kthread_create(struct napi_struct *n)
1402 /* Create and wake up the kthread once to put it in
1403 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1404 * warning and work with loadavg.
1406 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1407 n->dev->name, n->napi_id);
1408 if (IS_ERR(n->thread)) {
1409 err = PTR_ERR(n->thread);
1410 pr_err("kthread_run failed with err %d\n", err);
1417 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1419 const struct net_device_ops *ops = dev->netdev_ops;
1423 dev_addr_check(dev);
1425 if (!netif_device_present(dev)) {
1426 /* may be detached because parent is runtime-suspended */
1427 if (dev->dev.parent)
1428 pm_runtime_resume(dev->dev.parent);
1429 if (!netif_device_present(dev))
1433 /* Block netpoll from trying to do any rx path servicing.
1434 * If we don't do this there is a chance ndo_poll_controller
1435 * or ndo_poll may be running while we open the device
1437 netpoll_poll_disable(dev);
1439 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1440 ret = notifier_to_errno(ret);
1444 set_bit(__LINK_STATE_START, &dev->state);
1446 if (ops->ndo_validate_addr)
1447 ret = ops->ndo_validate_addr(dev);
1449 if (!ret && ops->ndo_open)
1450 ret = ops->ndo_open(dev);
1452 netpoll_poll_enable(dev);
1455 clear_bit(__LINK_STATE_START, &dev->state);
1457 dev->flags |= IFF_UP;
1458 dev_set_rx_mode(dev);
1460 add_device_randomness(dev->dev_addr, dev->addr_len);
1467 * dev_open - prepare an interface for use.
1468 * @dev: device to open
1469 * @extack: netlink extended ack
1471 * Takes a device from down to up state. The device's private open
1472 * function is invoked and then the multicast lists are loaded. Finally
1473 * the device is moved into the up state and a %NETDEV_UP message is
1474 * sent to the netdev notifier chain.
1476 * Calling this function on an active interface is a nop. On a failure
1477 * a negative errno code is returned.
1479 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1483 if (dev->flags & IFF_UP)
1486 ret = __dev_open(dev, extack);
1490 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1491 call_netdevice_notifiers(NETDEV_UP, dev);
1495 EXPORT_SYMBOL(dev_open);
1497 static void __dev_close_many(struct list_head *head)
1499 struct net_device *dev;
1504 list_for_each_entry(dev, head, close_list) {
1505 /* Temporarily disable netpoll until the interface is down */
1506 netpoll_poll_disable(dev);
1508 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1510 clear_bit(__LINK_STATE_START, &dev->state);
1512 /* Synchronize to scheduled poll. We cannot touch poll list, it
1513 * can be even on different cpu. So just clear netif_running().
1515 * dev->stop() will invoke napi_disable() on all of it's
1516 * napi_struct instances on this device.
1518 smp_mb__after_atomic(); /* Commit netif_running(). */
1521 dev_deactivate_many(head);
1523 list_for_each_entry(dev, head, close_list) {
1524 const struct net_device_ops *ops = dev->netdev_ops;
1527 * Call the device specific close. This cannot fail.
1528 * Only if device is UP
1530 * We allow it to be called even after a DETACH hot-plug
1536 dev->flags &= ~IFF_UP;
1537 netpoll_poll_enable(dev);
1541 static void __dev_close(struct net_device *dev)
1545 list_add(&dev->close_list, &single);
1546 __dev_close_many(&single);
1550 void dev_close_many(struct list_head *head, bool unlink)
1552 struct net_device *dev, *tmp;
1554 /* Remove the devices that don't need to be closed */
1555 list_for_each_entry_safe(dev, tmp, head, close_list)
1556 if (!(dev->flags & IFF_UP))
1557 list_del_init(&dev->close_list);
1559 __dev_close_many(head);
1561 list_for_each_entry_safe(dev, tmp, head, close_list) {
1562 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1563 call_netdevice_notifiers(NETDEV_DOWN, dev);
1565 list_del_init(&dev->close_list);
1568 EXPORT_SYMBOL(dev_close_many);
1571 * dev_close - shutdown an interface.
1572 * @dev: device to shutdown
1574 * This function moves an active device into down state. A
1575 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1576 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1579 void dev_close(struct net_device *dev)
1581 if (dev->flags & IFF_UP) {
1584 list_add(&dev->close_list, &single);
1585 dev_close_many(&single, true);
1589 EXPORT_SYMBOL(dev_close);
1593 * dev_disable_lro - disable Large Receive Offload on a device
1596 * Disable Large Receive Offload (LRO) on a net device. Must be
1597 * called under RTNL. This is needed if received packets may be
1598 * forwarded to another interface.
1600 void dev_disable_lro(struct net_device *dev)
1602 struct net_device *lower_dev;
1603 struct list_head *iter;
1605 dev->wanted_features &= ~NETIF_F_LRO;
1606 netdev_update_features(dev);
1608 if (unlikely(dev->features & NETIF_F_LRO))
1609 netdev_WARN(dev, "failed to disable LRO!\n");
1611 netdev_for_each_lower_dev(dev, lower_dev, iter)
1612 dev_disable_lro(lower_dev);
1614 EXPORT_SYMBOL(dev_disable_lro);
1617 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1620 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1621 * called under RTNL. This is needed if Generic XDP is installed on
1624 static void dev_disable_gro_hw(struct net_device *dev)
1626 dev->wanted_features &= ~NETIF_F_GRO_HW;
1627 netdev_update_features(dev);
1629 if (unlikely(dev->features & NETIF_F_GRO_HW))
1630 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1633 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1636 case NETDEV_##val: \
1637 return "NETDEV_" __stringify(val);
1639 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1640 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1641 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1642 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1643 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1644 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1645 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1646 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1647 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1648 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1649 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1653 return "UNKNOWN_NETDEV_EVENT";
1655 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1657 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1658 struct net_device *dev)
1660 struct netdev_notifier_info info = {
1664 return nb->notifier_call(nb, val, &info);
1667 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1668 struct net_device *dev)
1672 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1673 err = notifier_to_errno(err);
1677 if (!(dev->flags & IFF_UP))
1680 call_netdevice_notifier(nb, NETDEV_UP, dev);
1684 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1685 struct net_device *dev)
1687 if (dev->flags & IFF_UP) {
1688 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1690 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1692 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1695 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1698 struct net_device *dev;
1701 for_each_netdev(net, dev) {
1702 err = call_netdevice_register_notifiers(nb, dev);
1709 for_each_netdev_continue_reverse(net, dev)
1710 call_netdevice_unregister_notifiers(nb, dev);
1714 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1717 struct net_device *dev;
1719 for_each_netdev(net, dev)
1720 call_netdevice_unregister_notifiers(nb, dev);
1723 static int dev_boot_phase = 1;
1726 * register_netdevice_notifier - register a network notifier block
1729 * Register a notifier to be called when network device events occur.
1730 * The notifier passed is linked into the kernel structures and must
1731 * not be reused until it has been unregistered. A negative errno code
1732 * is returned on a failure.
1734 * When registered all registration and up events are replayed
1735 * to the new notifier to allow device to have a race free
1736 * view of the network device list.
1739 int register_netdevice_notifier(struct notifier_block *nb)
1744 /* Close race with setup_net() and cleanup_net() */
1745 down_write(&pernet_ops_rwsem);
1747 err = raw_notifier_chain_register(&netdev_chain, nb);
1753 err = call_netdevice_register_net_notifiers(nb, net);
1760 up_write(&pernet_ops_rwsem);
1764 for_each_net_continue_reverse(net)
1765 call_netdevice_unregister_net_notifiers(nb, net);
1767 raw_notifier_chain_unregister(&netdev_chain, nb);
1770 EXPORT_SYMBOL(register_netdevice_notifier);
1773 * unregister_netdevice_notifier - unregister a network notifier block
1776 * Unregister a notifier previously registered by
1777 * register_netdevice_notifier(). The notifier is unlinked into the
1778 * kernel structures and may then be reused. A negative errno code
1779 * is returned on a failure.
1781 * After unregistering unregister and down device events are synthesized
1782 * for all devices on the device list to the removed notifier to remove
1783 * the need for special case cleanup code.
1786 int unregister_netdevice_notifier(struct notifier_block *nb)
1791 /* Close race with setup_net() and cleanup_net() */
1792 down_write(&pernet_ops_rwsem);
1794 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1799 call_netdevice_unregister_net_notifiers(nb, net);
1803 up_write(&pernet_ops_rwsem);
1806 EXPORT_SYMBOL(unregister_netdevice_notifier);
1808 static int __register_netdevice_notifier_net(struct net *net,
1809 struct notifier_block *nb,
1810 bool ignore_call_fail)
1814 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1820 err = call_netdevice_register_net_notifiers(nb, net);
1821 if (err && !ignore_call_fail)
1822 goto chain_unregister;
1827 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1831 static int __unregister_netdevice_notifier_net(struct net *net,
1832 struct notifier_block *nb)
1836 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1840 call_netdevice_unregister_net_notifiers(nb, net);
1845 * register_netdevice_notifier_net - register a per-netns network notifier block
1846 * @net: network namespace
1849 * Register a notifier to be called when network device events occur.
1850 * The notifier passed is linked into the kernel structures and must
1851 * not be reused until it has been unregistered. A negative errno code
1852 * is returned on a failure.
1854 * When registered all registration and up events are replayed
1855 * to the new notifier to allow device to have a race free
1856 * view of the network device list.
1859 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1864 err = __register_netdevice_notifier_net(net, nb, false);
1868 EXPORT_SYMBOL(register_netdevice_notifier_net);
1871 * unregister_netdevice_notifier_net - unregister a per-netns
1872 * network notifier block
1873 * @net: network namespace
1876 * Unregister a notifier previously registered by
1877 * register_netdevice_notifier_net(). The notifier is unlinked from the
1878 * kernel structures and may then be reused. A negative errno code
1879 * is returned on a failure.
1881 * After unregistering unregister and down device events are synthesized
1882 * for all devices on the device list to the removed notifier to remove
1883 * the need for special case cleanup code.
1886 int unregister_netdevice_notifier_net(struct net *net,
1887 struct notifier_block *nb)
1892 err = __unregister_netdevice_notifier_net(net, nb);
1896 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1898 static void __move_netdevice_notifier_net(struct net *src_net,
1899 struct net *dst_net,
1900 struct notifier_block *nb)
1902 __unregister_netdevice_notifier_net(src_net, nb);
1903 __register_netdevice_notifier_net(dst_net, nb, true);
1906 int register_netdevice_notifier_dev_net(struct net_device *dev,
1907 struct notifier_block *nb,
1908 struct netdev_net_notifier *nn)
1913 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1916 list_add(&nn->list, &dev->net_notifier_list);
1921 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1923 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1924 struct notifier_block *nb,
1925 struct netdev_net_notifier *nn)
1930 list_del(&nn->list);
1931 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1935 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1937 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1940 struct netdev_net_notifier *nn;
1942 list_for_each_entry(nn, &dev->net_notifier_list, list)
1943 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
1947 * call_netdevice_notifiers_info - call all network notifier blocks
1948 * @val: value passed unmodified to notifier function
1949 * @info: notifier information data
1951 * Call all network notifier blocks. Parameters and return value
1952 * are as for raw_notifier_call_chain().
1955 int call_netdevice_notifiers_info(unsigned long val,
1956 struct netdev_notifier_info *info)
1958 struct net *net = dev_net(info->dev);
1963 /* Run per-netns notifier block chain first, then run the global one.
1964 * Hopefully, one day, the global one is going to be removed after
1965 * all notifier block registrators get converted to be per-netns.
1967 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1968 if (ret & NOTIFY_STOP_MASK)
1970 return raw_notifier_call_chain(&netdev_chain, val, info);
1974 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
1975 * for and rollback on error
1976 * @val_up: value passed unmodified to notifier function
1977 * @val_down: value passed unmodified to the notifier function when
1978 * recovering from an error on @val_up
1979 * @info: notifier information data
1981 * Call all per-netns network notifier blocks, but not notifier blocks on
1982 * the global notifier chain. Parameters and return value are as for
1983 * raw_notifier_call_chain_robust().
1987 call_netdevice_notifiers_info_robust(unsigned long val_up,
1988 unsigned long val_down,
1989 struct netdev_notifier_info *info)
1991 struct net *net = dev_net(info->dev);
1995 return raw_notifier_call_chain_robust(&net->netdev_chain,
1996 val_up, val_down, info);
1999 static int call_netdevice_notifiers_extack(unsigned long val,
2000 struct net_device *dev,
2001 struct netlink_ext_ack *extack)
2003 struct netdev_notifier_info info = {
2008 return call_netdevice_notifiers_info(val, &info);
2012 * call_netdevice_notifiers - call all network notifier blocks
2013 * @val: value passed unmodified to notifier function
2014 * @dev: net_device pointer passed unmodified to notifier function
2016 * Call all network notifier blocks. Parameters and return value
2017 * are as for raw_notifier_call_chain().
2020 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2022 return call_netdevice_notifiers_extack(val, dev, NULL);
2024 EXPORT_SYMBOL(call_netdevice_notifiers);
2027 * call_netdevice_notifiers_mtu - call all network notifier blocks
2028 * @val: value passed unmodified to notifier function
2029 * @dev: net_device pointer passed unmodified to notifier function
2030 * @arg: additional u32 argument passed to the notifier function
2032 * Call all network notifier blocks. Parameters and return value
2033 * are as for raw_notifier_call_chain().
2035 static int call_netdevice_notifiers_mtu(unsigned long val,
2036 struct net_device *dev, u32 arg)
2038 struct netdev_notifier_info_ext info = {
2043 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2045 return call_netdevice_notifiers_info(val, &info.info);
2048 #ifdef CONFIG_NET_INGRESS
2049 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2051 void net_inc_ingress_queue(void)
2053 static_branch_inc(&ingress_needed_key);
2055 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2057 void net_dec_ingress_queue(void)
2059 static_branch_dec(&ingress_needed_key);
2061 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2064 #ifdef CONFIG_NET_EGRESS
2065 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2067 void net_inc_egress_queue(void)
2069 static_branch_inc(&egress_needed_key);
2071 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2073 void net_dec_egress_queue(void)
2075 static_branch_dec(&egress_needed_key);
2077 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2080 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2081 EXPORT_SYMBOL(netstamp_needed_key);
2082 #ifdef CONFIG_JUMP_LABEL
2083 static atomic_t netstamp_needed_deferred;
2084 static atomic_t netstamp_wanted;
2085 static void netstamp_clear(struct work_struct *work)
2087 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2090 wanted = atomic_add_return(deferred, &netstamp_wanted);
2092 static_branch_enable(&netstamp_needed_key);
2094 static_branch_disable(&netstamp_needed_key);
2096 static DECLARE_WORK(netstamp_work, netstamp_clear);
2099 void net_enable_timestamp(void)
2101 #ifdef CONFIG_JUMP_LABEL
2102 int wanted = atomic_read(&netstamp_wanted);
2104 while (wanted > 0) {
2105 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2108 atomic_inc(&netstamp_needed_deferred);
2109 schedule_work(&netstamp_work);
2111 static_branch_inc(&netstamp_needed_key);
2114 EXPORT_SYMBOL(net_enable_timestamp);
2116 void net_disable_timestamp(void)
2118 #ifdef CONFIG_JUMP_LABEL
2119 int wanted = atomic_read(&netstamp_wanted);
2121 while (wanted > 1) {
2122 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2125 atomic_dec(&netstamp_needed_deferred);
2126 schedule_work(&netstamp_work);
2128 static_branch_dec(&netstamp_needed_key);
2131 EXPORT_SYMBOL(net_disable_timestamp);
2133 static inline void net_timestamp_set(struct sk_buff *skb)
2136 skb->mono_delivery_time = 0;
2137 if (static_branch_unlikely(&netstamp_needed_key))
2138 skb->tstamp = ktime_get_real();
2141 #define net_timestamp_check(COND, SKB) \
2142 if (static_branch_unlikely(&netstamp_needed_key)) { \
2143 if ((COND) && !(SKB)->tstamp) \
2144 (SKB)->tstamp = ktime_get_real(); \
2147 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2149 return __is_skb_forwardable(dev, skb, true);
2151 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2153 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2156 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2159 skb->protocol = eth_type_trans(skb, dev);
2160 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2166 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2168 return __dev_forward_skb2(dev, skb, true);
2170 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2173 * dev_forward_skb - loopback an skb to another netif
2175 * @dev: destination network device
2176 * @skb: buffer to forward
2179 * NET_RX_SUCCESS (no congestion)
2180 * NET_RX_DROP (packet was dropped, but freed)
2182 * dev_forward_skb can be used for injecting an skb from the
2183 * start_xmit function of one device into the receive queue
2184 * of another device.
2186 * The receiving device may be in another namespace, so
2187 * we have to clear all information in the skb that could
2188 * impact namespace isolation.
2190 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2192 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2194 EXPORT_SYMBOL_GPL(dev_forward_skb);
2196 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2198 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2201 static inline int deliver_skb(struct sk_buff *skb,
2202 struct packet_type *pt_prev,
2203 struct net_device *orig_dev)
2205 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2207 refcount_inc(&skb->users);
2208 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2211 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2212 struct packet_type **pt,
2213 struct net_device *orig_dev,
2215 struct list_head *ptype_list)
2217 struct packet_type *ptype, *pt_prev = *pt;
2219 list_for_each_entry_rcu(ptype, ptype_list, list) {
2220 if (ptype->type != type)
2223 deliver_skb(skb, pt_prev, orig_dev);
2229 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2231 if (!ptype->af_packet_priv || !skb->sk)
2234 if (ptype->id_match)
2235 return ptype->id_match(ptype, skb->sk);
2236 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2243 * dev_nit_active - return true if any network interface taps are in use
2245 * @dev: network device to check for the presence of taps
2247 bool dev_nit_active(struct net_device *dev)
2249 return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
2251 EXPORT_SYMBOL_GPL(dev_nit_active);
2254 * Support routine. Sends outgoing frames to any network
2255 * taps currently in use.
2258 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2260 struct packet_type *ptype;
2261 struct sk_buff *skb2 = NULL;
2262 struct packet_type *pt_prev = NULL;
2263 struct list_head *ptype_list = &ptype_all;
2267 list_for_each_entry_rcu(ptype, ptype_list, list) {
2268 if (ptype->ignore_outgoing)
2271 /* Never send packets back to the socket
2272 * they originated from - MvS (miquels@drinkel.ow.org)
2274 if (skb_loop_sk(ptype, skb))
2278 deliver_skb(skb2, pt_prev, skb->dev);
2283 /* need to clone skb, done only once */
2284 skb2 = skb_clone(skb, GFP_ATOMIC);
2288 net_timestamp_set(skb2);
2290 /* skb->nh should be correctly
2291 * set by sender, so that the second statement is
2292 * just protection against buggy protocols.
2294 skb_reset_mac_header(skb2);
2296 if (skb_network_header(skb2) < skb2->data ||
2297 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2298 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2299 ntohs(skb2->protocol),
2301 skb_reset_network_header(skb2);
2304 skb2->transport_header = skb2->network_header;
2305 skb2->pkt_type = PACKET_OUTGOING;
2309 if (ptype_list == &ptype_all) {
2310 ptype_list = &dev->ptype_all;
2315 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2316 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2322 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2325 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2326 * @dev: Network device
2327 * @txq: number of queues available
2329 * If real_num_tx_queues is changed the tc mappings may no longer be
2330 * valid. To resolve this verify the tc mapping remains valid and if
2331 * not NULL the mapping. With no priorities mapping to this
2332 * offset/count pair it will no longer be used. In the worst case TC0
2333 * is invalid nothing can be done so disable priority mappings. If is
2334 * expected that drivers will fix this mapping if they can before
2335 * calling netif_set_real_num_tx_queues.
2337 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2340 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2342 /* If TC0 is invalidated disable TC mapping */
2343 if (tc->offset + tc->count > txq) {
2344 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2349 /* Invalidated prio to tc mappings set to TC0 */
2350 for (i = 1; i < TC_BITMASK + 1; i++) {
2351 int q = netdev_get_prio_tc_map(dev, i);
2353 tc = &dev->tc_to_txq[q];
2354 if (tc->offset + tc->count > txq) {
2355 netdev_warn(dev, "Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
2357 netdev_set_prio_tc_map(dev, i, 0);
2362 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2365 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2368 /* walk through the TCs and see if it falls into any of them */
2369 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2370 if ((txq - tc->offset) < tc->count)
2374 /* didn't find it, just return -1 to indicate no match */
2380 EXPORT_SYMBOL(netdev_txq_to_tc);
2383 static struct static_key xps_needed __read_mostly;
2384 static struct static_key xps_rxqs_needed __read_mostly;
2385 static DEFINE_MUTEX(xps_map_mutex);
2386 #define xmap_dereference(P) \
2387 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2389 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2390 struct xps_dev_maps *old_maps, int tci, u16 index)
2392 struct xps_map *map = NULL;
2395 map = xmap_dereference(dev_maps->attr_map[tci]);
2399 for (pos = map->len; pos--;) {
2400 if (map->queues[pos] != index)
2404 map->queues[pos] = map->queues[--map->len];
2409 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2410 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2411 kfree_rcu(map, rcu);
2418 static bool remove_xps_queue_cpu(struct net_device *dev,
2419 struct xps_dev_maps *dev_maps,
2420 int cpu, u16 offset, u16 count)
2422 int num_tc = dev_maps->num_tc;
2423 bool active = false;
2426 for (tci = cpu * num_tc; num_tc--; tci++) {
2429 for (i = count, j = offset; i--; j++) {
2430 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2440 static void reset_xps_maps(struct net_device *dev,
2441 struct xps_dev_maps *dev_maps,
2442 enum xps_map_type type)
2444 static_key_slow_dec_cpuslocked(&xps_needed);
2445 if (type == XPS_RXQS)
2446 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2448 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2450 kfree_rcu(dev_maps, rcu);
2453 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2454 u16 offset, u16 count)
2456 struct xps_dev_maps *dev_maps;
2457 bool active = false;
2460 dev_maps = xmap_dereference(dev->xps_maps[type]);
2464 for (j = 0; j < dev_maps->nr_ids; j++)
2465 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2467 reset_xps_maps(dev, dev_maps, type);
2469 if (type == XPS_CPUS) {
2470 for (i = offset + (count - 1); count--; i--)
2471 netdev_queue_numa_node_write(
2472 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2476 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2479 if (!static_key_false(&xps_needed))
2483 mutex_lock(&xps_map_mutex);
2485 if (static_key_false(&xps_rxqs_needed))
2486 clean_xps_maps(dev, XPS_RXQS, offset, count);
2488 clean_xps_maps(dev, XPS_CPUS, offset, count);
2490 mutex_unlock(&xps_map_mutex);
2494 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2496 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2499 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2500 u16 index, bool is_rxqs_map)
2502 struct xps_map *new_map;
2503 int alloc_len = XPS_MIN_MAP_ALLOC;
2506 for (pos = 0; map && pos < map->len; pos++) {
2507 if (map->queues[pos] != index)
2512 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2514 if (pos < map->alloc_len)
2517 alloc_len = map->alloc_len * 2;
2520 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2524 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2526 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2527 cpu_to_node(attr_index));
2531 for (i = 0; i < pos; i++)
2532 new_map->queues[i] = map->queues[i];
2533 new_map->alloc_len = alloc_len;
2539 /* Copy xps maps at a given index */
2540 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2541 struct xps_dev_maps *new_dev_maps, int index,
2542 int tc, bool skip_tc)
2544 int i, tci = index * dev_maps->num_tc;
2545 struct xps_map *map;
2547 /* copy maps belonging to foreign traffic classes */
2548 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2549 if (i == tc && skip_tc)
2552 /* fill in the new device map from the old device map */
2553 map = xmap_dereference(dev_maps->attr_map[tci]);
2554 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2558 /* Must be called under cpus_read_lock */
2559 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2560 u16 index, enum xps_map_type type)
2562 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2563 const unsigned long *online_mask = NULL;
2564 bool active = false, copy = false;
2565 int i, j, tci, numa_node_id = -2;
2566 int maps_sz, num_tc = 1, tc = 0;
2567 struct xps_map *map, *new_map;
2568 unsigned int nr_ids;
2570 WARN_ON_ONCE(index >= dev->num_tx_queues);
2573 /* Do not allow XPS on subordinate device directly */
2574 num_tc = dev->num_tc;
2578 /* If queue belongs to subordinate dev use its map */
2579 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2581 tc = netdev_txq_to_tc(dev, index);
2586 mutex_lock(&xps_map_mutex);
2588 dev_maps = xmap_dereference(dev->xps_maps[type]);
2589 if (type == XPS_RXQS) {
2590 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2591 nr_ids = dev->num_rx_queues;
2593 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2594 if (num_possible_cpus() > 1)
2595 online_mask = cpumask_bits(cpu_online_mask);
2596 nr_ids = nr_cpu_ids;
2599 if (maps_sz < L1_CACHE_BYTES)
2600 maps_sz = L1_CACHE_BYTES;
2602 /* The old dev_maps could be larger or smaller than the one we're
2603 * setting up now, as dev->num_tc or nr_ids could have been updated in
2604 * between. We could try to be smart, but let's be safe instead and only
2605 * copy foreign traffic classes if the two map sizes match.
2608 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2611 /* allocate memory for queue storage */
2612 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2614 if (!new_dev_maps) {
2615 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2616 if (!new_dev_maps) {
2617 mutex_unlock(&xps_map_mutex);
2621 new_dev_maps->nr_ids = nr_ids;
2622 new_dev_maps->num_tc = num_tc;
2625 tci = j * num_tc + tc;
2626 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2628 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2632 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2636 goto out_no_new_maps;
2639 /* Increment static keys at most once per type */
2640 static_key_slow_inc_cpuslocked(&xps_needed);
2641 if (type == XPS_RXQS)
2642 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2645 for (j = 0; j < nr_ids; j++) {
2646 bool skip_tc = false;
2648 tci = j * num_tc + tc;
2649 if (netif_attr_test_mask(j, mask, nr_ids) &&
2650 netif_attr_test_online(j, online_mask, nr_ids)) {
2651 /* add tx-queue to CPU/rx-queue maps */
2656 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2657 while ((pos < map->len) && (map->queues[pos] != index))
2660 if (pos == map->len)
2661 map->queues[map->len++] = index;
2663 if (type == XPS_CPUS) {
2664 if (numa_node_id == -2)
2665 numa_node_id = cpu_to_node(j);
2666 else if (numa_node_id != cpu_to_node(j))
2673 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2677 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2679 /* Cleanup old maps */
2681 goto out_no_old_maps;
2683 for (j = 0; j < dev_maps->nr_ids; j++) {
2684 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2685 map = xmap_dereference(dev_maps->attr_map[tci]);
2690 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2695 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2696 kfree_rcu(map, rcu);
2700 old_dev_maps = dev_maps;
2703 dev_maps = new_dev_maps;
2707 if (type == XPS_CPUS)
2708 /* update Tx queue numa node */
2709 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2710 (numa_node_id >= 0) ?
2711 numa_node_id : NUMA_NO_NODE);
2716 /* removes tx-queue from unused CPUs/rx-queues */
2717 for (j = 0; j < dev_maps->nr_ids; j++) {
2718 tci = j * dev_maps->num_tc;
2720 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2722 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2723 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2726 active |= remove_xps_queue(dev_maps,
2727 copy ? old_dev_maps : NULL,
2733 kfree_rcu(old_dev_maps, rcu);
2735 /* free map if not active */
2737 reset_xps_maps(dev, dev_maps, type);
2740 mutex_unlock(&xps_map_mutex);
2744 /* remove any maps that we added */
2745 for (j = 0; j < nr_ids; j++) {
2746 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2747 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2749 xmap_dereference(dev_maps->attr_map[tci]) :
2751 if (new_map && new_map != map)
2756 mutex_unlock(&xps_map_mutex);
2758 kfree(new_dev_maps);
2761 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2763 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2769 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2774 EXPORT_SYMBOL(netif_set_xps_queue);
2777 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2779 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2781 /* Unbind any subordinate channels */
2782 while (txq-- != &dev->_tx[0]) {
2784 netdev_unbind_sb_channel(dev, txq->sb_dev);
2788 void netdev_reset_tc(struct net_device *dev)
2791 netif_reset_xps_queues_gt(dev, 0);
2793 netdev_unbind_all_sb_channels(dev);
2795 /* Reset TC configuration of device */
2797 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2798 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2800 EXPORT_SYMBOL(netdev_reset_tc);
2802 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2804 if (tc >= dev->num_tc)
2808 netif_reset_xps_queues(dev, offset, count);
2810 dev->tc_to_txq[tc].count = count;
2811 dev->tc_to_txq[tc].offset = offset;
2814 EXPORT_SYMBOL(netdev_set_tc_queue);
2816 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2818 if (num_tc > TC_MAX_QUEUE)
2822 netif_reset_xps_queues_gt(dev, 0);
2824 netdev_unbind_all_sb_channels(dev);
2826 dev->num_tc = num_tc;
2829 EXPORT_SYMBOL(netdev_set_num_tc);
2831 void netdev_unbind_sb_channel(struct net_device *dev,
2832 struct net_device *sb_dev)
2834 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2837 netif_reset_xps_queues_gt(sb_dev, 0);
2839 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2840 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2842 while (txq-- != &dev->_tx[0]) {
2843 if (txq->sb_dev == sb_dev)
2847 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2849 int netdev_bind_sb_channel_queue(struct net_device *dev,
2850 struct net_device *sb_dev,
2851 u8 tc, u16 count, u16 offset)
2853 /* Make certain the sb_dev and dev are already configured */
2854 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2857 /* We cannot hand out queues we don't have */
2858 if ((offset + count) > dev->real_num_tx_queues)
2861 /* Record the mapping */
2862 sb_dev->tc_to_txq[tc].count = count;
2863 sb_dev->tc_to_txq[tc].offset = offset;
2865 /* Provide a way for Tx queue to find the tc_to_txq map or
2866 * XPS map for itself.
2869 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2873 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2875 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2877 /* Do not use a multiqueue device to represent a subordinate channel */
2878 if (netif_is_multiqueue(dev))
2881 /* We allow channels 1 - 32767 to be used for subordinate channels.
2882 * Channel 0 is meant to be "native" mode and used only to represent
2883 * the main root device. We allow writing 0 to reset the device back
2884 * to normal mode after being used as a subordinate channel.
2886 if (channel > S16_MAX)
2889 dev->num_tc = -channel;
2893 EXPORT_SYMBOL(netdev_set_sb_channel);
2896 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2897 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2899 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2904 disabling = txq < dev->real_num_tx_queues;
2906 if (txq < 1 || txq > dev->num_tx_queues)
2909 if (dev->reg_state == NETREG_REGISTERED ||
2910 dev->reg_state == NETREG_UNREGISTERING) {
2913 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2919 netif_setup_tc(dev, txq);
2921 dev_qdisc_change_real_num_tx(dev, txq);
2923 dev->real_num_tx_queues = txq;
2927 qdisc_reset_all_tx_gt(dev, txq);
2929 netif_reset_xps_queues_gt(dev, txq);
2933 dev->real_num_tx_queues = txq;
2938 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2942 * netif_set_real_num_rx_queues - set actual number of RX queues used
2943 * @dev: Network device
2944 * @rxq: Actual number of RX queues
2946 * This must be called either with the rtnl_lock held or before
2947 * registration of the net device. Returns 0 on success, or a
2948 * negative error code. If called before registration, it always
2951 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2955 if (rxq < 1 || rxq > dev->num_rx_queues)
2958 if (dev->reg_state == NETREG_REGISTERED) {
2961 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2967 dev->real_num_rx_queues = rxq;
2970 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
2974 * netif_set_real_num_queues - set actual number of RX and TX queues used
2975 * @dev: Network device
2976 * @txq: Actual number of TX queues
2977 * @rxq: Actual number of RX queues
2979 * Set the real number of both TX and RX queues.
2980 * Does nothing if the number of queues is already correct.
2982 int netif_set_real_num_queues(struct net_device *dev,
2983 unsigned int txq, unsigned int rxq)
2985 unsigned int old_rxq = dev->real_num_rx_queues;
2988 if (txq < 1 || txq > dev->num_tx_queues ||
2989 rxq < 1 || rxq > dev->num_rx_queues)
2992 /* Start from increases, so the error path only does decreases -
2993 * decreases can't fail.
2995 if (rxq > dev->real_num_rx_queues) {
2996 err = netif_set_real_num_rx_queues(dev, rxq);
3000 if (txq > dev->real_num_tx_queues) {
3001 err = netif_set_real_num_tx_queues(dev, txq);
3005 if (rxq < dev->real_num_rx_queues)
3006 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3007 if (txq < dev->real_num_tx_queues)
3008 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3012 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3015 EXPORT_SYMBOL(netif_set_real_num_queues);
3018 * netif_set_tso_max_size() - set the max size of TSO frames supported
3019 * @dev: netdev to update
3020 * @size: max skb->len of a TSO frame
3022 * Set the limit on the size of TSO super-frames the device can handle.
3023 * Unless explicitly set the stack will assume the value of
3024 * %GSO_LEGACY_MAX_SIZE.
3026 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3028 dev->tso_max_size = min(GSO_MAX_SIZE, size);
3029 if (size < READ_ONCE(dev->gso_max_size))
3030 netif_set_gso_max_size(dev, size);
3031 if (size < READ_ONCE(dev->gso_ipv4_max_size))
3032 netif_set_gso_ipv4_max_size(dev, size);
3034 EXPORT_SYMBOL(netif_set_tso_max_size);
3037 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3038 * @dev: netdev to update
3039 * @segs: max number of TCP segments
3041 * Set the limit on the number of TCP segments the device can generate from
3042 * a single TSO super-frame.
3043 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3045 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3047 dev->tso_max_segs = segs;
3048 if (segs < READ_ONCE(dev->gso_max_segs))
3049 netif_set_gso_max_segs(dev, segs);
3051 EXPORT_SYMBOL(netif_set_tso_max_segs);
3054 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3055 * @to: netdev to update
3056 * @from: netdev from which to copy the limits
3058 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3060 netif_set_tso_max_size(to, from->tso_max_size);
3061 netif_set_tso_max_segs(to, from->tso_max_segs);
3063 EXPORT_SYMBOL(netif_inherit_tso_max);
3066 * netif_get_num_default_rss_queues - default number of RSS queues
3068 * Default value is the number of physical cores if there are only 1 or 2, or
3069 * divided by 2 if there are more.
3071 int netif_get_num_default_rss_queues(void)
3076 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3079 cpumask_copy(cpus, cpu_online_mask);
3080 for_each_cpu(cpu, cpus) {
3082 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3084 free_cpumask_var(cpus);
3086 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3088 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3090 static void __netif_reschedule(struct Qdisc *q)
3092 struct softnet_data *sd;
3093 unsigned long flags;
3095 local_irq_save(flags);
3096 sd = this_cpu_ptr(&softnet_data);
3097 q->next_sched = NULL;
3098 *sd->output_queue_tailp = q;
3099 sd->output_queue_tailp = &q->next_sched;
3100 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3101 local_irq_restore(flags);
3104 void __netif_schedule(struct Qdisc *q)
3106 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3107 __netif_reschedule(q);
3109 EXPORT_SYMBOL(__netif_schedule);
3111 struct dev_kfree_skb_cb {
3112 enum skb_drop_reason reason;
3115 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3117 return (struct dev_kfree_skb_cb *)skb->cb;
3120 void netif_schedule_queue(struct netdev_queue *txq)
3123 if (!netif_xmit_stopped(txq)) {
3124 struct Qdisc *q = rcu_dereference(txq->qdisc);
3126 __netif_schedule(q);
3130 EXPORT_SYMBOL(netif_schedule_queue);
3132 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3134 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3138 q = rcu_dereference(dev_queue->qdisc);
3139 __netif_schedule(q);
3143 EXPORT_SYMBOL(netif_tx_wake_queue);
3145 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3147 unsigned long flags;
3152 if (likely(refcount_read(&skb->users) == 1)) {
3154 refcount_set(&skb->users, 0);
3155 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3158 get_kfree_skb_cb(skb)->reason = reason;
3159 local_irq_save(flags);
3160 skb->next = __this_cpu_read(softnet_data.completion_queue);
3161 __this_cpu_write(softnet_data.completion_queue, skb);
3162 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3163 local_irq_restore(flags);
3165 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3167 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3169 if (in_hardirq() || irqs_disabled())
3170 dev_kfree_skb_irq_reason(skb, reason);
3172 kfree_skb_reason(skb, reason);
3174 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3178 * netif_device_detach - mark device as removed
3179 * @dev: network device
3181 * Mark device as removed from system and therefore no longer available.
3183 void netif_device_detach(struct net_device *dev)
3185 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3186 netif_running(dev)) {
3187 netif_tx_stop_all_queues(dev);
3190 EXPORT_SYMBOL(netif_device_detach);
3193 * netif_device_attach - mark device as attached
3194 * @dev: network device
3196 * Mark device as attached from system and restart if needed.
3198 void netif_device_attach(struct net_device *dev)
3200 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3201 netif_running(dev)) {
3202 netif_tx_wake_all_queues(dev);
3203 __netdev_watchdog_up(dev);
3206 EXPORT_SYMBOL(netif_device_attach);
3209 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3210 * to be used as a distribution range.
3212 static u16 skb_tx_hash(const struct net_device *dev,
3213 const struct net_device *sb_dev,
3214 struct sk_buff *skb)
3218 u16 qcount = dev->real_num_tx_queues;
3221 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3223 qoffset = sb_dev->tc_to_txq[tc].offset;
3224 qcount = sb_dev->tc_to_txq[tc].count;
3225 if (unlikely(!qcount)) {
3226 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3227 sb_dev->name, qoffset, tc);
3229 qcount = dev->real_num_tx_queues;
3233 if (skb_rx_queue_recorded(skb)) {
3234 DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3235 hash = skb_get_rx_queue(skb);
3236 if (hash >= qoffset)
3238 while (unlikely(hash >= qcount))
3240 return hash + qoffset;
3243 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3246 void skb_warn_bad_offload(const struct sk_buff *skb)
3248 static const netdev_features_t null_features;
3249 struct net_device *dev = skb->dev;
3250 const char *name = "";
3252 if (!net_ratelimit())
3256 if (dev->dev.parent)
3257 name = dev_driver_string(dev->dev.parent);
3259 name = netdev_name(dev);
3261 skb_dump(KERN_WARNING, skb, false);
3262 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3263 name, dev ? &dev->features : &null_features,
3264 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3268 * Invalidate hardware checksum when packet is to be mangled, and
3269 * complete checksum manually on outgoing path.
3271 int skb_checksum_help(struct sk_buff *skb)
3274 int ret = 0, offset;
3276 if (skb->ip_summed == CHECKSUM_COMPLETE)
3277 goto out_set_summed;
3279 if (unlikely(skb_is_gso(skb))) {
3280 skb_warn_bad_offload(skb);
3284 /* Before computing a checksum, we should make sure no frag could
3285 * be modified by an external entity : checksum could be wrong.
3287 if (skb_has_shared_frag(skb)) {
3288 ret = __skb_linearize(skb);
3293 offset = skb_checksum_start_offset(skb);
3295 if (unlikely(offset >= skb_headlen(skb))) {
3296 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3297 WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
3298 offset, skb_headlen(skb));
3301 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3303 offset += skb->csum_offset;
3304 if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
3305 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3306 WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
3307 offset + sizeof(__sum16), skb_headlen(skb));
3310 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3314 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3316 skb->ip_summed = CHECKSUM_NONE;
3320 EXPORT_SYMBOL(skb_checksum_help);
3322 int skb_crc32c_csum_help(struct sk_buff *skb)
3325 int ret = 0, offset, start;
3327 if (skb->ip_summed != CHECKSUM_PARTIAL)
3330 if (unlikely(skb_is_gso(skb)))
3333 /* Before computing a checksum, we should make sure no frag could
3334 * be modified by an external entity : checksum could be wrong.
3336 if (unlikely(skb_has_shared_frag(skb))) {
3337 ret = __skb_linearize(skb);
3341 start = skb_checksum_start_offset(skb);
3342 offset = start + offsetof(struct sctphdr, checksum);
3343 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3348 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3352 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3353 skb->len - start, ~(__u32)0,
3355 *(__le32 *)(skb->data + offset) = crc32c_csum;
3356 skb_reset_csum_not_inet(skb);
3361 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3363 __be16 type = skb->protocol;
3365 /* Tunnel gso handlers can set protocol to ethernet. */
3366 if (type == htons(ETH_P_TEB)) {
3369 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3372 eth = (struct ethhdr *)skb->data;
3373 type = eth->h_proto;
3376 return vlan_get_protocol_and_depth(skb, type, depth);
3380 /* Take action when hardware reception checksum errors are detected. */
3382 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3384 netdev_err(dev, "hw csum failure\n");
3385 skb_dump(KERN_ERR, skb, true);
3389 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3391 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3393 EXPORT_SYMBOL(netdev_rx_csum_fault);
3396 /* XXX: check that highmem exists at all on the given machine. */
3397 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3399 #ifdef CONFIG_HIGHMEM
3402 if (!(dev->features & NETIF_F_HIGHDMA)) {
3403 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3404 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3406 if (PageHighMem(skb_frag_page(frag)))
3414 /* If MPLS offload request, verify we are testing hardware MPLS features
3415 * instead of standard features for the netdev.
3417 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3418 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3419 netdev_features_t features,
3422 if (eth_p_mpls(type))
3423 features &= skb->dev->mpls_features;
3428 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3429 netdev_features_t features,
3436 static netdev_features_t harmonize_features(struct sk_buff *skb,
3437 netdev_features_t features)
3441 type = skb_network_protocol(skb, NULL);
3442 features = net_mpls_features(skb, features, type);
3444 if (skb->ip_summed != CHECKSUM_NONE &&
3445 !can_checksum_protocol(features, type)) {
3446 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3448 if (illegal_highdma(skb->dev, skb))
3449 features &= ~NETIF_F_SG;
3454 netdev_features_t passthru_features_check(struct sk_buff *skb,
3455 struct net_device *dev,
3456 netdev_features_t features)
3460 EXPORT_SYMBOL(passthru_features_check);
3462 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3463 struct net_device *dev,
3464 netdev_features_t features)
3466 return vlan_features_check(skb, features);
3469 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3470 struct net_device *dev,
3471 netdev_features_t features)
3473 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3475 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3476 return features & ~NETIF_F_GSO_MASK;
3478 if (!skb_shinfo(skb)->gso_type) {
3479 skb_warn_bad_offload(skb);
3480 return features & ~NETIF_F_GSO_MASK;
3483 /* Support for GSO partial features requires software
3484 * intervention before we can actually process the packets
3485 * so we need to strip support for any partial features now
3486 * and we can pull them back in after we have partially
3487 * segmented the frame.
3489 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3490 features &= ~dev->gso_partial_features;
3492 /* Make sure to clear the IPv4 ID mangling feature if the
3493 * IPv4 header has the potential to be fragmented.
3495 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3496 struct iphdr *iph = skb->encapsulation ?
3497 inner_ip_hdr(skb) : ip_hdr(skb);
3499 if (!(iph->frag_off & htons(IP_DF)))
3500 features &= ~NETIF_F_TSO_MANGLEID;
3506 netdev_features_t netif_skb_features(struct sk_buff *skb)
3508 struct net_device *dev = skb->dev;
3509 netdev_features_t features = dev->features;
3511 if (skb_is_gso(skb))
3512 features = gso_features_check(skb, dev, features);
3514 /* If encapsulation offload request, verify we are testing
3515 * hardware encapsulation features instead of standard
3516 * features for the netdev
3518 if (skb->encapsulation)
3519 features &= dev->hw_enc_features;
3521 if (skb_vlan_tagged(skb))
3522 features = netdev_intersect_features(features,
3523 dev->vlan_features |
3524 NETIF_F_HW_VLAN_CTAG_TX |
3525 NETIF_F_HW_VLAN_STAG_TX);
3527 if (dev->netdev_ops->ndo_features_check)
3528 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3531 features &= dflt_features_check(skb, dev, features);
3533 return harmonize_features(skb, features);
3535 EXPORT_SYMBOL(netif_skb_features);
3537 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3538 struct netdev_queue *txq, bool more)
3543 if (dev_nit_active(dev))
3544 dev_queue_xmit_nit(skb, dev);
3547 trace_net_dev_start_xmit(skb, dev);
3548 rc = netdev_start_xmit(skb, dev, txq, more);
3549 trace_net_dev_xmit(skb, rc, dev, len);
3554 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3555 struct netdev_queue *txq, int *ret)
3557 struct sk_buff *skb = first;
3558 int rc = NETDEV_TX_OK;
3561 struct sk_buff *next = skb->next;
3563 skb_mark_not_on_list(skb);
3564 rc = xmit_one(skb, dev, txq, next != NULL);
3565 if (unlikely(!dev_xmit_complete(rc))) {
3571 if (netif_tx_queue_stopped(txq) && skb) {
3572 rc = NETDEV_TX_BUSY;
3582 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3583 netdev_features_t features)
3585 if (skb_vlan_tag_present(skb) &&
3586 !vlan_hw_offload_capable(features, skb->vlan_proto))
3587 skb = __vlan_hwaccel_push_inside(skb);
3591 int skb_csum_hwoffload_help(struct sk_buff *skb,
3592 const netdev_features_t features)
3594 if (unlikely(skb_csum_is_sctp(skb)))
3595 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3596 skb_crc32c_csum_help(skb);
3598 if (features & NETIF_F_HW_CSUM)
3601 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3602 switch (skb->csum_offset) {
3603 case offsetof(struct tcphdr, check):
3604 case offsetof(struct udphdr, check):
3609 return skb_checksum_help(skb);
3611 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3613 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3615 netdev_features_t features;
3617 features = netif_skb_features(skb);
3618 skb = validate_xmit_vlan(skb, features);
3622 skb = sk_validate_xmit_skb(skb, dev);
3626 if (netif_needs_gso(skb, features)) {
3627 struct sk_buff *segs;
3629 segs = skb_gso_segment(skb, features);
3637 if (skb_needs_linearize(skb, features) &&
3638 __skb_linearize(skb))
3641 /* If packet is not checksummed and device does not
3642 * support checksumming for this protocol, complete
3643 * checksumming here.
3645 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3646 if (skb->encapsulation)
3647 skb_set_inner_transport_header(skb,
3648 skb_checksum_start_offset(skb));
3650 skb_set_transport_header(skb,
3651 skb_checksum_start_offset(skb));
3652 if (skb_csum_hwoffload_help(skb, features))
3657 skb = validate_xmit_xfrm(skb, features, again);
3664 dev_core_stats_tx_dropped_inc(dev);
3668 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3670 struct sk_buff *next, *head = NULL, *tail;
3672 for (; skb != NULL; skb = next) {
3674 skb_mark_not_on_list(skb);
3676 /* in case skb wont be segmented, point to itself */
3679 skb = validate_xmit_skb(skb, dev, again);
3687 /* If skb was segmented, skb->prev points to
3688 * the last segment. If not, it still contains skb.
3694 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3696 static void qdisc_pkt_len_init(struct sk_buff *skb)
3698 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3700 qdisc_skb_cb(skb)->pkt_len = skb->len;
3702 /* To get more precise estimation of bytes sent on wire,
3703 * we add to pkt_len the headers size of all segments
3705 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3706 u16 gso_segs = shinfo->gso_segs;
3707 unsigned int hdr_len;
3709 /* mac layer + network layer */
3710 hdr_len = skb_transport_offset(skb);
3712 /* + transport layer */
3713 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3714 const struct tcphdr *th;
3715 struct tcphdr _tcphdr;
3717 th = skb_header_pointer(skb, hdr_len,
3718 sizeof(_tcphdr), &_tcphdr);
3720 hdr_len += __tcp_hdrlen(th);
3722 struct udphdr _udphdr;
3724 if (skb_header_pointer(skb, hdr_len,
3725 sizeof(_udphdr), &_udphdr))
3726 hdr_len += sizeof(struct udphdr);
3729 if (shinfo->gso_type & SKB_GSO_DODGY)
3730 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3733 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3737 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3738 struct sk_buff **to_free,
3739 struct netdev_queue *txq)
3743 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3744 if (rc == NET_XMIT_SUCCESS)
3745 trace_qdisc_enqueue(q, txq, skb);
3749 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3750 struct net_device *dev,
3751 struct netdev_queue *txq)
3753 spinlock_t *root_lock = qdisc_lock(q);
3754 struct sk_buff *to_free = NULL;
3758 qdisc_calculate_pkt_len(skb, q);
3760 if (q->flags & TCQ_F_NOLOCK) {
3761 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3762 qdisc_run_begin(q)) {
3763 /* Retest nolock_qdisc_is_empty() within the protection
3764 * of q->seqlock to protect from racing with requeuing.
3766 if (unlikely(!nolock_qdisc_is_empty(q))) {
3767 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3774 qdisc_bstats_cpu_update(q, skb);
3775 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3776 !nolock_qdisc_is_empty(q))
3780 return NET_XMIT_SUCCESS;
3783 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3787 if (unlikely(to_free))
3788 kfree_skb_list_reason(to_free,
3789 SKB_DROP_REASON_QDISC_DROP);
3794 * Heuristic to force contended enqueues to serialize on a
3795 * separate lock before trying to get qdisc main lock.
3796 * This permits qdisc->running owner to get the lock more
3797 * often and dequeue packets faster.
3798 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3799 * and then other tasks will only enqueue packets. The packets will be
3800 * sent after the qdisc owner is scheduled again. To prevent this
3801 * scenario the task always serialize on the lock.
3803 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3804 if (unlikely(contended))
3805 spin_lock(&q->busylock);
3807 spin_lock(root_lock);
3808 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3809 __qdisc_drop(skb, &to_free);
3811 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3812 qdisc_run_begin(q)) {
3814 * This is a work-conserving queue; there are no old skbs
3815 * waiting to be sent out; and the qdisc is not running -
3816 * xmit the skb directly.
3819 qdisc_bstats_update(q, skb);
3821 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3822 if (unlikely(contended)) {
3823 spin_unlock(&q->busylock);
3830 rc = NET_XMIT_SUCCESS;
3832 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3833 if (qdisc_run_begin(q)) {
3834 if (unlikely(contended)) {
3835 spin_unlock(&q->busylock);
3842 spin_unlock(root_lock);
3843 if (unlikely(to_free))
3844 kfree_skb_list_reason(to_free, SKB_DROP_REASON_QDISC_DROP);
3845 if (unlikely(contended))
3846 spin_unlock(&q->busylock);
3850 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3851 static void skb_update_prio(struct sk_buff *skb)
3853 const struct netprio_map *map;
3854 const struct sock *sk;
3855 unsigned int prioidx;
3859 map = rcu_dereference_bh(skb->dev->priomap);
3862 sk = skb_to_full_sk(skb);
3866 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3868 if (prioidx < map->priomap_len)
3869 skb->priority = map->priomap[prioidx];
3872 #define skb_update_prio(skb)
3876 * dev_loopback_xmit - loop back @skb
3877 * @net: network namespace this loopback is happening in
3878 * @sk: sk needed to be a netfilter okfn
3879 * @skb: buffer to transmit
3881 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3883 skb_reset_mac_header(skb);
3884 __skb_pull(skb, skb_network_offset(skb));
3885 skb->pkt_type = PACKET_LOOPBACK;
3886 if (skb->ip_summed == CHECKSUM_NONE)
3887 skb->ip_summed = CHECKSUM_UNNECESSARY;
3888 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
3893 EXPORT_SYMBOL(dev_loopback_xmit);
3895 #ifdef CONFIG_NET_EGRESS
3896 static struct netdev_queue *
3897 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
3899 int qm = skb_get_queue_mapping(skb);
3901 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
3904 static bool netdev_xmit_txqueue_skipped(void)
3906 return __this_cpu_read(softnet_data.xmit.skip_txqueue);
3909 void netdev_xmit_skip_txqueue(bool skip)
3911 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
3913 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3914 #endif /* CONFIG_NET_EGRESS */
3916 #ifdef CONFIG_NET_XGRESS
3917 static int tc_run(struct tcx_entry *entry, struct sk_buff *skb)
3919 int ret = TC_ACT_UNSPEC;
3920 #ifdef CONFIG_NET_CLS_ACT
3921 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
3922 struct tcf_result res;
3927 tc_skb_cb(skb)->mru = 0;
3928 tc_skb_cb(skb)->post_ct = false;
3930 mini_qdisc_bstats_cpu_update(miniq, skb);
3931 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
3932 /* Only tcf related quirks below. */
3935 mini_qdisc_qstats_cpu_drop(miniq);
3938 case TC_ACT_RECLASSIFY:
3939 skb->tc_index = TC_H_MIN(res.classid);
3942 #endif /* CONFIG_NET_CLS_ACT */
3946 static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
3950 static_branch_inc(&tcx_needed_key);
3955 static_branch_dec(&tcx_needed_key);
3958 static __always_inline enum tcx_action_base
3959 tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
3960 const bool needs_mac)
3962 const struct bpf_mprog_fp *fp;
3963 const struct bpf_prog *prog;
3967 __skb_push(skb, skb->mac_len);
3968 bpf_mprog_foreach_prog(entry, fp, prog) {
3969 bpf_compute_data_pointers(skb);
3970 ret = bpf_prog_run(prog, skb);
3971 if (ret != TCX_NEXT)
3975 __skb_pull(skb, skb->mac_len);
3976 return tcx_action_code(skb, ret);
3979 static __always_inline struct sk_buff *
3980 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
3981 struct net_device *orig_dev, bool *another)
3983 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
3989 *ret = deliver_skb(skb, *pt_prev, orig_dev);
3993 qdisc_skb_cb(skb)->pkt_len = skb->len;
3994 tcx_set_ingress(skb, true);
3996 if (static_branch_unlikely(&tcx_needed_key)) {
3997 sch_ret = tcx_run(entry, skb, true);
3998 if (sch_ret != TC_ACT_UNSPEC)
3999 goto ingress_verdict;
4001 sch_ret = tc_run(tcx_entry(entry), skb);
4004 case TC_ACT_REDIRECT:
4005 /* skb_mac_header check was done by BPF, so we can safely
4006 * push the L2 header back before redirecting to another
4009 __skb_push(skb, skb->mac_len);
4010 if (skb_do_redirect(skb) == -EAGAIN) {
4011 __skb_pull(skb, skb->mac_len);
4015 *ret = NET_RX_SUCCESS;
4018 kfree_skb_reason(skb, SKB_DROP_REASON_TC_INGRESS);
4021 /* used by tc_run */
4027 case TC_ACT_CONSUMED:
4028 *ret = NET_RX_SUCCESS;
4035 static __always_inline struct sk_buff *
4036 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4038 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
4044 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
4045 * already set by the caller.
4047 if (static_branch_unlikely(&tcx_needed_key)) {
4048 sch_ret = tcx_run(entry, skb, false);
4049 if (sch_ret != TC_ACT_UNSPEC)
4050 goto egress_verdict;
4052 sch_ret = tc_run(tcx_entry(entry), skb);
4055 case TC_ACT_REDIRECT:
4056 /* No need to push/pop skb's mac_header here on egress! */
4057 skb_do_redirect(skb);
4058 *ret = NET_XMIT_SUCCESS;
4061 kfree_skb_reason(skb, SKB_DROP_REASON_TC_EGRESS);
4062 *ret = NET_XMIT_DROP;
4064 /* used by tc_run */
4070 case TC_ACT_CONSUMED:
4071 *ret = NET_XMIT_SUCCESS;
4078 static __always_inline struct sk_buff *
4079 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4080 struct net_device *orig_dev, bool *another)
4085 static __always_inline struct sk_buff *
4086 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4090 #endif /* CONFIG_NET_XGRESS */
4093 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
4094 struct xps_dev_maps *dev_maps, unsigned int tci)
4096 int tc = netdev_get_prio_tc_map(dev, skb->priority);
4097 struct xps_map *map;
4098 int queue_index = -1;
4100 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
4103 tci *= dev_maps->num_tc;
4106 map = rcu_dereference(dev_maps->attr_map[tci]);
4109 queue_index = map->queues[0];
4111 queue_index = map->queues[reciprocal_scale(
4112 skb_get_hash(skb), map->len)];
4113 if (unlikely(queue_index >= dev->real_num_tx_queues))
4120 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
4121 struct sk_buff *skb)
4124 struct xps_dev_maps *dev_maps;
4125 struct sock *sk = skb->sk;
4126 int queue_index = -1;
4128 if (!static_key_false(&xps_needed))
4132 if (!static_key_false(&xps_rxqs_needed))
4135 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
4137 int tci = sk_rx_queue_get(sk);
4140 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4145 if (queue_index < 0) {
4146 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
4148 unsigned int tci = skb->sender_cpu - 1;
4150 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4162 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
4163 struct net_device *sb_dev)
4167 EXPORT_SYMBOL(dev_pick_tx_zero);
4169 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4170 struct net_device *sb_dev)
4172 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4174 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4176 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4177 struct net_device *sb_dev)
4179 struct sock *sk = skb->sk;
4180 int queue_index = sk_tx_queue_get(sk);
4182 sb_dev = sb_dev ? : dev;
4184 if (queue_index < 0 || skb->ooo_okay ||
4185 queue_index >= dev->real_num_tx_queues) {
4186 int new_index = get_xps_queue(dev, sb_dev, skb);
4189 new_index = skb_tx_hash(dev, sb_dev, skb);
4191 if (queue_index != new_index && sk &&
4193 rcu_access_pointer(sk->sk_dst_cache))
4194 sk_tx_queue_set(sk, new_index);
4196 queue_index = new_index;
4201 EXPORT_SYMBOL(netdev_pick_tx);
4203 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4204 struct sk_buff *skb,
4205 struct net_device *sb_dev)
4207 int queue_index = 0;
4210 u32 sender_cpu = skb->sender_cpu - 1;
4212 if (sender_cpu >= (u32)NR_CPUS)
4213 skb->sender_cpu = raw_smp_processor_id() + 1;
4216 if (dev->real_num_tx_queues != 1) {
4217 const struct net_device_ops *ops = dev->netdev_ops;
4219 if (ops->ndo_select_queue)
4220 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4222 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4224 queue_index = netdev_cap_txqueue(dev, queue_index);
4227 skb_set_queue_mapping(skb, queue_index);
4228 return netdev_get_tx_queue(dev, queue_index);
4232 * __dev_queue_xmit() - transmit a buffer
4233 * @skb: buffer to transmit
4234 * @sb_dev: suboordinate device used for L2 forwarding offload
4236 * Queue a buffer for transmission to a network device. The caller must
4237 * have set the device and priority and built the buffer before calling
4238 * this function. The function can be called from an interrupt.
4240 * When calling this method, interrupts MUST be enabled. This is because
4241 * the BH enable code must have IRQs enabled so that it will not deadlock.
4243 * Regardless of the return value, the skb is consumed, so it is currently
4244 * difficult to retry a send to this method. (You can bump the ref count
4245 * before sending to hold a reference for retry if you are careful.)
4248 * * 0 - buffer successfully transmitted
4249 * * positive qdisc return code - NET_XMIT_DROP etc.
4250 * * negative errno - other errors
4252 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4254 struct net_device *dev = skb->dev;
4255 struct netdev_queue *txq = NULL;
4260 skb_reset_mac_header(skb);
4261 skb_assert_len(skb);
4263 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4264 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4266 /* Disable soft irqs for various locks below. Also
4267 * stops preemption for RCU.
4271 skb_update_prio(skb);
4273 qdisc_pkt_len_init(skb);
4274 tcx_set_ingress(skb, false);
4275 #ifdef CONFIG_NET_EGRESS
4276 if (static_branch_unlikely(&egress_needed_key)) {
4277 if (nf_hook_egress_active()) {
4278 skb = nf_hook_egress(skb, &rc, dev);
4283 netdev_xmit_skip_txqueue(false);
4285 nf_skip_egress(skb, true);
4286 skb = sch_handle_egress(skb, &rc, dev);
4289 nf_skip_egress(skb, false);
4291 if (netdev_xmit_txqueue_skipped())
4292 txq = netdev_tx_queue_mapping(dev, skb);
4295 /* If device/qdisc don't need skb->dst, release it right now while
4296 * its hot in this cpu cache.
4298 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4304 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4306 q = rcu_dereference_bh(txq->qdisc);
4308 trace_net_dev_queue(skb);
4310 rc = __dev_xmit_skb(skb, q, dev, txq);
4314 /* The device has no queue. Common case for software devices:
4315 * loopback, all the sorts of tunnels...
4317 * Really, it is unlikely that netif_tx_lock protection is necessary
4318 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4320 * However, it is possible, that they rely on protection
4323 * Check this and shot the lock. It is not prone from deadlocks.
4324 *Either shot noqueue qdisc, it is even simpler 8)
4326 if (dev->flags & IFF_UP) {
4327 int cpu = smp_processor_id(); /* ok because BHs are off */
4329 /* Other cpus might concurrently change txq->xmit_lock_owner
4330 * to -1 or to their cpu id, but not to our id.
4332 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4333 if (dev_xmit_recursion())
4334 goto recursion_alert;
4336 skb = validate_xmit_skb(skb, dev, &again);
4340 HARD_TX_LOCK(dev, txq, cpu);
4342 if (!netif_xmit_stopped(txq)) {
4343 dev_xmit_recursion_inc();
4344 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4345 dev_xmit_recursion_dec();
4346 if (dev_xmit_complete(rc)) {
4347 HARD_TX_UNLOCK(dev, txq);
4351 HARD_TX_UNLOCK(dev, txq);
4352 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4355 /* Recursion is detected! It is possible,
4359 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4365 rcu_read_unlock_bh();
4367 dev_core_stats_tx_dropped_inc(dev);
4368 kfree_skb_list(skb);
4371 rcu_read_unlock_bh();
4374 EXPORT_SYMBOL(__dev_queue_xmit);
4376 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4378 struct net_device *dev = skb->dev;
4379 struct sk_buff *orig_skb = skb;
4380 struct netdev_queue *txq;
4381 int ret = NETDEV_TX_BUSY;
4384 if (unlikely(!netif_running(dev) ||
4385 !netif_carrier_ok(dev)))
4388 skb = validate_xmit_skb_list(skb, dev, &again);
4389 if (skb != orig_skb)
4392 skb_set_queue_mapping(skb, queue_id);
4393 txq = skb_get_tx_queue(dev, skb);
4397 dev_xmit_recursion_inc();
4398 HARD_TX_LOCK(dev, txq, smp_processor_id());
4399 if (!netif_xmit_frozen_or_drv_stopped(txq))
4400 ret = netdev_start_xmit(skb, dev, txq, false);
4401 HARD_TX_UNLOCK(dev, txq);
4402 dev_xmit_recursion_dec();
4407 dev_core_stats_tx_dropped_inc(dev);
4408 kfree_skb_list(skb);
4409 return NET_XMIT_DROP;
4411 EXPORT_SYMBOL(__dev_direct_xmit);
4413 /*************************************************************************
4415 *************************************************************************/
4417 int netdev_max_backlog __read_mostly = 1000;
4418 EXPORT_SYMBOL(netdev_max_backlog);
4420 int netdev_tstamp_prequeue __read_mostly = 1;
4421 unsigned int sysctl_skb_defer_max __read_mostly = 64;
4422 int netdev_budget __read_mostly = 300;
4423 /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
4424 unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
4425 int weight_p __read_mostly = 64; /* old backlog weight */
4426 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4427 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4428 int dev_rx_weight __read_mostly = 64;
4429 int dev_tx_weight __read_mostly = 64;
4431 /* Called with irq disabled */
4432 static inline void ____napi_schedule(struct softnet_data *sd,
4433 struct napi_struct *napi)
4435 struct task_struct *thread;
4437 lockdep_assert_irqs_disabled();
4439 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4440 /* Paired with smp_mb__before_atomic() in
4441 * napi_enable()/dev_set_threaded().
4442 * Use READ_ONCE() to guarantee a complete
4443 * read on napi->thread. Only call
4444 * wake_up_process() when it's not NULL.
4446 thread = READ_ONCE(napi->thread);
4448 /* Avoid doing set_bit() if the thread is in
4449 * INTERRUPTIBLE state, cause napi_thread_wait()
4450 * makes sure to proceed with napi polling
4451 * if the thread is explicitly woken from here.
4453 if (READ_ONCE(thread->__state) != TASK_INTERRUPTIBLE)
4454 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4455 wake_up_process(thread);
4460 list_add_tail(&napi->poll_list, &sd->poll_list);
4461 WRITE_ONCE(napi->list_owner, smp_processor_id());
4462 /* If not called from net_rx_action()
4463 * we have to raise NET_RX_SOFTIRQ.
4465 if (!sd->in_net_rx_action)
4466 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4471 /* One global table that all flow-based protocols share. */
4472 struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
4473 EXPORT_SYMBOL(rps_sock_flow_table);
4474 u32 rps_cpu_mask __read_mostly;
4475 EXPORT_SYMBOL(rps_cpu_mask);
4477 struct static_key_false rps_needed __read_mostly;
4478 EXPORT_SYMBOL(rps_needed);
4479 struct static_key_false rfs_needed __read_mostly;
4480 EXPORT_SYMBOL(rfs_needed);
4482 static struct rps_dev_flow *
4483 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4484 struct rps_dev_flow *rflow, u16 next_cpu)
4486 if (next_cpu < nr_cpu_ids) {
4487 #ifdef CONFIG_RFS_ACCEL
4488 struct netdev_rx_queue *rxqueue;
4489 struct rps_dev_flow_table *flow_table;
4490 struct rps_dev_flow *old_rflow;
4495 /* Should we steer this flow to a different hardware queue? */
4496 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4497 !(dev->features & NETIF_F_NTUPLE))
4499 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4500 if (rxq_index == skb_get_rx_queue(skb))
4503 rxqueue = dev->_rx + rxq_index;
4504 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4507 flow_id = skb_get_hash(skb) & flow_table->mask;
4508 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4509 rxq_index, flow_id);
4513 rflow = &flow_table->flows[flow_id];
4515 if (old_rflow->filter == rflow->filter)
4516 old_rflow->filter = RPS_NO_FILTER;
4520 per_cpu(softnet_data, next_cpu).input_queue_head;
4523 rflow->cpu = next_cpu;
4528 * get_rps_cpu is called from netif_receive_skb and returns the target
4529 * CPU from the RPS map of the receiving queue for a given skb.
4530 * rcu_read_lock must be held on entry.
4532 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4533 struct rps_dev_flow **rflowp)
4535 const struct rps_sock_flow_table *sock_flow_table;
4536 struct netdev_rx_queue *rxqueue = dev->_rx;
4537 struct rps_dev_flow_table *flow_table;
4538 struct rps_map *map;
4543 if (skb_rx_queue_recorded(skb)) {
4544 u16 index = skb_get_rx_queue(skb);
4546 if (unlikely(index >= dev->real_num_rx_queues)) {
4547 WARN_ONCE(dev->real_num_rx_queues > 1,
4548 "%s received packet on queue %u, but number "
4549 "of RX queues is %u\n",
4550 dev->name, index, dev->real_num_rx_queues);
4556 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4558 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4559 map = rcu_dereference(rxqueue->rps_map);
4560 if (!flow_table && !map)
4563 skb_reset_network_header(skb);
4564 hash = skb_get_hash(skb);
4568 sock_flow_table = rcu_dereference(rps_sock_flow_table);
4569 if (flow_table && sock_flow_table) {
4570 struct rps_dev_flow *rflow;
4574 /* First check into global flow table if there is a match.
4575 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
4577 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
4578 if ((ident ^ hash) & ~rps_cpu_mask)
4581 next_cpu = ident & rps_cpu_mask;
4583 /* OK, now we know there is a match,
4584 * we can look at the local (per receive queue) flow table
4586 rflow = &flow_table->flows[hash & flow_table->mask];
4590 * If the desired CPU (where last recvmsg was done) is
4591 * different from current CPU (one in the rx-queue flow
4592 * table entry), switch if one of the following holds:
4593 * - Current CPU is unset (>= nr_cpu_ids).
4594 * - Current CPU is offline.
4595 * - The current CPU's queue tail has advanced beyond the
4596 * last packet that was enqueued using this table entry.
4597 * This guarantees that all previous packets for the flow
4598 * have been dequeued, thus preserving in order delivery.
4600 if (unlikely(tcpu != next_cpu) &&
4601 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4602 ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
4603 rflow->last_qtail)) >= 0)) {
4605 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4608 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4618 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4619 if (cpu_online(tcpu)) {
4629 #ifdef CONFIG_RFS_ACCEL
4632 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4633 * @dev: Device on which the filter was set
4634 * @rxq_index: RX queue index
4635 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4636 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4638 * Drivers that implement ndo_rx_flow_steer() should periodically call
4639 * this function for each installed filter and remove the filters for
4640 * which it returns %true.
4642 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4643 u32 flow_id, u16 filter_id)
4645 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4646 struct rps_dev_flow_table *flow_table;
4647 struct rps_dev_flow *rflow;
4652 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4653 if (flow_table && flow_id <= flow_table->mask) {
4654 rflow = &flow_table->flows[flow_id];
4655 cpu = READ_ONCE(rflow->cpu);
4656 if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
4657 ((int)(per_cpu(softnet_data, cpu).input_queue_head -
4658 rflow->last_qtail) <
4659 (int)(10 * flow_table->mask)))
4665 EXPORT_SYMBOL(rps_may_expire_flow);
4667 #endif /* CONFIG_RFS_ACCEL */
4669 /* Called from hardirq (IPI) context */
4670 static void rps_trigger_softirq(void *data)
4672 struct softnet_data *sd = data;
4674 ____napi_schedule(sd, &sd->backlog);
4678 #endif /* CONFIG_RPS */
4680 /* Called from hardirq (IPI) context */
4681 static void trigger_rx_softirq(void *data)
4683 struct softnet_data *sd = data;
4685 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4686 smp_store_release(&sd->defer_ipi_scheduled, 0);
4690 * After we queued a packet into sd->input_pkt_queue,
4691 * we need to make sure this queue is serviced soon.
4693 * - If this is another cpu queue, link it to our rps_ipi_list,
4694 * and make sure we will process rps_ipi_list from net_rx_action().
4696 * - If this is our own queue, NAPI schedule our backlog.
4697 * Note that this also raises NET_RX_SOFTIRQ.
4699 static void napi_schedule_rps(struct softnet_data *sd)
4701 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4705 sd->rps_ipi_next = mysd->rps_ipi_list;
4706 mysd->rps_ipi_list = sd;
4708 /* If not called from net_rx_action() or napi_threaded_poll()
4709 * we have to raise NET_RX_SOFTIRQ.
4711 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
4712 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4715 #endif /* CONFIG_RPS */
4716 __napi_schedule_irqoff(&mysd->backlog);
4719 #ifdef CONFIG_NET_FLOW_LIMIT
4720 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4723 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4725 #ifdef CONFIG_NET_FLOW_LIMIT
4726 struct sd_flow_limit *fl;
4727 struct softnet_data *sd;
4728 unsigned int old_flow, new_flow;
4730 if (qlen < (READ_ONCE(netdev_max_backlog) >> 1))
4733 sd = this_cpu_ptr(&softnet_data);
4736 fl = rcu_dereference(sd->flow_limit);
4738 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4739 old_flow = fl->history[fl->history_head];
4740 fl->history[fl->history_head] = new_flow;
4743 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4745 if (likely(fl->buckets[old_flow]))
4746 fl->buckets[old_flow]--;
4748 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4760 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4761 * queue (may be a remote CPU queue).
4763 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4764 unsigned int *qtail)
4766 enum skb_drop_reason reason;
4767 struct softnet_data *sd;
4768 unsigned long flags;
4771 reason = SKB_DROP_REASON_NOT_SPECIFIED;
4772 sd = &per_cpu(softnet_data, cpu);
4774 rps_lock_irqsave(sd, &flags);
4775 if (!netif_running(skb->dev))
4777 qlen = skb_queue_len(&sd->input_pkt_queue);
4778 if (qlen <= READ_ONCE(netdev_max_backlog) && !skb_flow_limit(skb, qlen)) {
4781 __skb_queue_tail(&sd->input_pkt_queue, skb);
4782 input_queue_tail_incr_save(sd, qtail);
4783 rps_unlock_irq_restore(sd, &flags);
4784 return NET_RX_SUCCESS;
4787 /* Schedule NAPI for backlog device
4788 * We can use non atomic operation since we own the queue lock
4790 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4791 napi_schedule_rps(sd);
4794 reason = SKB_DROP_REASON_CPU_BACKLOG;
4798 rps_unlock_irq_restore(sd, &flags);
4800 dev_core_stats_rx_dropped_inc(skb->dev);
4801 kfree_skb_reason(skb, reason);
4805 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4807 struct net_device *dev = skb->dev;
4808 struct netdev_rx_queue *rxqueue;
4812 if (skb_rx_queue_recorded(skb)) {
4813 u16 index = skb_get_rx_queue(skb);
4815 if (unlikely(index >= dev->real_num_rx_queues)) {
4816 WARN_ONCE(dev->real_num_rx_queues > 1,
4817 "%s received packet on queue %u, but number "
4818 "of RX queues is %u\n",
4819 dev->name, index, dev->real_num_rx_queues);
4821 return rxqueue; /* Return first rxqueue */
4828 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4829 struct bpf_prog *xdp_prog)
4831 void *orig_data, *orig_data_end, *hard_start;
4832 struct netdev_rx_queue *rxqueue;
4833 bool orig_bcast, orig_host;
4834 u32 mac_len, frame_sz;
4835 __be16 orig_eth_type;
4840 /* The XDP program wants to see the packet starting at the MAC
4843 mac_len = skb->data - skb_mac_header(skb);
4844 hard_start = skb->data - skb_headroom(skb);
4846 /* SKB "head" area always have tailroom for skb_shared_info */
4847 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4848 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4850 rxqueue = netif_get_rxqueue(skb);
4851 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4852 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4853 skb_headlen(skb) + mac_len, true);
4855 orig_data_end = xdp->data_end;
4856 orig_data = xdp->data;
4857 eth = (struct ethhdr *)xdp->data;
4858 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4859 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4860 orig_eth_type = eth->h_proto;
4862 act = bpf_prog_run_xdp(xdp_prog, xdp);
4864 /* check if bpf_xdp_adjust_head was used */
4865 off = xdp->data - orig_data;
4868 __skb_pull(skb, off);
4870 __skb_push(skb, -off);
4872 skb->mac_header += off;
4873 skb_reset_network_header(skb);
4876 /* check if bpf_xdp_adjust_tail was used */
4877 off = xdp->data_end - orig_data_end;
4879 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4880 skb->len += off; /* positive on grow, negative on shrink */
4883 /* check if XDP changed eth hdr such SKB needs update */
4884 eth = (struct ethhdr *)xdp->data;
4885 if ((orig_eth_type != eth->h_proto) ||
4886 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4887 skb->dev->dev_addr)) ||
4888 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4889 __skb_push(skb, ETH_HLEN);
4890 skb->pkt_type = PACKET_HOST;
4891 skb->protocol = eth_type_trans(skb, skb->dev);
4894 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
4895 * before calling us again on redirect path. We do not call do_redirect
4896 * as we leave that up to the caller.
4898 * Caller is responsible for managing lifetime of skb (i.e. calling
4899 * kfree_skb in response to actions it cannot handle/XDP_DROP).
4904 __skb_push(skb, mac_len);
4907 metalen = xdp->data - xdp->data_meta;
4909 skb_metadata_set(skb, metalen);
4916 static u32 netif_receive_generic_xdp(struct sk_buff *skb,
4917 struct xdp_buff *xdp,
4918 struct bpf_prog *xdp_prog)
4922 /* Reinjected packets coming from act_mirred or similar should
4923 * not get XDP generic processing.
4925 if (skb_is_redirected(skb))
4928 /* XDP packets must be linear and must have sufficient headroom
4929 * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
4930 * native XDP provides, thus we need to do it here as well.
4932 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
4933 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
4934 int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
4935 int troom = skb->tail + skb->data_len - skb->end;
4937 /* In case we have to go down the path and also linearize,
4938 * then lets do the pskb_expand_head() work just once here.
4940 if (pskb_expand_head(skb,
4941 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
4942 troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
4944 if (skb_linearize(skb))
4948 act = bpf_prog_run_generic_xdp(skb, xdp, xdp_prog);
4955 bpf_warn_invalid_xdp_action(skb->dev, xdp_prog, act);
4958 trace_xdp_exception(skb->dev, xdp_prog, act);
4969 /* When doing generic XDP we have to bypass the qdisc layer and the
4970 * network taps in order to match in-driver-XDP behavior. This also means
4971 * that XDP packets are able to starve other packets going through a qdisc,
4972 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
4973 * queues, so they do not have this starvation issue.
4975 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
4977 struct net_device *dev = skb->dev;
4978 struct netdev_queue *txq;
4979 bool free_skb = true;
4982 txq = netdev_core_pick_tx(dev, skb, NULL);
4983 cpu = smp_processor_id();
4984 HARD_TX_LOCK(dev, txq, cpu);
4985 if (!netif_xmit_frozen_or_drv_stopped(txq)) {
4986 rc = netdev_start_xmit(skb, dev, txq, 0);
4987 if (dev_xmit_complete(rc))
4990 HARD_TX_UNLOCK(dev, txq);
4992 trace_xdp_exception(dev, xdp_prog, XDP_TX);
4993 dev_core_stats_tx_dropped_inc(dev);
4998 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
5000 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
5003 struct xdp_buff xdp;
5007 act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
5008 if (act != XDP_PASS) {
5011 err = xdp_do_generic_redirect(skb->dev, skb,
5017 generic_xdp_tx(skb, xdp_prog);
5025 kfree_skb_reason(skb, SKB_DROP_REASON_XDP);
5028 EXPORT_SYMBOL_GPL(do_xdp_generic);
5030 static int netif_rx_internal(struct sk_buff *skb)
5034 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5036 trace_netif_rx(skb);
5039 if (static_branch_unlikely(&rps_needed)) {
5040 struct rps_dev_flow voidflow, *rflow = &voidflow;
5045 cpu = get_rps_cpu(skb->dev, skb, &rflow);
5047 cpu = smp_processor_id();
5049 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5057 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
5063 * __netif_rx - Slightly optimized version of netif_rx
5064 * @skb: buffer to post
5066 * This behaves as netif_rx except that it does not disable bottom halves.
5067 * As a result this function may only be invoked from the interrupt context
5068 * (either hard or soft interrupt).
5070 int __netif_rx(struct sk_buff *skb)
5074 lockdep_assert_once(hardirq_count() | softirq_count());
5076 trace_netif_rx_entry(skb);
5077 ret = netif_rx_internal(skb);
5078 trace_netif_rx_exit(ret);
5081 EXPORT_SYMBOL(__netif_rx);
5084 * netif_rx - post buffer to the network code
5085 * @skb: buffer to post
5087 * This function receives a packet from a device driver and queues it for
5088 * the upper (protocol) levels to process via the backlog NAPI device. It
5089 * always succeeds. The buffer may be dropped during processing for
5090 * congestion control or by the protocol layers.
5091 * The network buffer is passed via the backlog NAPI device. Modern NIC
5092 * driver should use NAPI and GRO.
5093 * This function can used from interrupt and from process context. The
5094 * caller from process context must not disable interrupts before invoking
5098 * NET_RX_SUCCESS (no congestion)
5099 * NET_RX_DROP (packet was dropped)
5102 int netif_rx(struct sk_buff *skb)
5104 bool need_bh_off = !(hardirq_count() | softirq_count());
5109 trace_netif_rx_entry(skb);
5110 ret = netif_rx_internal(skb);
5111 trace_netif_rx_exit(ret);
5116 EXPORT_SYMBOL(netif_rx);
5118 static __latent_entropy void net_tx_action(struct softirq_action *h)
5120 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
5122 if (sd->completion_queue) {
5123 struct sk_buff *clist;
5125 local_irq_disable();
5126 clist = sd->completion_queue;
5127 sd->completion_queue = NULL;
5131 struct sk_buff *skb = clist;
5133 clist = clist->next;
5135 WARN_ON(refcount_read(&skb->users));
5136 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
5137 trace_consume_skb(skb, net_tx_action);
5139 trace_kfree_skb(skb, net_tx_action,
5140 get_kfree_skb_cb(skb)->reason);
5142 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
5145 __napi_kfree_skb(skb,
5146 get_kfree_skb_cb(skb)->reason);
5150 if (sd->output_queue) {
5153 local_irq_disable();
5154 head = sd->output_queue;
5155 sd->output_queue = NULL;
5156 sd->output_queue_tailp = &sd->output_queue;
5162 struct Qdisc *q = head;
5163 spinlock_t *root_lock = NULL;
5165 head = head->next_sched;
5167 /* We need to make sure head->next_sched is read
5168 * before clearing __QDISC_STATE_SCHED
5170 smp_mb__before_atomic();
5172 if (!(q->flags & TCQ_F_NOLOCK)) {
5173 root_lock = qdisc_lock(q);
5174 spin_lock(root_lock);
5175 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
5177 /* There is a synchronize_net() between
5178 * STATE_DEACTIVATED flag being set and
5179 * qdisc_reset()/some_qdisc_is_busy() in
5180 * dev_deactivate(), so we can safely bail out
5181 * early here to avoid data race between
5182 * qdisc_deactivate() and some_qdisc_is_busy()
5183 * for lockless qdisc.
5185 clear_bit(__QDISC_STATE_SCHED, &q->state);
5189 clear_bit(__QDISC_STATE_SCHED, &q->state);
5192 spin_unlock(root_lock);
5198 xfrm_dev_backlog(sd);
5201 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5202 /* This hook is defined here for ATM LANE */
5203 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5204 unsigned char *addr) __read_mostly;
5205 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5209 * netdev_is_rx_handler_busy - check if receive handler is registered
5210 * @dev: device to check
5212 * Check if a receive handler is already registered for a given device.
5213 * Return true if there one.
5215 * The caller must hold the rtnl_mutex.
5217 bool netdev_is_rx_handler_busy(struct net_device *dev)
5220 return dev && rtnl_dereference(dev->rx_handler);
5222 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5225 * netdev_rx_handler_register - register receive handler
5226 * @dev: device to register a handler for
5227 * @rx_handler: receive handler to register
5228 * @rx_handler_data: data pointer that is used by rx handler
5230 * Register a receive handler for a device. This handler will then be
5231 * called from __netif_receive_skb. A negative errno code is returned
5234 * The caller must hold the rtnl_mutex.
5236 * For a general description of rx_handler, see enum rx_handler_result.
5238 int netdev_rx_handler_register(struct net_device *dev,
5239 rx_handler_func_t *rx_handler,
5240 void *rx_handler_data)
5242 if (netdev_is_rx_handler_busy(dev))
5245 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5248 /* Note: rx_handler_data must be set before rx_handler */
5249 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5250 rcu_assign_pointer(dev->rx_handler, rx_handler);
5254 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5257 * netdev_rx_handler_unregister - unregister receive handler
5258 * @dev: device to unregister a handler from
5260 * Unregister a receive handler from a device.
5262 * The caller must hold the rtnl_mutex.
5264 void netdev_rx_handler_unregister(struct net_device *dev)
5268 RCU_INIT_POINTER(dev->rx_handler, NULL);
5269 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5270 * section has a guarantee to see a non NULL rx_handler_data
5274 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5276 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5279 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5280 * the special handling of PFMEMALLOC skbs.
5282 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5284 switch (skb->protocol) {
5285 case htons(ETH_P_ARP):
5286 case htons(ETH_P_IP):
5287 case htons(ETH_P_IPV6):
5288 case htons(ETH_P_8021Q):
5289 case htons(ETH_P_8021AD):
5296 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5297 int *ret, struct net_device *orig_dev)
5299 if (nf_hook_ingress_active(skb)) {
5303 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5308 ingress_retval = nf_hook_ingress(skb);
5310 return ingress_retval;
5315 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5316 struct packet_type **ppt_prev)
5318 struct packet_type *ptype, *pt_prev;
5319 rx_handler_func_t *rx_handler;
5320 struct sk_buff *skb = *pskb;
5321 struct net_device *orig_dev;
5322 bool deliver_exact = false;
5323 int ret = NET_RX_DROP;
5326 net_timestamp_check(!READ_ONCE(netdev_tstamp_prequeue), skb);
5328 trace_netif_receive_skb(skb);
5330 orig_dev = skb->dev;
5332 skb_reset_network_header(skb);
5333 if (!skb_transport_header_was_set(skb))
5334 skb_reset_transport_header(skb);
5335 skb_reset_mac_len(skb);
5340 skb->skb_iif = skb->dev->ifindex;
5342 __this_cpu_inc(softnet_data.processed);
5344 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5348 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
5351 if (ret2 != XDP_PASS) {
5357 if (eth_type_vlan(skb->protocol)) {
5358 skb = skb_vlan_untag(skb);
5363 if (skb_skip_tc_classify(skb))
5369 list_for_each_entry_rcu(ptype, &ptype_all, list) {
5371 ret = deliver_skb(skb, pt_prev, orig_dev);
5375 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5377 ret = deliver_skb(skb, pt_prev, orig_dev);
5382 #ifdef CONFIG_NET_INGRESS
5383 if (static_branch_unlikely(&ingress_needed_key)) {
5384 bool another = false;
5386 nf_skip_egress(skb, true);
5387 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5394 nf_skip_egress(skb, false);
5395 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5399 skb_reset_redirect(skb);
5401 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5404 if (skb_vlan_tag_present(skb)) {
5406 ret = deliver_skb(skb, pt_prev, orig_dev);
5409 if (vlan_do_receive(&skb))
5411 else if (unlikely(!skb))
5415 rx_handler = rcu_dereference(skb->dev->rx_handler);
5418 ret = deliver_skb(skb, pt_prev, orig_dev);
5421 switch (rx_handler(&skb)) {
5422 case RX_HANDLER_CONSUMED:
5423 ret = NET_RX_SUCCESS;
5425 case RX_HANDLER_ANOTHER:
5427 case RX_HANDLER_EXACT:
5428 deliver_exact = true;
5430 case RX_HANDLER_PASS:
5437 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5439 if (skb_vlan_tag_get_id(skb)) {
5440 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5443 skb->pkt_type = PACKET_OTHERHOST;
5444 } else if (eth_type_vlan(skb->protocol)) {
5445 /* Outer header is 802.1P with vlan 0, inner header is
5446 * 802.1Q or 802.1AD and vlan_do_receive() above could
5447 * not find vlan dev for vlan id 0.
5449 __vlan_hwaccel_clear_tag(skb);
5450 skb = skb_vlan_untag(skb);
5453 if (vlan_do_receive(&skb))
5454 /* After stripping off 802.1P header with vlan 0
5455 * vlan dev is found for inner header.
5458 else if (unlikely(!skb))
5461 /* We have stripped outer 802.1P vlan 0 header.
5462 * But could not find vlan dev.
5463 * check again for vlan id to set OTHERHOST.
5467 /* Note: we might in the future use prio bits
5468 * and set skb->priority like in vlan_do_receive()
5469 * For the time being, just ignore Priority Code Point
5471 __vlan_hwaccel_clear_tag(skb);
5474 type = skb->protocol;
5476 /* deliver only exact match when indicated */
5477 if (likely(!deliver_exact)) {
5478 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5479 &ptype_base[ntohs(type) &
5483 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5484 &orig_dev->ptype_specific);
5486 if (unlikely(skb->dev != orig_dev)) {
5487 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5488 &skb->dev->ptype_specific);
5492 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5494 *ppt_prev = pt_prev;
5498 dev_core_stats_rx_dropped_inc(skb->dev);
5500 dev_core_stats_rx_nohandler_inc(skb->dev);
5501 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5502 /* Jamal, now you will not able to escape explaining
5503 * me how you were going to use this. :-)
5509 /* The invariant here is that if *ppt_prev is not NULL
5510 * then skb should also be non-NULL.
5512 * Apparently *ppt_prev assignment above holds this invariant due to
5513 * skb dereferencing near it.
5519 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5521 struct net_device *orig_dev = skb->dev;
5522 struct packet_type *pt_prev = NULL;
5525 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5527 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5528 skb->dev, pt_prev, orig_dev);
5533 * netif_receive_skb_core - special purpose version of netif_receive_skb
5534 * @skb: buffer to process
5536 * More direct receive version of netif_receive_skb(). It should
5537 * only be used by callers that have a need to skip RPS and Generic XDP.
5538 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5540 * This function may only be called from softirq context and interrupts
5541 * should be enabled.
5543 * Return values (usually ignored):
5544 * NET_RX_SUCCESS: no congestion
5545 * NET_RX_DROP: packet was dropped
5547 int netif_receive_skb_core(struct sk_buff *skb)
5552 ret = __netif_receive_skb_one_core(skb, false);
5557 EXPORT_SYMBOL(netif_receive_skb_core);
5559 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5560 struct packet_type *pt_prev,
5561 struct net_device *orig_dev)
5563 struct sk_buff *skb, *next;
5567 if (list_empty(head))
5569 if (pt_prev->list_func != NULL)
5570 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5571 ip_list_rcv, head, pt_prev, orig_dev);
5573 list_for_each_entry_safe(skb, next, head, list) {
5574 skb_list_del_init(skb);
5575 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5579 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5581 /* Fast-path assumptions:
5582 * - There is no RX handler.
5583 * - Only one packet_type matches.
5584 * If either of these fails, we will end up doing some per-packet
5585 * processing in-line, then handling the 'last ptype' for the whole
5586 * sublist. This can't cause out-of-order delivery to any single ptype,
5587 * because the 'last ptype' must be constant across the sublist, and all
5588 * other ptypes are handled per-packet.
5590 /* Current (common) ptype of sublist */
5591 struct packet_type *pt_curr = NULL;
5592 /* Current (common) orig_dev of sublist */
5593 struct net_device *od_curr = NULL;
5594 struct list_head sublist;
5595 struct sk_buff *skb, *next;
5597 INIT_LIST_HEAD(&sublist);
5598 list_for_each_entry_safe(skb, next, head, list) {
5599 struct net_device *orig_dev = skb->dev;
5600 struct packet_type *pt_prev = NULL;
5602 skb_list_del_init(skb);
5603 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5606 if (pt_curr != pt_prev || od_curr != orig_dev) {
5607 /* dispatch old sublist */
5608 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5609 /* start new sublist */
5610 INIT_LIST_HEAD(&sublist);
5614 list_add_tail(&skb->list, &sublist);
5617 /* dispatch final sublist */
5618 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5621 static int __netif_receive_skb(struct sk_buff *skb)
5625 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5626 unsigned int noreclaim_flag;
5629 * PFMEMALLOC skbs are special, they should
5630 * - be delivered to SOCK_MEMALLOC sockets only
5631 * - stay away from userspace
5632 * - have bounded memory usage
5634 * Use PF_MEMALLOC as this saves us from propagating the allocation
5635 * context down to all allocation sites.
5637 noreclaim_flag = memalloc_noreclaim_save();
5638 ret = __netif_receive_skb_one_core(skb, true);
5639 memalloc_noreclaim_restore(noreclaim_flag);
5641 ret = __netif_receive_skb_one_core(skb, false);
5646 static void __netif_receive_skb_list(struct list_head *head)
5648 unsigned long noreclaim_flag = 0;
5649 struct sk_buff *skb, *next;
5650 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5652 list_for_each_entry_safe(skb, next, head, list) {
5653 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5654 struct list_head sublist;
5656 /* Handle the previous sublist */
5657 list_cut_before(&sublist, head, &skb->list);
5658 if (!list_empty(&sublist))
5659 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5660 pfmemalloc = !pfmemalloc;
5661 /* See comments in __netif_receive_skb */
5663 noreclaim_flag = memalloc_noreclaim_save();
5665 memalloc_noreclaim_restore(noreclaim_flag);
5668 /* Handle the remaining sublist */
5669 if (!list_empty(head))
5670 __netif_receive_skb_list_core(head, pfmemalloc);
5671 /* Restore pflags */
5673 memalloc_noreclaim_restore(noreclaim_flag);
5676 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5678 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5679 struct bpf_prog *new = xdp->prog;
5682 switch (xdp->command) {
5683 case XDP_SETUP_PROG:
5684 rcu_assign_pointer(dev->xdp_prog, new);
5689 static_branch_dec(&generic_xdp_needed_key);
5690 } else if (new && !old) {
5691 static_branch_inc(&generic_xdp_needed_key);
5692 dev_disable_lro(dev);
5693 dev_disable_gro_hw(dev);
5705 static int netif_receive_skb_internal(struct sk_buff *skb)
5709 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5711 if (skb_defer_rx_timestamp(skb))
5712 return NET_RX_SUCCESS;
5716 if (static_branch_unlikely(&rps_needed)) {
5717 struct rps_dev_flow voidflow, *rflow = &voidflow;
5718 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5721 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5727 ret = __netif_receive_skb(skb);
5732 void netif_receive_skb_list_internal(struct list_head *head)
5734 struct sk_buff *skb, *next;
5735 struct list_head sublist;
5737 INIT_LIST_HEAD(&sublist);
5738 list_for_each_entry_safe(skb, next, head, list) {
5739 net_timestamp_check(READ_ONCE(netdev_tstamp_prequeue), skb);
5740 skb_list_del_init(skb);
5741 if (!skb_defer_rx_timestamp(skb))
5742 list_add_tail(&skb->list, &sublist);
5744 list_splice_init(&sublist, head);
5748 if (static_branch_unlikely(&rps_needed)) {
5749 list_for_each_entry_safe(skb, next, head, list) {
5750 struct rps_dev_flow voidflow, *rflow = &voidflow;
5751 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5754 /* Will be handled, remove from list */
5755 skb_list_del_init(skb);
5756 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5761 __netif_receive_skb_list(head);
5766 * netif_receive_skb - process receive buffer from network
5767 * @skb: buffer to process
5769 * netif_receive_skb() is the main receive data processing function.
5770 * It always succeeds. The buffer may be dropped during processing
5771 * for congestion control or by the protocol layers.
5773 * This function may only be called from softirq context and interrupts
5774 * should be enabled.
5776 * Return values (usually ignored):
5777 * NET_RX_SUCCESS: no congestion
5778 * NET_RX_DROP: packet was dropped
5780 int netif_receive_skb(struct sk_buff *skb)
5784 trace_netif_receive_skb_entry(skb);
5786 ret = netif_receive_skb_internal(skb);
5787 trace_netif_receive_skb_exit(ret);
5791 EXPORT_SYMBOL(netif_receive_skb);
5794 * netif_receive_skb_list - process many receive buffers from network
5795 * @head: list of skbs to process.
5797 * Since return value of netif_receive_skb() is normally ignored, and
5798 * wouldn't be meaningful for a list, this function returns void.
5800 * This function may only be called from softirq context and interrupts
5801 * should be enabled.
5803 void netif_receive_skb_list(struct list_head *head)
5805 struct sk_buff *skb;
5807 if (list_empty(head))
5809 if (trace_netif_receive_skb_list_entry_enabled()) {
5810 list_for_each_entry(skb, head, list)
5811 trace_netif_receive_skb_list_entry(skb);
5813 netif_receive_skb_list_internal(head);
5814 trace_netif_receive_skb_list_exit(0);
5816 EXPORT_SYMBOL(netif_receive_skb_list);
5818 static DEFINE_PER_CPU(struct work_struct, flush_works);
5820 /* Network device is going away, flush any packets still pending */
5821 static void flush_backlog(struct work_struct *work)
5823 struct sk_buff *skb, *tmp;
5824 struct softnet_data *sd;
5827 sd = this_cpu_ptr(&softnet_data);
5829 rps_lock_irq_disable(sd);
5830 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5831 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5832 __skb_unlink(skb, &sd->input_pkt_queue);
5833 dev_kfree_skb_irq(skb);
5834 input_queue_head_incr(sd);
5837 rps_unlock_irq_enable(sd);
5839 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5840 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5841 __skb_unlink(skb, &sd->process_queue);
5843 input_queue_head_incr(sd);
5849 static bool flush_required(int cpu)
5851 #if IS_ENABLED(CONFIG_RPS)
5852 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5855 rps_lock_irq_disable(sd);
5857 /* as insertion into process_queue happens with the rps lock held,
5858 * process_queue access may race only with dequeue
5860 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5861 !skb_queue_empty_lockless(&sd->process_queue);
5862 rps_unlock_irq_enable(sd);
5866 /* without RPS we can't safely check input_pkt_queue: during a
5867 * concurrent remote skb_queue_splice() we can detect as empty both
5868 * input_pkt_queue and process_queue even if the latter could end-up
5869 * containing a lot of packets.
5874 static void flush_all_backlogs(void)
5876 static cpumask_t flush_cpus;
5879 /* since we are under rtnl lock protection we can use static data
5880 * for the cpumask and avoid allocating on stack the possibly
5887 cpumask_clear(&flush_cpus);
5888 for_each_online_cpu(cpu) {
5889 if (flush_required(cpu)) {
5890 queue_work_on(cpu, system_highpri_wq,
5891 per_cpu_ptr(&flush_works, cpu));
5892 cpumask_set_cpu(cpu, &flush_cpus);
5896 /* we can have in flight packet[s] on the cpus we are not flushing,
5897 * synchronize_net() in unregister_netdevice_many() will take care of
5900 for_each_cpu(cpu, &flush_cpus)
5901 flush_work(per_cpu_ptr(&flush_works, cpu));
5906 static void net_rps_send_ipi(struct softnet_data *remsd)
5910 struct softnet_data *next = remsd->rps_ipi_next;
5912 if (cpu_online(remsd->cpu))
5913 smp_call_function_single_async(remsd->cpu, &remsd->csd);
5920 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
5921 * Note: called with local irq disabled, but exits with local irq enabled.
5923 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
5926 struct softnet_data *remsd = sd->rps_ipi_list;
5929 sd->rps_ipi_list = NULL;
5933 /* Send pending IPI's to kick RPS processing on remote cpus. */
5934 net_rps_send_ipi(remsd);
5940 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
5943 return sd->rps_ipi_list != NULL;
5949 static int process_backlog(struct napi_struct *napi, int quota)
5951 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
5955 /* Check if we have pending ipi, its better to send them now,
5956 * not waiting net_rx_action() end.
5958 if (sd_has_rps_ipi_waiting(sd)) {
5959 local_irq_disable();
5960 net_rps_action_and_irq_enable(sd);
5963 napi->weight = READ_ONCE(dev_rx_weight);
5965 struct sk_buff *skb;
5967 while ((skb = __skb_dequeue(&sd->process_queue))) {
5969 __netif_receive_skb(skb);
5971 input_queue_head_incr(sd);
5972 if (++work >= quota)
5977 rps_lock_irq_disable(sd);
5978 if (skb_queue_empty(&sd->input_pkt_queue)) {
5980 * Inline a custom version of __napi_complete().
5981 * only current cpu owns and manipulates this napi,
5982 * and NAPI_STATE_SCHED is the only possible flag set
5984 * We can use a plain write instead of clear_bit(),
5985 * and we dont need an smp_mb() memory barrier.
5990 skb_queue_splice_tail_init(&sd->input_pkt_queue,
5991 &sd->process_queue);
5993 rps_unlock_irq_enable(sd);
6000 * __napi_schedule - schedule for receive
6001 * @n: entry to schedule
6003 * The entry's receive function will be scheduled to run.
6004 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6006 void __napi_schedule(struct napi_struct *n)
6008 unsigned long flags;
6010 local_irq_save(flags);
6011 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6012 local_irq_restore(flags);
6014 EXPORT_SYMBOL(__napi_schedule);
6017 * napi_schedule_prep - check if napi can be scheduled
6020 * Test if NAPI routine is already running, and if not mark
6021 * it as running. This is used as a condition variable to
6022 * insure only one NAPI poll instance runs. We also make
6023 * sure there is no pending NAPI disable.
6025 bool napi_schedule_prep(struct napi_struct *n)
6027 unsigned long new, val = READ_ONCE(n->state);
6030 if (unlikely(val & NAPIF_STATE_DISABLE))
6032 new = val | NAPIF_STATE_SCHED;
6034 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6035 * This was suggested by Alexander Duyck, as compiler
6036 * emits better code than :
6037 * if (val & NAPIF_STATE_SCHED)
6038 * new |= NAPIF_STATE_MISSED;
6040 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6042 } while (!try_cmpxchg(&n->state, &val, new));
6044 return !(val & NAPIF_STATE_SCHED);
6046 EXPORT_SYMBOL(napi_schedule_prep);
6049 * __napi_schedule_irqoff - schedule for receive
6050 * @n: entry to schedule
6052 * Variant of __napi_schedule() assuming hard irqs are masked.
6054 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6055 * because the interrupt disabled assumption might not be true
6056 * due to force-threaded interrupts and spinlock substitution.
6058 void __napi_schedule_irqoff(struct napi_struct *n)
6060 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6061 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6065 EXPORT_SYMBOL(__napi_schedule_irqoff);
6067 bool napi_complete_done(struct napi_struct *n, int work_done)
6069 unsigned long flags, val, new, timeout = 0;
6073 * 1) Don't let napi dequeue from the cpu poll list
6074 * just in case its running on a different cpu.
6075 * 2) If we are busy polling, do nothing here, we have
6076 * the guarantee we will be called later.
6078 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6079 NAPIF_STATE_IN_BUSY_POLL)))
6084 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6085 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6087 if (n->defer_hard_irqs_count > 0) {
6088 n->defer_hard_irqs_count--;
6089 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6093 if (n->gro_bitmask) {
6094 /* When the NAPI instance uses a timeout and keeps postponing
6095 * it, we need to bound somehow the time packets are kept in
6098 napi_gro_flush(n, !!timeout);
6103 if (unlikely(!list_empty(&n->poll_list))) {
6104 /* If n->poll_list is not empty, we need to mask irqs */
6105 local_irq_save(flags);
6106 list_del_init(&n->poll_list);
6107 local_irq_restore(flags);
6109 WRITE_ONCE(n->list_owner, -1);
6111 val = READ_ONCE(n->state);
6113 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6115 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6116 NAPIF_STATE_SCHED_THREADED |
6117 NAPIF_STATE_PREFER_BUSY_POLL);
6119 /* If STATE_MISSED was set, leave STATE_SCHED set,
6120 * because we will call napi->poll() one more time.
6121 * This C code was suggested by Alexander Duyck to help gcc.
6123 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6125 } while (!try_cmpxchg(&n->state, &val, new));
6127 if (unlikely(val & NAPIF_STATE_MISSED)) {
6133 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6134 HRTIMER_MODE_REL_PINNED);
6137 EXPORT_SYMBOL(napi_complete_done);
6139 /* must be called under rcu_read_lock(), as we dont take a reference */
6140 static struct napi_struct *napi_by_id(unsigned int napi_id)
6142 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6143 struct napi_struct *napi;
6145 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6146 if (napi->napi_id == napi_id)
6152 #if defined(CONFIG_NET_RX_BUSY_POLL)
6154 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6156 if (!skip_schedule) {
6157 gro_normal_list(napi);
6158 __napi_schedule(napi);
6162 if (napi->gro_bitmask) {
6163 /* flush too old packets
6164 * If HZ < 1000, flush all packets.
6166 napi_gro_flush(napi, HZ >= 1000);
6169 gro_normal_list(napi);
6170 clear_bit(NAPI_STATE_SCHED, &napi->state);
6173 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock, bool prefer_busy_poll,
6176 bool skip_schedule = false;
6177 unsigned long timeout;
6180 /* Busy polling means there is a high chance device driver hard irq
6181 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6182 * set in napi_schedule_prep().
6183 * Since we are about to call napi->poll() once more, we can safely
6184 * clear NAPI_STATE_MISSED.
6186 * Note: x86 could use a single "lock and ..." instruction
6187 * to perform these two clear_bit()
6189 clear_bit(NAPI_STATE_MISSED, &napi->state);
6190 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6194 if (prefer_busy_poll) {
6195 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6196 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6197 if (napi->defer_hard_irqs_count && timeout) {
6198 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6199 skip_schedule = true;
6203 /* All we really want here is to re-enable device interrupts.
6204 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6206 rc = napi->poll(napi, budget);
6207 /* We can't gro_normal_list() here, because napi->poll() might have
6208 * rearmed the napi (napi_complete_done()) in which case it could
6209 * already be running on another CPU.
6211 trace_napi_poll(napi, rc, budget);
6212 netpoll_poll_unlock(have_poll_lock);
6214 __busy_poll_stop(napi, skip_schedule);
6218 void napi_busy_loop(unsigned int napi_id,
6219 bool (*loop_end)(void *, unsigned long),
6220 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6222 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6223 int (*napi_poll)(struct napi_struct *napi, int budget);
6224 void *have_poll_lock = NULL;
6225 struct napi_struct *napi;
6232 napi = napi_by_id(napi_id);
6236 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6243 unsigned long val = READ_ONCE(napi->state);
6245 /* If multiple threads are competing for this napi,
6246 * we avoid dirtying napi->state as much as we can.
6248 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6249 NAPIF_STATE_IN_BUSY_POLL)) {
6250 if (prefer_busy_poll)
6251 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6254 if (cmpxchg(&napi->state, val,
6255 val | NAPIF_STATE_IN_BUSY_POLL |
6256 NAPIF_STATE_SCHED) != val) {
6257 if (prefer_busy_poll)
6258 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6261 have_poll_lock = netpoll_poll_lock(napi);
6262 napi_poll = napi->poll;
6264 work = napi_poll(napi, budget);
6265 trace_napi_poll(napi, work, budget);
6266 gro_normal_list(napi);
6269 __NET_ADD_STATS(dev_net(napi->dev),
6270 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6273 if (!loop_end || loop_end(loop_end_arg, start_time))
6276 if (unlikely(need_resched())) {
6278 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6279 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6283 if (loop_end(loop_end_arg, start_time))
6290 busy_poll_stop(napi, have_poll_lock, prefer_busy_poll, budget);
6291 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6296 EXPORT_SYMBOL(napi_busy_loop);
6298 #endif /* CONFIG_NET_RX_BUSY_POLL */
6300 static void napi_hash_add(struct napi_struct *napi)
6302 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6305 spin_lock(&napi_hash_lock);
6307 /* 0..NR_CPUS range is reserved for sender_cpu use */
6309 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6310 napi_gen_id = MIN_NAPI_ID;
6311 } while (napi_by_id(napi_gen_id));
6312 napi->napi_id = napi_gen_id;
6314 hlist_add_head_rcu(&napi->napi_hash_node,
6315 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6317 spin_unlock(&napi_hash_lock);
6320 /* Warning : caller is responsible to make sure rcu grace period
6321 * is respected before freeing memory containing @napi
6323 static void napi_hash_del(struct napi_struct *napi)
6325 spin_lock(&napi_hash_lock);
6327 hlist_del_init_rcu(&napi->napi_hash_node);
6329 spin_unlock(&napi_hash_lock);
6332 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6334 struct napi_struct *napi;
6336 napi = container_of(timer, struct napi_struct, timer);
6338 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6339 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6341 if (!napi_disable_pending(napi) &&
6342 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6343 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6344 __napi_schedule_irqoff(napi);
6347 return HRTIMER_NORESTART;
6350 static void init_gro_hash(struct napi_struct *napi)
6354 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6355 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6356 napi->gro_hash[i].count = 0;
6358 napi->gro_bitmask = 0;
6361 int dev_set_threaded(struct net_device *dev, bool threaded)
6363 struct napi_struct *napi;
6366 if (dev->threaded == threaded)
6370 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6371 if (!napi->thread) {
6372 err = napi_kthread_create(napi);
6381 dev->threaded = threaded;
6383 /* Make sure kthread is created before THREADED bit
6386 smp_mb__before_atomic();
6388 /* Setting/unsetting threaded mode on a napi might not immediately
6389 * take effect, if the current napi instance is actively being
6390 * polled. In this case, the switch between threaded mode and
6391 * softirq mode will happen in the next round of napi_schedule().
6392 * This should not cause hiccups/stalls to the live traffic.
6394 list_for_each_entry(napi, &dev->napi_list, dev_list)
6395 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6399 EXPORT_SYMBOL(dev_set_threaded);
6401 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6402 int (*poll)(struct napi_struct *, int), int weight)
6404 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6407 INIT_LIST_HEAD(&napi->poll_list);
6408 INIT_HLIST_NODE(&napi->napi_hash_node);
6409 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6410 napi->timer.function = napi_watchdog;
6411 init_gro_hash(napi);
6413 INIT_LIST_HEAD(&napi->rx_list);
6416 if (weight > NAPI_POLL_WEIGHT)
6417 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6419 napi->weight = weight;
6421 #ifdef CONFIG_NETPOLL
6422 napi->poll_owner = -1;
6424 napi->list_owner = -1;
6425 set_bit(NAPI_STATE_SCHED, &napi->state);
6426 set_bit(NAPI_STATE_NPSVC, &napi->state);
6427 list_add_rcu(&napi->dev_list, &dev->napi_list);
6428 napi_hash_add(napi);
6429 napi_get_frags_check(napi);
6430 /* Create kthread for this napi if dev->threaded is set.
6431 * Clear dev->threaded if kthread creation failed so that
6432 * threaded mode will not be enabled in napi_enable().
6434 if (dev->threaded && napi_kthread_create(napi))
6437 EXPORT_SYMBOL(netif_napi_add_weight);
6439 void napi_disable(struct napi_struct *n)
6441 unsigned long val, new;
6444 set_bit(NAPI_STATE_DISABLE, &n->state);
6446 val = READ_ONCE(n->state);
6448 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6449 usleep_range(20, 200);
6450 val = READ_ONCE(n->state);
6453 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6454 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6455 } while (!try_cmpxchg(&n->state, &val, new));
6457 hrtimer_cancel(&n->timer);
6459 clear_bit(NAPI_STATE_DISABLE, &n->state);
6461 EXPORT_SYMBOL(napi_disable);
6464 * napi_enable - enable NAPI scheduling
6467 * Resume NAPI from being scheduled on this context.
6468 * Must be paired with napi_disable.
6470 void napi_enable(struct napi_struct *n)
6472 unsigned long new, val = READ_ONCE(n->state);
6475 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6477 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6478 if (n->dev->threaded && n->thread)
6479 new |= NAPIF_STATE_THREADED;
6480 } while (!try_cmpxchg(&n->state, &val, new));
6482 EXPORT_SYMBOL(napi_enable);
6484 static void flush_gro_hash(struct napi_struct *napi)
6488 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6489 struct sk_buff *skb, *n;
6491 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6493 napi->gro_hash[i].count = 0;
6497 /* Must be called in process context */
6498 void __netif_napi_del(struct napi_struct *napi)
6500 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6503 napi_hash_del(napi);
6504 list_del_rcu(&napi->dev_list);
6505 napi_free_frags(napi);
6507 flush_gro_hash(napi);
6508 napi->gro_bitmask = 0;
6511 kthread_stop(napi->thread);
6512 napi->thread = NULL;
6515 EXPORT_SYMBOL(__netif_napi_del);
6517 static int __napi_poll(struct napi_struct *n, bool *repoll)
6523 /* This NAPI_STATE_SCHED test is for avoiding a race
6524 * with netpoll's poll_napi(). Only the entity which
6525 * obtains the lock and sees NAPI_STATE_SCHED set will
6526 * actually make the ->poll() call. Therefore we avoid
6527 * accidentally calling ->poll() when NAPI is not scheduled.
6530 if (test_bit(NAPI_STATE_SCHED, &n->state)) {
6531 work = n->poll(n, weight);
6532 trace_napi_poll(n, work, weight);
6535 if (unlikely(work > weight))
6536 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6537 n->poll, work, weight);
6539 if (likely(work < weight))
6542 /* Drivers must not modify the NAPI state if they
6543 * consume the entire weight. In such cases this code
6544 * still "owns" the NAPI instance and therefore can
6545 * move the instance around on the list at-will.
6547 if (unlikely(napi_disable_pending(n))) {
6552 /* The NAPI context has more processing work, but busy-polling
6553 * is preferred. Exit early.
6555 if (napi_prefer_busy_poll(n)) {
6556 if (napi_complete_done(n, work)) {
6557 /* If timeout is not set, we need to make sure
6558 * that the NAPI is re-scheduled.
6565 if (n->gro_bitmask) {
6566 /* flush too old packets
6567 * If HZ < 1000, flush all packets.
6569 napi_gro_flush(n, HZ >= 1000);
6574 /* Some drivers may have called napi_schedule
6575 * prior to exhausting their budget.
6577 if (unlikely(!list_empty(&n->poll_list))) {
6578 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6579 n->dev ? n->dev->name : "backlog");
6588 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6590 bool do_repoll = false;
6594 list_del_init(&n->poll_list);
6596 have = netpoll_poll_lock(n);
6598 work = __napi_poll(n, &do_repoll);
6601 list_add_tail(&n->poll_list, repoll);
6603 netpoll_poll_unlock(have);
6608 static int napi_thread_wait(struct napi_struct *napi)
6612 set_current_state(TASK_INTERRUPTIBLE);
6614 while (!kthread_should_stop()) {
6615 /* Testing SCHED_THREADED bit here to make sure the current
6616 * kthread owns this napi and could poll on this napi.
6617 * Testing SCHED bit is not enough because SCHED bit might be
6618 * set by some other busy poll thread or by napi_disable().
6620 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state) || woken) {
6621 WARN_ON(!list_empty(&napi->poll_list));
6622 __set_current_state(TASK_RUNNING);
6627 /* woken being true indicates this thread owns this napi. */
6629 set_current_state(TASK_INTERRUPTIBLE);
6631 __set_current_state(TASK_RUNNING);
6636 static void skb_defer_free_flush(struct softnet_data *sd)
6638 struct sk_buff *skb, *next;
6640 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6641 if (!READ_ONCE(sd->defer_list))
6644 spin_lock(&sd->defer_lock);
6645 skb = sd->defer_list;
6646 sd->defer_list = NULL;
6647 sd->defer_count = 0;
6648 spin_unlock(&sd->defer_lock);
6650 while (skb != NULL) {
6652 napi_consume_skb(skb, 1);
6657 static int napi_threaded_poll(void *data)
6659 struct napi_struct *napi = data;
6660 struct softnet_data *sd;
6663 while (!napi_thread_wait(napi)) {
6665 bool repoll = false;
6668 sd = this_cpu_ptr(&softnet_data);
6669 sd->in_napi_threaded_poll = true;
6671 have = netpoll_poll_lock(napi);
6672 __napi_poll(napi, &repoll);
6673 netpoll_poll_unlock(have);
6675 sd->in_napi_threaded_poll = false;
6678 if (sd_has_rps_ipi_waiting(sd)) {
6679 local_irq_disable();
6680 net_rps_action_and_irq_enable(sd);
6682 skb_defer_free_flush(sd);
6694 static __latent_entropy void net_rx_action(struct softirq_action *h)
6696 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6697 unsigned long time_limit = jiffies +
6698 usecs_to_jiffies(READ_ONCE(netdev_budget_usecs));
6699 int budget = READ_ONCE(netdev_budget);
6704 sd->in_net_rx_action = true;
6705 local_irq_disable();
6706 list_splice_init(&sd->poll_list, &list);
6710 struct napi_struct *n;
6712 skb_defer_free_flush(sd);
6714 if (list_empty(&list)) {
6715 if (list_empty(&repoll)) {
6716 sd->in_net_rx_action = false;
6718 /* We need to check if ____napi_schedule()
6719 * had refilled poll_list while
6720 * sd->in_net_rx_action was true.
6722 if (!list_empty(&sd->poll_list))
6724 if (!sd_has_rps_ipi_waiting(sd))
6730 n = list_first_entry(&list, struct napi_struct, poll_list);
6731 budget -= napi_poll(n, &repoll);
6733 /* If softirq window is exhausted then punt.
6734 * Allow this to run for 2 jiffies since which will allow
6735 * an average latency of 1.5/HZ.
6737 if (unlikely(budget <= 0 ||
6738 time_after_eq(jiffies, time_limit))) {
6744 local_irq_disable();
6746 list_splice_tail_init(&sd->poll_list, &list);
6747 list_splice_tail(&repoll, &list);
6748 list_splice(&list, &sd->poll_list);
6749 if (!list_empty(&sd->poll_list))
6750 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6752 sd->in_net_rx_action = false;
6754 net_rps_action_and_irq_enable(sd);
6758 struct netdev_adjacent {
6759 struct net_device *dev;
6760 netdevice_tracker dev_tracker;
6762 /* upper master flag, there can only be one master device per list */
6765 /* lookup ignore flag */
6768 /* counter for the number of times this device was added to us */
6771 /* private field for the users */
6774 struct list_head list;
6775 struct rcu_head rcu;
6778 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
6779 struct list_head *adj_list)
6781 struct netdev_adjacent *adj;
6783 list_for_each_entry(adj, adj_list, list) {
6784 if (adj->dev == adj_dev)
6790 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
6791 struct netdev_nested_priv *priv)
6793 struct net_device *dev = (struct net_device *)priv->data;
6795 return upper_dev == dev;
6799 * netdev_has_upper_dev - Check if device is linked to an upper device
6801 * @upper_dev: upper device to check
6803 * Find out if a device is linked to specified upper device and return true
6804 * in case it is. Note that this checks only immediate upper device,
6805 * not through a complete stack of devices. The caller must hold the RTNL lock.
6807 bool netdev_has_upper_dev(struct net_device *dev,
6808 struct net_device *upper_dev)
6810 struct netdev_nested_priv priv = {
6811 .data = (void *)upper_dev,
6816 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6819 EXPORT_SYMBOL(netdev_has_upper_dev);
6822 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
6824 * @upper_dev: upper device to check
6826 * Find out if a device is linked to specified upper device and return true
6827 * in case it is. Note that this checks the entire upper device chain.
6828 * The caller must hold rcu lock.
6831 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
6832 struct net_device *upper_dev)
6834 struct netdev_nested_priv priv = {
6835 .data = (void *)upper_dev,
6838 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
6841 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
6844 * netdev_has_any_upper_dev - Check if device is linked to some device
6847 * Find out if a device is linked to an upper device and return true in case
6848 * it is. The caller must hold the RTNL lock.
6850 bool netdev_has_any_upper_dev(struct net_device *dev)
6854 return !list_empty(&dev->adj_list.upper);
6856 EXPORT_SYMBOL(netdev_has_any_upper_dev);
6859 * netdev_master_upper_dev_get - Get master upper device
6862 * Find a master upper device and return pointer to it or NULL in case
6863 * it's not there. The caller must hold the RTNL lock.
6865 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
6867 struct netdev_adjacent *upper;
6871 if (list_empty(&dev->adj_list.upper))
6874 upper = list_first_entry(&dev->adj_list.upper,
6875 struct netdev_adjacent, list);
6876 if (likely(upper->master))
6880 EXPORT_SYMBOL(netdev_master_upper_dev_get);
6882 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
6884 struct netdev_adjacent *upper;
6888 if (list_empty(&dev->adj_list.upper))
6891 upper = list_first_entry(&dev->adj_list.upper,
6892 struct netdev_adjacent, list);
6893 if (likely(upper->master) && !upper->ignore)
6899 * netdev_has_any_lower_dev - Check if device is linked to some device
6902 * Find out if a device is linked to a lower device and return true in case
6903 * it is. The caller must hold the RTNL lock.
6905 static bool netdev_has_any_lower_dev(struct net_device *dev)
6909 return !list_empty(&dev->adj_list.lower);
6912 void *netdev_adjacent_get_private(struct list_head *adj_list)
6914 struct netdev_adjacent *adj;
6916 adj = list_entry(adj_list, struct netdev_adjacent, list);
6918 return adj->private;
6920 EXPORT_SYMBOL(netdev_adjacent_get_private);
6923 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
6925 * @iter: list_head ** of the current position
6927 * Gets the next device from the dev's upper list, starting from iter
6928 * position. The caller must hold RCU read lock.
6930 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
6931 struct list_head **iter)
6933 struct netdev_adjacent *upper;
6935 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6937 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6939 if (&upper->list == &dev->adj_list.upper)
6942 *iter = &upper->list;
6946 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
6948 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
6949 struct list_head **iter,
6952 struct netdev_adjacent *upper;
6954 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
6956 if (&upper->list == &dev->adj_list.upper)
6959 *iter = &upper->list;
6960 *ignore = upper->ignore;
6965 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
6966 struct list_head **iter)
6968 struct netdev_adjacent *upper;
6970 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
6972 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
6974 if (&upper->list == &dev->adj_list.upper)
6977 *iter = &upper->list;
6982 static int __netdev_walk_all_upper_dev(struct net_device *dev,
6983 int (*fn)(struct net_device *dev,
6984 struct netdev_nested_priv *priv),
6985 struct netdev_nested_priv *priv)
6987 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
6988 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
6993 iter = &dev->adj_list.upper;
6997 ret = fn(now, priv);
7004 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7011 niter = &udev->adj_list.upper;
7012 dev_stack[cur] = now;
7013 iter_stack[cur++] = iter;
7020 next = dev_stack[--cur];
7021 niter = iter_stack[cur];
7031 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7032 int (*fn)(struct net_device *dev,
7033 struct netdev_nested_priv *priv),
7034 struct netdev_nested_priv *priv)
7036 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7037 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7041 iter = &dev->adj_list.upper;
7045 ret = fn(now, priv);
7052 udev = netdev_next_upper_dev_rcu(now, &iter);
7057 niter = &udev->adj_list.upper;
7058 dev_stack[cur] = now;
7059 iter_stack[cur++] = iter;
7066 next = dev_stack[--cur];
7067 niter = iter_stack[cur];
7076 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7078 static bool __netdev_has_upper_dev(struct net_device *dev,
7079 struct net_device *upper_dev)
7081 struct netdev_nested_priv priv = {
7083 .data = (void *)upper_dev,
7088 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7093 * netdev_lower_get_next_private - Get the next ->private from the
7094 * lower neighbour list
7096 * @iter: list_head ** of the current position
7098 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7099 * list, starting from iter position. The caller must hold either hold the
7100 * RTNL lock or its own locking that guarantees that the neighbour lower
7101 * list will remain unchanged.
7103 void *netdev_lower_get_next_private(struct net_device *dev,
7104 struct list_head **iter)
7106 struct netdev_adjacent *lower;
7108 lower = list_entry(*iter, struct netdev_adjacent, list);
7110 if (&lower->list == &dev->adj_list.lower)
7113 *iter = lower->list.next;
7115 return lower->private;
7117 EXPORT_SYMBOL(netdev_lower_get_next_private);
7120 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7121 * lower neighbour list, RCU
7124 * @iter: list_head ** of the current position
7126 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7127 * list, starting from iter position. The caller must hold RCU read lock.
7129 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7130 struct list_head **iter)
7132 struct netdev_adjacent *lower;
7134 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7136 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7138 if (&lower->list == &dev->adj_list.lower)
7141 *iter = &lower->list;
7143 return lower->private;
7145 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7148 * netdev_lower_get_next - Get the next device from the lower neighbour
7151 * @iter: list_head ** of the current position
7153 * Gets the next netdev_adjacent from the dev's lower neighbour
7154 * list, starting from iter position. The caller must hold RTNL lock or
7155 * its own locking that guarantees that the neighbour lower
7156 * list will remain unchanged.
7158 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7160 struct netdev_adjacent *lower;
7162 lower = list_entry(*iter, struct netdev_adjacent, list);
7164 if (&lower->list == &dev->adj_list.lower)
7167 *iter = lower->list.next;
7171 EXPORT_SYMBOL(netdev_lower_get_next);
7173 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7174 struct list_head **iter)
7176 struct netdev_adjacent *lower;
7178 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7180 if (&lower->list == &dev->adj_list.lower)
7183 *iter = &lower->list;
7188 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7189 struct list_head **iter,
7192 struct netdev_adjacent *lower;
7194 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7196 if (&lower->list == &dev->adj_list.lower)
7199 *iter = &lower->list;
7200 *ignore = lower->ignore;
7205 int netdev_walk_all_lower_dev(struct net_device *dev,
7206 int (*fn)(struct net_device *dev,
7207 struct netdev_nested_priv *priv),
7208 struct netdev_nested_priv *priv)
7210 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7211 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7215 iter = &dev->adj_list.lower;
7219 ret = fn(now, priv);
7226 ldev = netdev_next_lower_dev(now, &iter);
7231 niter = &ldev->adj_list.lower;
7232 dev_stack[cur] = now;
7233 iter_stack[cur++] = iter;
7240 next = dev_stack[--cur];
7241 niter = iter_stack[cur];
7250 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7252 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7253 int (*fn)(struct net_device *dev,
7254 struct netdev_nested_priv *priv),
7255 struct netdev_nested_priv *priv)
7257 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7258 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7263 iter = &dev->adj_list.lower;
7267 ret = fn(now, priv);
7274 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7281 niter = &ldev->adj_list.lower;
7282 dev_stack[cur] = now;
7283 iter_stack[cur++] = iter;
7290 next = dev_stack[--cur];
7291 niter = iter_stack[cur];
7301 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7302 struct list_head **iter)
7304 struct netdev_adjacent *lower;
7306 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7307 if (&lower->list == &dev->adj_list.lower)
7310 *iter = &lower->list;
7314 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7316 static u8 __netdev_upper_depth(struct net_device *dev)
7318 struct net_device *udev;
7319 struct list_head *iter;
7323 for (iter = &dev->adj_list.upper,
7324 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7326 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7329 if (max_depth < udev->upper_level)
7330 max_depth = udev->upper_level;
7336 static u8 __netdev_lower_depth(struct net_device *dev)
7338 struct net_device *ldev;
7339 struct list_head *iter;
7343 for (iter = &dev->adj_list.lower,
7344 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7346 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7349 if (max_depth < ldev->lower_level)
7350 max_depth = ldev->lower_level;
7356 static int __netdev_update_upper_level(struct net_device *dev,
7357 struct netdev_nested_priv *__unused)
7359 dev->upper_level = __netdev_upper_depth(dev) + 1;
7363 #ifdef CONFIG_LOCKDEP
7364 static LIST_HEAD(net_unlink_list);
7366 static void net_unlink_todo(struct net_device *dev)
7368 if (list_empty(&dev->unlink_list))
7369 list_add_tail(&dev->unlink_list, &net_unlink_list);
7373 static int __netdev_update_lower_level(struct net_device *dev,
7374 struct netdev_nested_priv *priv)
7376 dev->lower_level = __netdev_lower_depth(dev) + 1;
7378 #ifdef CONFIG_LOCKDEP
7382 if (priv->flags & NESTED_SYNC_IMM)
7383 dev->nested_level = dev->lower_level - 1;
7384 if (priv->flags & NESTED_SYNC_TODO)
7385 net_unlink_todo(dev);
7390 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7391 int (*fn)(struct net_device *dev,
7392 struct netdev_nested_priv *priv),
7393 struct netdev_nested_priv *priv)
7395 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7396 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7400 iter = &dev->adj_list.lower;
7404 ret = fn(now, priv);
7411 ldev = netdev_next_lower_dev_rcu(now, &iter);
7416 niter = &ldev->adj_list.lower;
7417 dev_stack[cur] = now;
7418 iter_stack[cur++] = iter;
7425 next = dev_stack[--cur];
7426 niter = iter_stack[cur];
7435 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7438 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7439 * lower neighbour list, RCU
7443 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7444 * list. The caller must hold RCU read lock.
7446 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7448 struct netdev_adjacent *lower;
7450 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7451 struct netdev_adjacent, list);
7453 return lower->private;
7456 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7459 * netdev_master_upper_dev_get_rcu - Get master upper device
7462 * Find a master upper device and return pointer to it or NULL in case
7463 * it's not there. The caller must hold the RCU read lock.
7465 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7467 struct netdev_adjacent *upper;
7469 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7470 struct netdev_adjacent, list);
7471 if (upper && likely(upper->master))
7475 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7477 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7478 struct net_device *adj_dev,
7479 struct list_head *dev_list)
7481 char linkname[IFNAMSIZ+7];
7483 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7484 "upper_%s" : "lower_%s", adj_dev->name);
7485 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7488 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7490 struct list_head *dev_list)
7492 char linkname[IFNAMSIZ+7];
7494 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7495 "upper_%s" : "lower_%s", name);
7496 sysfs_remove_link(&(dev->dev.kobj), linkname);
7499 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7500 struct net_device *adj_dev,
7501 struct list_head *dev_list)
7503 return (dev_list == &dev->adj_list.upper ||
7504 dev_list == &dev->adj_list.lower) &&
7505 net_eq(dev_net(dev), dev_net(adj_dev));
7508 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7509 struct net_device *adj_dev,
7510 struct list_head *dev_list,
7511 void *private, bool master)
7513 struct netdev_adjacent *adj;
7516 adj = __netdev_find_adj(adj_dev, dev_list);
7520 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7521 dev->name, adj_dev->name, adj->ref_nr);
7526 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7531 adj->master = master;
7533 adj->private = private;
7534 adj->ignore = false;
7535 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7537 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7538 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7540 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7541 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7546 /* Ensure that master link is always the first item in list. */
7548 ret = sysfs_create_link(&(dev->dev.kobj),
7549 &(adj_dev->dev.kobj), "master");
7551 goto remove_symlinks;
7553 list_add_rcu(&adj->list, dev_list);
7555 list_add_tail_rcu(&adj->list, dev_list);
7561 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7562 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7564 netdev_put(adj_dev, &adj->dev_tracker);
7570 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7571 struct net_device *adj_dev,
7573 struct list_head *dev_list)
7575 struct netdev_adjacent *adj;
7577 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7578 dev->name, adj_dev->name, ref_nr);
7580 adj = __netdev_find_adj(adj_dev, dev_list);
7583 pr_err("Adjacency does not exist for device %s from %s\n",
7584 dev->name, adj_dev->name);
7589 if (adj->ref_nr > ref_nr) {
7590 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7591 dev->name, adj_dev->name, ref_nr,
7592 adj->ref_nr - ref_nr);
7593 adj->ref_nr -= ref_nr;
7598 sysfs_remove_link(&(dev->dev.kobj), "master");
7600 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7601 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7603 list_del_rcu(&adj->list);
7604 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7605 adj_dev->name, dev->name, adj_dev->name);
7606 netdev_put(adj_dev, &adj->dev_tracker);
7607 kfree_rcu(adj, rcu);
7610 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7611 struct net_device *upper_dev,
7612 struct list_head *up_list,
7613 struct list_head *down_list,
7614 void *private, bool master)
7618 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7623 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7626 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7633 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7634 struct net_device *upper_dev,
7636 struct list_head *up_list,
7637 struct list_head *down_list)
7639 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7640 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7643 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7644 struct net_device *upper_dev,
7645 void *private, bool master)
7647 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7648 &dev->adj_list.upper,
7649 &upper_dev->adj_list.lower,
7653 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7654 struct net_device *upper_dev)
7656 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7657 &dev->adj_list.upper,
7658 &upper_dev->adj_list.lower);
7661 static int __netdev_upper_dev_link(struct net_device *dev,
7662 struct net_device *upper_dev, bool master,
7663 void *upper_priv, void *upper_info,
7664 struct netdev_nested_priv *priv,
7665 struct netlink_ext_ack *extack)
7667 struct netdev_notifier_changeupper_info changeupper_info = {
7672 .upper_dev = upper_dev,
7675 .upper_info = upper_info,
7677 struct net_device *master_dev;
7682 if (dev == upper_dev)
7685 /* To prevent loops, check if dev is not upper device to upper_dev. */
7686 if (__netdev_has_upper_dev(upper_dev, dev))
7689 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7693 if (__netdev_has_upper_dev(dev, upper_dev))
7696 master_dev = __netdev_master_upper_dev_get(dev);
7698 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7701 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7702 &changeupper_info.info);
7703 ret = notifier_to_errno(ret);
7707 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7712 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7713 &changeupper_info.info);
7714 ret = notifier_to_errno(ret);
7718 __netdev_update_upper_level(dev, NULL);
7719 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7721 __netdev_update_lower_level(upper_dev, priv);
7722 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7728 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7734 * netdev_upper_dev_link - Add a link to the upper device
7736 * @upper_dev: new upper device
7737 * @extack: netlink extended ack
7739 * Adds a link to device which is upper to this one. The caller must hold
7740 * the RTNL lock. On a failure a negative errno code is returned.
7741 * On success the reference counts are adjusted and the function
7744 int netdev_upper_dev_link(struct net_device *dev,
7745 struct net_device *upper_dev,
7746 struct netlink_ext_ack *extack)
7748 struct netdev_nested_priv priv = {
7749 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7753 return __netdev_upper_dev_link(dev, upper_dev, false,
7754 NULL, NULL, &priv, extack);
7756 EXPORT_SYMBOL(netdev_upper_dev_link);
7759 * netdev_master_upper_dev_link - Add a master link to the upper device
7761 * @upper_dev: new upper device
7762 * @upper_priv: upper device private
7763 * @upper_info: upper info to be passed down via notifier
7764 * @extack: netlink extended ack
7766 * Adds a link to device which is upper to this one. In this case, only
7767 * one master upper device can be linked, although other non-master devices
7768 * might be linked as well. The caller must hold the RTNL lock.
7769 * On a failure a negative errno code is returned. On success the reference
7770 * counts are adjusted and the function returns zero.
7772 int netdev_master_upper_dev_link(struct net_device *dev,
7773 struct net_device *upper_dev,
7774 void *upper_priv, void *upper_info,
7775 struct netlink_ext_ack *extack)
7777 struct netdev_nested_priv priv = {
7778 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7782 return __netdev_upper_dev_link(dev, upper_dev, true,
7783 upper_priv, upper_info, &priv, extack);
7785 EXPORT_SYMBOL(netdev_master_upper_dev_link);
7787 static void __netdev_upper_dev_unlink(struct net_device *dev,
7788 struct net_device *upper_dev,
7789 struct netdev_nested_priv *priv)
7791 struct netdev_notifier_changeupper_info changeupper_info = {
7795 .upper_dev = upper_dev,
7801 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
7803 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7804 &changeupper_info.info);
7806 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7808 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7809 &changeupper_info.info);
7811 __netdev_update_upper_level(dev, NULL);
7812 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7814 __netdev_update_lower_level(upper_dev, priv);
7815 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7820 * netdev_upper_dev_unlink - Removes a link to upper device
7822 * @upper_dev: new upper device
7824 * Removes a link to device which is upper to this one. The caller must hold
7827 void netdev_upper_dev_unlink(struct net_device *dev,
7828 struct net_device *upper_dev)
7830 struct netdev_nested_priv priv = {
7831 .flags = NESTED_SYNC_TODO,
7835 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
7837 EXPORT_SYMBOL(netdev_upper_dev_unlink);
7839 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
7840 struct net_device *lower_dev,
7843 struct netdev_adjacent *adj;
7845 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
7849 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
7854 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
7855 struct net_device *lower_dev)
7857 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
7860 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
7861 struct net_device *lower_dev)
7863 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
7866 int netdev_adjacent_change_prepare(struct net_device *old_dev,
7867 struct net_device *new_dev,
7868 struct net_device *dev,
7869 struct netlink_ext_ack *extack)
7871 struct netdev_nested_priv priv = {
7880 if (old_dev && new_dev != old_dev)
7881 netdev_adjacent_dev_disable(dev, old_dev);
7882 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
7885 if (old_dev && new_dev != old_dev)
7886 netdev_adjacent_dev_enable(dev, old_dev);
7892 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
7894 void netdev_adjacent_change_commit(struct net_device *old_dev,
7895 struct net_device *new_dev,
7896 struct net_device *dev)
7898 struct netdev_nested_priv priv = {
7899 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7903 if (!new_dev || !old_dev)
7906 if (new_dev == old_dev)
7909 netdev_adjacent_dev_enable(dev, old_dev);
7910 __netdev_upper_dev_unlink(old_dev, dev, &priv);
7912 EXPORT_SYMBOL(netdev_adjacent_change_commit);
7914 void netdev_adjacent_change_abort(struct net_device *old_dev,
7915 struct net_device *new_dev,
7916 struct net_device *dev)
7918 struct netdev_nested_priv priv = {
7926 if (old_dev && new_dev != old_dev)
7927 netdev_adjacent_dev_enable(dev, old_dev);
7929 __netdev_upper_dev_unlink(new_dev, dev, &priv);
7931 EXPORT_SYMBOL(netdev_adjacent_change_abort);
7934 * netdev_bonding_info_change - Dispatch event about slave change
7936 * @bonding_info: info to dispatch
7938 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
7939 * The caller must hold the RTNL lock.
7941 void netdev_bonding_info_change(struct net_device *dev,
7942 struct netdev_bonding_info *bonding_info)
7944 struct netdev_notifier_bonding_info info = {
7948 memcpy(&info.bonding_info, bonding_info,
7949 sizeof(struct netdev_bonding_info));
7950 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
7953 EXPORT_SYMBOL(netdev_bonding_info_change);
7955 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
7956 struct netlink_ext_ack *extack)
7958 struct netdev_notifier_offload_xstats_info info = {
7960 .info.extack = extack,
7961 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
7966 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
7968 if (!dev->offload_xstats_l3)
7971 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
7972 NETDEV_OFFLOAD_XSTATS_DISABLE,
7974 err = notifier_to_errno(rc);
7981 kfree(dev->offload_xstats_l3);
7982 dev->offload_xstats_l3 = NULL;
7986 int netdev_offload_xstats_enable(struct net_device *dev,
7987 enum netdev_offload_xstats_type type,
7988 struct netlink_ext_ack *extack)
7992 if (netdev_offload_xstats_enabled(dev, type))
7996 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
7997 return netdev_offload_xstats_enable_l3(dev, extack);
8003 EXPORT_SYMBOL(netdev_offload_xstats_enable);
8005 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
8007 struct netdev_notifier_offload_xstats_info info = {
8009 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8012 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8014 kfree(dev->offload_xstats_l3);
8015 dev->offload_xstats_l3 = NULL;
8018 int netdev_offload_xstats_disable(struct net_device *dev,
8019 enum netdev_offload_xstats_type type)
8023 if (!netdev_offload_xstats_enabled(dev, type))
8027 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8028 netdev_offload_xstats_disable_l3(dev);
8035 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8037 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8039 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8042 static struct rtnl_hw_stats64 *
8043 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8044 enum netdev_offload_xstats_type type)
8047 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8048 return dev->offload_xstats_l3;
8055 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8056 enum netdev_offload_xstats_type type)
8060 return netdev_offload_xstats_get_ptr(dev, type);
8062 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8064 struct netdev_notifier_offload_xstats_ru {
8068 struct netdev_notifier_offload_xstats_rd {
8069 struct rtnl_hw_stats64 stats;
8073 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8074 const struct rtnl_hw_stats64 *src)
8076 dest->rx_packets += src->rx_packets;
8077 dest->tx_packets += src->tx_packets;
8078 dest->rx_bytes += src->rx_bytes;
8079 dest->tx_bytes += src->tx_bytes;
8080 dest->rx_errors += src->rx_errors;
8081 dest->tx_errors += src->tx_errors;
8082 dest->rx_dropped += src->rx_dropped;
8083 dest->tx_dropped += src->tx_dropped;
8084 dest->multicast += src->multicast;
8087 static int netdev_offload_xstats_get_used(struct net_device *dev,
8088 enum netdev_offload_xstats_type type,
8090 struct netlink_ext_ack *extack)
8092 struct netdev_notifier_offload_xstats_ru report_used = {};
8093 struct netdev_notifier_offload_xstats_info info = {
8095 .info.extack = extack,
8097 .report_used = &report_used,
8101 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8102 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8104 *p_used = report_used.used;
8105 return notifier_to_errno(rc);
8108 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8109 enum netdev_offload_xstats_type type,
8110 struct rtnl_hw_stats64 *p_stats,
8112 struct netlink_ext_ack *extack)
8114 struct netdev_notifier_offload_xstats_rd report_delta = {};
8115 struct netdev_notifier_offload_xstats_info info = {
8117 .info.extack = extack,
8119 .report_delta = &report_delta,
8121 struct rtnl_hw_stats64 *stats;
8124 stats = netdev_offload_xstats_get_ptr(dev, type);
8125 if (WARN_ON(!stats))
8128 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8131 /* Cache whatever we got, even if there was an error, otherwise the
8132 * successful stats retrievals would get lost.
8134 netdev_hw_stats64_add(stats, &report_delta.stats);
8138 *p_used = report_delta.used;
8140 return notifier_to_errno(rc);
8143 int netdev_offload_xstats_get(struct net_device *dev,
8144 enum netdev_offload_xstats_type type,
8145 struct rtnl_hw_stats64 *p_stats, bool *p_used,
8146 struct netlink_ext_ack *extack)
8151 return netdev_offload_xstats_get_stats(dev, type, p_stats,
8154 return netdev_offload_xstats_get_used(dev, type, p_used,
8157 EXPORT_SYMBOL(netdev_offload_xstats_get);
8160 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8161 const struct rtnl_hw_stats64 *stats)
8163 report_delta->used = true;
8164 netdev_hw_stats64_add(&report_delta->stats, stats);
8166 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8169 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8171 report_used->used = true;
8173 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8175 void netdev_offload_xstats_push_delta(struct net_device *dev,
8176 enum netdev_offload_xstats_type type,
8177 const struct rtnl_hw_stats64 *p_stats)
8179 struct rtnl_hw_stats64 *stats;
8183 stats = netdev_offload_xstats_get_ptr(dev, type);
8184 if (WARN_ON(!stats))
8187 netdev_hw_stats64_add(stats, p_stats);
8189 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8192 * netdev_get_xmit_slave - Get the xmit slave of master device
8195 * @all_slaves: assume all the slaves are active
8197 * The reference counters are not incremented so the caller must be
8198 * careful with locks. The caller must hold RCU lock.
8199 * %NULL is returned if no slave is found.
8202 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8203 struct sk_buff *skb,
8206 const struct net_device_ops *ops = dev->netdev_ops;
8208 if (!ops->ndo_get_xmit_slave)
8210 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8212 EXPORT_SYMBOL(netdev_get_xmit_slave);
8214 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8217 const struct net_device_ops *ops = dev->netdev_ops;
8219 if (!ops->ndo_sk_get_lower_dev)
8221 return ops->ndo_sk_get_lower_dev(dev, sk);
8225 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8229 * %NULL is returned if no lower device is found.
8232 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8235 struct net_device *lower;
8237 lower = netdev_sk_get_lower_dev(dev, sk);
8240 lower = netdev_sk_get_lower_dev(dev, sk);
8245 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8247 static void netdev_adjacent_add_links(struct net_device *dev)
8249 struct netdev_adjacent *iter;
8251 struct net *net = dev_net(dev);
8253 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8254 if (!net_eq(net, dev_net(iter->dev)))
8256 netdev_adjacent_sysfs_add(iter->dev, dev,
8257 &iter->dev->adj_list.lower);
8258 netdev_adjacent_sysfs_add(dev, iter->dev,
8259 &dev->adj_list.upper);
8262 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8263 if (!net_eq(net, dev_net(iter->dev)))
8265 netdev_adjacent_sysfs_add(iter->dev, dev,
8266 &iter->dev->adj_list.upper);
8267 netdev_adjacent_sysfs_add(dev, iter->dev,
8268 &dev->adj_list.lower);
8272 static void netdev_adjacent_del_links(struct net_device *dev)
8274 struct netdev_adjacent *iter;
8276 struct net *net = dev_net(dev);
8278 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8279 if (!net_eq(net, dev_net(iter->dev)))
8281 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8282 &iter->dev->adj_list.lower);
8283 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8284 &dev->adj_list.upper);
8287 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8288 if (!net_eq(net, dev_net(iter->dev)))
8290 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8291 &iter->dev->adj_list.upper);
8292 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8293 &dev->adj_list.lower);
8297 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8299 struct netdev_adjacent *iter;
8301 struct net *net = dev_net(dev);
8303 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8304 if (!net_eq(net, dev_net(iter->dev)))
8306 netdev_adjacent_sysfs_del(iter->dev, oldname,
8307 &iter->dev->adj_list.lower);
8308 netdev_adjacent_sysfs_add(iter->dev, dev,
8309 &iter->dev->adj_list.lower);
8312 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8313 if (!net_eq(net, dev_net(iter->dev)))
8315 netdev_adjacent_sysfs_del(iter->dev, oldname,
8316 &iter->dev->adj_list.upper);
8317 netdev_adjacent_sysfs_add(iter->dev, dev,
8318 &iter->dev->adj_list.upper);
8322 void *netdev_lower_dev_get_private(struct net_device *dev,
8323 struct net_device *lower_dev)
8325 struct netdev_adjacent *lower;
8329 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8333 return lower->private;
8335 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8339 * netdev_lower_state_changed - Dispatch event about lower device state change
8340 * @lower_dev: device
8341 * @lower_state_info: state to dispatch
8343 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8344 * The caller must hold the RTNL lock.
8346 void netdev_lower_state_changed(struct net_device *lower_dev,
8347 void *lower_state_info)
8349 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8350 .info.dev = lower_dev,
8354 changelowerstate_info.lower_state_info = lower_state_info;
8355 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8356 &changelowerstate_info.info);
8358 EXPORT_SYMBOL(netdev_lower_state_changed);
8360 static void dev_change_rx_flags(struct net_device *dev, int flags)
8362 const struct net_device_ops *ops = dev->netdev_ops;
8364 if (ops->ndo_change_rx_flags)
8365 ops->ndo_change_rx_flags(dev, flags);
8368 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8370 unsigned int old_flags = dev->flags;
8376 dev->flags |= IFF_PROMISC;
8377 dev->promiscuity += inc;
8378 if (dev->promiscuity == 0) {
8381 * If inc causes overflow, untouch promisc and return error.
8384 dev->flags &= ~IFF_PROMISC;
8386 dev->promiscuity -= inc;
8387 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8391 if (dev->flags != old_flags) {
8392 netdev_info(dev, "%s promiscuous mode\n",
8393 dev->flags & IFF_PROMISC ? "entered" : "left");
8394 if (audit_enabled) {
8395 current_uid_gid(&uid, &gid);
8396 audit_log(audit_context(), GFP_ATOMIC,
8397 AUDIT_ANOM_PROMISCUOUS,
8398 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8399 dev->name, (dev->flags & IFF_PROMISC),
8400 (old_flags & IFF_PROMISC),
8401 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8402 from_kuid(&init_user_ns, uid),
8403 from_kgid(&init_user_ns, gid),
8404 audit_get_sessionid(current));
8407 dev_change_rx_flags(dev, IFF_PROMISC);
8410 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8415 * dev_set_promiscuity - update promiscuity count on a device
8419 * Add or remove promiscuity from a device. While the count in the device
8420 * remains above zero the interface remains promiscuous. Once it hits zero
8421 * the device reverts back to normal filtering operation. A negative inc
8422 * value is used to drop promiscuity on the device.
8423 * Return 0 if successful or a negative errno code on error.
8425 int dev_set_promiscuity(struct net_device *dev, int inc)
8427 unsigned int old_flags = dev->flags;
8430 err = __dev_set_promiscuity(dev, inc, true);
8433 if (dev->flags != old_flags)
8434 dev_set_rx_mode(dev);
8437 EXPORT_SYMBOL(dev_set_promiscuity);
8439 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8441 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8445 dev->flags |= IFF_ALLMULTI;
8446 dev->allmulti += inc;
8447 if (dev->allmulti == 0) {
8450 * If inc causes overflow, untouch allmulti and return error.
8453 dev->flags &= ~IFF_ALLMULTI;
8455 dev->allmulti -= inc;
8456 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8460 if (dev->flags ^ old_flags) {
8461 netdev_info(dev, "%s allmulticast mode\n",
8462 dev->flags & IFF_ALLMULTI ? "entered" : "left");
8463 dev_change_rx_flags(dev, IFF_ALLMULTI);
8464 dev_set_rx_mode(dev);
8466 __dev_notify_flags(dev, old_flags,
8467 dev->gflags ^ old_gflags, 0, NULL);
8473 * dev_set_allmulti - update allmulti count on a device
8477 * Add or remove reception of all multicast frames to a device. While the
8478 * count in the device remains above zero the interface remains listening
8479 * to all interfaces. Once it hits zero the device reverts back to normal
8480 * filtering operation. A negative @inc value is used to drop the counter
8481 * when releasing a resource needing all multicasts.
8482 * Return 0 if successful or a negative errno code on error.
8485 int dev_set_allmulti(struct net_device *dev, int inc)
8487 return __dev_set_allmulti(dev, inc, true);
8489 EXPORT_SYMBOL(dev_set_allmulti);
8492 * Upload unicast and multicast address lists to device and
8493 * configure RX filtering. When the device doesn't support unicast
8494 * filtering it is put in promiscuous mode while unicast addresses
8497 void __dev_set_rx_mode(struct net_device *dev)
8499 const struct net_device_ops *ops = dev->netdev_ops;
8501 /* dev_open will call this function so the list will stay sane. */
8502 if (!(dev->flags&IFF_UP))
8505 if (!netif_device_present(dev))
8508 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8509 /* Unicast addresses changes may only happen under the rtnl,
8510 * therefore calling __dev_set_promiscuity here is safe.
8512 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8513 __dev_set_promiscuity(dev, 1, false);
8514 dev->uc_promisc = true;
8515 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8516 __dev_set_promiscuity(dev, -1, false);
8517 dev->uc_promisc = false;
8521 if (ops->ndo_set_rx_mode)
8522 ops->ndo_set_rx_mode(dev);
8525 void dev_set_rx_mode(struct net_device *dev)
8527 netif_addr_lock_bh(dev);
8528 __dev_set_rx_mode(dev);
8529 netif_addr_unlock_bh(dev);
8533 * dev_get_flags - get flags reported to userspace
8536 * Get the combination of flag bits exported through APIs to userspace.
8538 unsigned int dev_get_flags(const struct net_device *dev)
8542 flags = (dev->flags & ~(IFF_PROMISC |
8547 (dev->gflags & (IFF_PROMISC |
8550 if (netif_running(dev)) {
8551 if (netif_oper_up(dev))
8552 flags |= IFF_RUNNING;
8553 if (netif_carrier_ok(dev))
8554 flags |= IFF_LOWER_UP;
8555 if (netif_dormant(dev))
8556 flags |= IFF_DORMANT;
8561 EXPORT_SYMBOL(dev_get_flags);
8563 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8564 struct netlink_ext_ack *extack)
8566 unsigned int old_flags = dev->flags;
8572 * Set the flags on our device.
8575 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8576 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8578 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8582 * Load in the correct multicast list now the flags have changed.
8585 if ((old_flags ^ flags) & IFF_MULTICAST)
8586 dev_change_rx_flags(dev, IFF_MULTICAST);
8588 dev_set_rx_mode(dev);
8591 * Have we downed the interface. We handle IFF_UP ourselves
8592 * according to user attempts to set it, rather than blindly
8597 if ((old_flags ^ flags) & IFF_UP) {
8598 if (old_flags & IFF_UP)
8601 ret = __dev_open(dev, extack);
8604 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8605 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8606 unsigned int old_flags = dev->flags;
8608 dev->gflags ^= IFF_PROMISC;
8610 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8611 if (dev->flags != old_flags)
8612 dev_set_rx_mode(dev);
8615 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8616 * is important. Some (broken) drivers set IFF_PROMISC, when
8617 * IFF_ALLMULTI is requested not asking us and not reporting.
8619 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8620 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8622 dev->gflags ^= IFF_ALLMULTI;
8623 __dev_set_allmulti(dev, inc, false);
8629 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8630 unsigned int gchanges, u32 portid,
8631 const struct nlmsghdr *nlh)
8633 unsigned int changes = dev->flags ^ old_flags;
8636 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8638 if (changes & IFF_UP) {
8639 if (dev->flags & IFF_UP)
8640 call_netdevice_notifiers(NETDEV_UP, dev);
8642 call_netdevice_notifiers(NETDEV_DOWN, dev);
8645 if (dev->flags & IFF_UP &&
8646 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8647 struct netdev_notifier_change_info change_info = {
8651 .flags_changed = changes,
8654 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8659 * dev_change_flags - change device settings
8661 * @flags: device state flags
8662 * @extack: netlink extended ack
8664 * Change settings on device based state flags. The flags are
8665 * in the userspace exported format.
8667 int dev_change_flags(struct net_device *dev, unsigned int flags,
8668 struct netlink_ext_ack *extack)
8671 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8673 ret = __dev_change_flags(dev, flags, extack);
8677 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8678 __dev_notify_flags(dev, old_flags, changes, 0, NULL);
8681 EXPORT_SYMBOL(dev_change_flags);
8683 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8685 const struct net_device_ops *ops = dev->netdev_ops;
8687 if (ops->ndo_change_mtu)
8688 return ops->ndo_change_mtu(dev, new_mtu);
8690 /* Pairs with all the lockless reads of dev->mtu in the stack */
8691 WRITE_ONCE(dev->mtu, new_mtu);
8694 EXPORT_SYMBOL(__dev_set_mtu);
8696 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8697 struct netlink_ext_ack *extack)
8699 /* MTU must be positive, and in range */
8700 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8701 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8705 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8706 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8713 * dev_set_mtu_ext - Change maximum transfer unit
8715 * @new_mtu: new transfer unit
8716 * @extack: netlink extended ack
8718 * Change the maximum transfer size of the network device.
8720 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8721 struct netlink_ext_ack *extack)
8725 if (new_mtu == dev->mtu)
8728 err = dev_validate_mtu(dev, new_mtu, extack);
8732 if (!netif_device_present(dev))
8735 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8736 err = notifier_to_errno(err);
8740 orig_mtu = dev->mtu;
8741 err = __dev_set_mtu(dev, new_mtu);
8744 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8746 err = notifier_to_errno(err);
8748 /* setting mtu back and notifying everyone again,
8749 * so that they have a chance to revert changes.
8751 __dev_set_mtu(dev, orig_mtu);
8752 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8759 int dev_set_mtu(struct net_device *dev, int new_mtu)
8761 struct netlink_ext_ack extack;
8764 memset(&extack, 0, sizeof(extack));
8765 err = dev_set_mtu_ext(dev, new_mtu, &extack);
8766 if (err && extack._msg)
8767 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
8770 EXPORT_SYMBOL(dev_set_mtu);
8773 * dev_change_tx_queue_len - Change TX queue length of a netdevice
8775 * @new_len: new tx queue length
8777 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
8779 unsigned int orig_len = dev->tx_queue_len;
8782 if (new_len != (unsigned int)new_len)
8785 if (new_len != orig_len) {
8786 dev->tx_queue_len = new_len;
8787 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
8788 res = notifier_to_errno(res);
8791 res = dev_qdisc_change_tx_queue_len(dev);
8799 netdev_err(dev, "refused to change device tx_queue_len\n");
8800 dev->tx_queue_len = orig_len;
8805 * dev_set_group - Change group this device belongs to
8807 * @new_group: group this device should belong to
8809 void dev_set_group(struct net_device *dev, int new_group)
8811 dev->group = new_group;
8815 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
8817 * @addr: new address
8818 * @extack: netlink extended ack
8820 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
8821 struct netlink_ext_ack *extack)
8823 struct netdev_notifier_pre_changeaddr_info info = {
8825 .info.extack = extack,
8830 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
8831 return notifier_to_errno(rc);
8833 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
8836 * dev_set_mac_address - Change Media Access Control Address
8839 * @extack: netlink extended ack
8841 * Change the hardware (MAC) address of the device
8843 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
8844 struct netlink_ext_ack *extack)
8846 const struct net_device_ops *ops = dev->netdev_ops;
8849 if (!ops->ndo_set_mac_address)
8851 if (sa->sa_family != dev->type)
8853 if (!netif_device_present(dev))
8855 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
8858 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
8859 err = ops->ndo_set_mac_address(dev, sa);
8863 dev->addr_assign_type = NET_ADDR_SET;
8864 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
8865 add_device_randomness(dev->dev_addr, dev->addr_len);
8868 EXPORT_SYMBOL(dev_set_mac_address);
8870 static DECLARE_RWSEM(dev_addr_sem);
8872 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
8873 struct netlink_ext_ack *extack)
8877 down_write(&dev_addr_sem);
8878 ret = dev_set_mac_address(dev, sa, extack);
8879 up_write(&dev_addr_sem);
8882 EXPORT_SYMBOL(dev_set_mac_address_user);
8884 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
8886 size_t size = sizeof(sa->sa_data_min);
8887 struct net_device *dev;
8890 down_read(&dev_addr_sem);
8893 dev = dev_get_by_name_rcu(net, dev_name);
8899 memset(sa->sa_data, 0, size);
8901 memcpy(sa->sa_data, dev->dev_addr,
8902 min_t(size_t, size, dev->addr_len));
8903 sa->sa_family = dev->type;
8907 up_read(&dev_addr_sem);
8910 EXPORT_SYMBOL(dev_get_mac_address);
8913 * dev_change_carrier - Change device carrier
8915 * @new_carrier: new value
8917 * Change device carrier
8919 int dev_change_carrier(struct net_device *dev, bool new_carrier)
8921 const struct net_device_ops *ops = dev->netdev_ops;
8923 if (!ops->ndo_change_carrier)
8925 if (!netif_device_present(dev))
8927 return ops->ndo_change_carrier(dev, new_carrier);
8931 * dev_get_phys_port_id - Get device physical port ID
8935 * Get device physical port ID
8937 int dev_get_phys_port_id(struct net_device *dev,
8938 struct netdev_phys_item_id *ppid)
8940 const struct net_device_ops *ops = dev->netdev_ops;
8942 if (!ops->ndo_get_phys_port_id)
8944 return ops->ndo_get_phys_port_id(dev, ppid);
8948 * dev_get_phys_port_name - Get device physical port name
8951 * @len: limit of bytes to copy to name
8953 * Get device physical port name
8955 int dev_get_phys_port_name(struct net_device *dev,
8956 char *name, size_t len)
8958 const struct net_device_ops *ops = dev->netdev_ops;
8961 if (ops->ndo_get_phys_port_name) {
8962 err = ops->ndo_get_phys_port_name(dev, name, len);
8963 if (err != -EOPNOTSUPP)
8966 return devlink_compat_phys_port_name_get(dev, name, len);
8970 * dev_get_port_parent_id - Get the device's port parent identifier
8971 * @dev: network device
8972 * @ppid: pointer to a storage for the port's parent identifier
8973 * @recurse: allow/disallow recursion to lower devices
8975 * Get the devices's port parent identifier
8977 int dev_get_port_parent_id(struct net_device *dev,
8978 struct netdev_phys_item_id *ppid,
8981 const struct net_device_ops *ops = dev->netdev_ops;
8982 struct netdev_phys_item_id first = { };
8983 struct net_device *lower_dev;
8984 struct list_head *iter;
8987 if (ops->ndo_get_port_parent_id) {
8988 err = ops->ndo_get_port_parent_id(dev, ppid);
8989 if (err != -EOPNOTSUPP)
8993 err = devlink_compat_switch_id_get(dev, ppid);
8994 if (!recurse || err != -EOPNOTSUPP)
8997 netdev_for_each_lower_dev(dev, lower_dev, iter) {
8998 err = dev_get_port_parent_id(lower_dev, ppid, true);
9003 else if (memcmp(&first, ppid, sizeof(*ppid)))
9009 EXPORT_SYMBOL(dev_get_port_parent_id);
9012 * netdev_port_same_parent_id - Indicate if two network devices have
9013 * the same port parent identifier
9014 * @a: first network device
9015 * @b: second network device
9017 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9019 struct netdev_phys_item_id a_id = { };
9020 struct netdev_phys_item_id b_id = { };
9022 if (dev_get_port_parent_id(a, &a_id, true) ||
9023 dev_get_port_parent_id(b, &b_id, true))
9026 return netdev_phys_item_id_same(&a_id, &b_id);
9028 EXPORT_SYMBOL(netdev_port_same_parent_id);
9031 * dev_change_proto_down - set carrier according to proto_down.
9034 * @proto_down: new value
9036 int dev_change_proto_down(struct net_device *dev, bool proto_down)
9038 if (!(dev->priv_flags & IFF_CHANGE_PROTO_DOWN))
9040 if (!netif_device_present(dev))
9043 netif_carrier_off(dev);
9045 netif_carrier_on(dev);
9046 dev->proto_down = proto_down;
9051 * dev_change_proto_down_reason - proto down reason
9054 * @mask: proto down mask
9055 * @value: proto down value
9057 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
9063 dev->proto_down_reason = value;
9065 for_each_set_bit(b, &mask, 32) {
9066 if (value & (1 << b))
9067 dev->proto_down_reason |= BIT(b);
9069 dev->proto_down_reason &= ~BIT(b);
9074 struct bpf_xdp_link {
9075 struct bpf_link link;
9076 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9080 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9082 if (flags & XDP_FLAGS_HW_MODE)
9084 if (flags & XDP_FLAGS_DRV_MODE)
9085 return XDP_MODE_DRV;
9086 if (flags & XDP_FLAGS_SKB_MODE)
9087 return XDP_MODE_SKB;
9088 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9091 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9095 return generic_xdp_install;
9098 return dev->netdev_ops->ndo_bpf;
9104 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9105 enum bpf_xdp_mode mode)
9107 return dev->xdp_state[mode].link;
9110 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9111 enum bpf_xdp_mode mode)
9113 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9116 return link->link.prog;
9117 return dev->xdp_state[mode].prog;
9120 u8 dev_xdp_prog_count(struct net_device *dev)
9125 for (i = 0; i < __MAX_XDP_MODE; i++)
9126 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9130 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9132 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9134 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9136 return prog ? prog->aux->id : 0;
9139 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9140 struct bpf_xdp_link *link)
9142 dev->xdp_state[mode].link = link;
9143 dev->xdp_state[mode].prog = NULL;
9146 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9147 struct bpf_prog *prog)
9149 dev->xdp_state[mode].link = NULL;
9150 dev->xdp_state[mode].prog = prog;
9153 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9154 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9155 u32 flags, struct bpf_prog *prog)
9157 struct netdev_bpf xdp;
9160 memset(&xdp, 0, sizeof(xdp));
9161 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9162 xdp.extack = extack;
9166 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9167 * "moved" into driver), so they don't increment it on their own, but
9168 * they do decrement refcnt when program is detached or replaced.
9169 * Given net_device also owns link/prog, we need to bump refcnt here
9170 * to prevent drivers from underflowing it.
9174 err = bpf_op(dev, &xdp);
9181 if (mode != XDP_MODE_HW)
9182 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9187 static void dev_xdp_uninstall(struct net_device *dev)
9189 struct bpf_xdp_link *link;
9190 struct bpf_prog *prog;
9191 enum bpf_xdp_mode mode;
9196 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9197 prog = dev_xdp_prog(dev, mode);
9201 bpf_op = dev_xdp_bpf_op(dev, mode);
9205 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9207 /* auto-detach link from net device */
9208 link = dev_xdp_link(dev, mode);
9214 dev_xdp_set_link(dev, mode, NULL);
9218 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9219 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9220 struct bpf_prog *old_prog, u32 flags)
9222 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9223 struct bpf_prog *cur_prog;
9224 struct net_device *upper;
9225 struct list_head *iter;
9226 enum bpf_xdp_mode mode;
9232 /* either link or prog attachment, never both */
9233 if (link && (new_prog || old_prog))
9235 /* link supports only XDP mode flags */
9236 if (link && (flags & ~XDP_FLAGS_MODES)) {
9237 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9240 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9241 if (num_modes > 1) {
9242 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9245 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9246 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9247 NL_SET_ERR_MSG(extack,
9248 "More than one program loaded, unset mode is ambiguous");
9251 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9252 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9253 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9257 mode = dev_xdp_mode(dev, flags);
9258 /* can't replace attached link */
9259 if (dev_xdp_link(dev, mode)) {
9260 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9264 /* don't allow if an upper device already has a program */
9265 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9266 if (dev_xdp_prog_count(upper) > 0) {
9267 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9272 cur_prog = dev_xdp_prog(dev, mode);
9273 /* can't replace attached prog with link */
9274 if (link && cur_prog) {
9275 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9278 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9279 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9283 /* put effective new program into new_prog */
9285 new_prog = link->link.prog;
9288 bool offload = mode == XDP_MODE_HW;
9289 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9290 ? XDP_MODE_DRV : XDP_MODE_SKB;
9292 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9293 NL_SET_ERR_MSG(extack, "XDP program already attached");
9296 if (!offload && dev_xdp_prog(dev, other_mode)) {
9297 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9300 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9301 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9304 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9305 NL_SET_ERR_MSG(extack, "Program bound to different device");
9308 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9309 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9312 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9313 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9318 /* don't call drivers if the effective program didn't change */
9319 if (new_prog != cur_prog) {
9320 bpf_op = dev_xdp_bpf_op(dev, mode);
9322 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9326 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9332 dev_xdp_set_link(dev, mode, link);
9334 dev_xdp_set_prog(dev, mode, new_prog);
9336 bpf_prog_put(cur_prog);
9341 static int dev_xdp_attach_link(struct net_device *dev,
9342 struct netlink_ext_ack *extack,
9343 struct bpf_xdp_link *link)
9345 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9348 static int dev_xdp_detach_link(struct net_device *dev,
9349 struct netlink_ext_ack *extack,
9350 struct bpf_xdp_link *link)
9352 enum bpf_xdp_mode mode;
9357 mode = dev_xdp_mode(dev, link->flags);
9358 if (dev_xdp_link(dev, mode) != link)
9361 bpf_op = dev_xdp_bpf_op(dev, mode);
9362 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9363 dev_xdp_set_link(dev, mode, NULL);
9367 static void bpf_xdp_link_release(struct bpf_link *link)
9369 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9373 /* if racing with net_device's tear down, xdp_link->dev might be
9374 * already NULL, in which case link was already auto-detached
9376 if (xdp_link->dev) {
9377 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9378 xdp_link->dev = NULL;
9384 static int bpf_xdp_link_detach(struct bpf_link *link)
9386 bpf_xdp_link_release(link);
9390 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9392 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9397 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9398 struct seq_file *seq)
9400 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9405 ifindex = xdp_link->dev->ifindex;
9408 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9411 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9412 struct bpf_link_info *info)
9414 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9419 ifindex = xdp_link->dev->ifindex;
9422 info->xdp.ifindex = ifindex;
9426 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9427 struct bpf_prog *old_prog)
9429 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9430 enum bpf_xdp_mode mode;
9436 /* link might have been auto-released already, so fail */
9437 if (!xdp_link->dev) {
9442 if (old_prog && link->prog != old_prog) {
9446 old_prog = link->prog;
9447 if (old_prog->type != new_prog->type ||
9448 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9453 if (old_prog == new_prog) {
9454 /* no-op, don't disturb drivers */
9455 bpf_prog_put(new_prog);
9459 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9460 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9461 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9462 xdp_link->flags, new_prog);
9466 old_prog = xchg(&link->prog, new_prog);
9467 bpf_prog_put(old_prog);
9474 static const struct bpf_link_ops bpf_xdp_link_lops = {
9475 .release = bpf_xdp_link_release,
9476 .dealloc = bpf_xdp_link_dealloc,
9477 .detach = bpf_xdp_link_detach,
9478 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9479 .fill_link_info = bpf_xdp_link_fill_link_info,
9480 .update_prog = bpf_xdp_link_update,
9483 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9485 struct net *net = current->nsproxy->net_ns;
9486 struct bpf_link_primer link_primer;
9487 struct netlink_ext_ack extack = {};
9488 struct bpf_xdp_link *link;
9489 struct net_device *dev;
9493 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9499 link = kzalloc(sizeof(*link), GFP_USER);
9505 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9507 link->flags = attr->link_create.flags;
9509 err = bpf_link_prime(&link->link, &link_primer);
9515 err = dev_xdp_attach_link(dev, &extack, link);
9520 bpf_link_cleanup(&link_primer);
9521 trace_bpf_xdp_link_attach_failed(extack._msg);
9525 fd = bpf_link_settle(&link_primer);
9526 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9539 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9541 * @extack: netlink extended ack
9542 * @fd: new program fd or negative value to clear
9543 * @expected_fd: old program fd that userspace expects to replace or clear
9544 * @flags: xdp-related flags
9546 * Set or clear a bpf program for a device
9548 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9549 int fd, int expected_fd, u32 flags)
9551 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9552 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9558 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9559 mode != XDP_MODE_SKB);
9560 if (IS_ERR(new_prog))
9561 return PTR_ERR(new_prog);
9564 if (expected_fd >= 0) {
9565 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9566 mode != XDP_MODE_SKB);
9567 if (IS_ERR(old_prog)) {
9568 err = PTR_ERR(old_prog);
9574 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9577 if (err && new_prog)
9578 bpf_prog_put(new_prog);
9580 bpf_prog_put(old_prog);
9585 * dev_index_reserve() - allocate an ifindex in a namespace
9586 * @net: the applicable net namespace
9587 * @ifindex: requested ifindex, pass %0 to get one allocated
9589 * Allocate a ifindex for a new device. Caller must either use the ifindex
9590 * to store the device (via list_netdevice()) or call dev_index_release()
9591 * to give the index up.
9593 * Return: a suitable unique value for a new device interface number or -errno.
9595 static int dev_index_reserve(struct net *net, u32 ifindex)
9599 if (ifindex > INT_MAX) {
9600 DEBUG_NET_WARN_ON_ONCE(1);
9605 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
9606 xa_limit_31b, &net->ifindex, GFP_KERNEL);
9608 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
9615 static void dev_index_release(struct net *net, int ifindex)
9617 /* Expect only unused indexes, unlist_netdevice() removes the used */
9618 WARN_ON(xa_erase(&net->dev_by_index, ifindex));
9621 /* Delayed registration/unregisteration */
9622 LIST_HEAD(net_todo_list);
9623 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9625 static void net_set_todo(struct net_device *dev)
9627 list_add_tail(&dev->todo_list, &net_todo_list);
9628 atomic_inc(&dev_net(dev)->dev_unreg_count);
9631 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9632 struct net_device *upper, netdev_features_t features)
9634 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9635 netdev_features_t feature;
9638 for_each_netdev_feature(upper_disables, feature_bit) {
9639 feature = __NETIF_F_BIT(feature_bit);
9640 if (!(upper->wanted_features & feature)
9641 && (features & feature)) {
9642 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9643 &feature, upper->name);
9644 features &= ~feature;
9651 static void netdev_sync_lower_features(struct net_device *upper,
9652 struct net_device *lower, netdev_features_t features)
9654 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9655 netdev_features_t feature;
9658 for_each_netdev_feature(upper_disables, feature_bit) {
9659 feature = __NETIF_F_BIT(feature_bit);
9660 if (!(features & feature) && (lower->features & feature)) {
9661 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9662 &feature, lower->name);
9663 lower->wanted_features &= ~feature;
9664 __netdev_update_features(lower);
9666 if (unlikely(lower->features & feature))
9667 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9668 &feature, lower->name);
9670 netdev_features_change(lower);
9675 static netdev_features_t netdev_fix_features(struct net_device *dev,
9676 netdev_features_t features)
9678 /* Fix illegal checksum combinations */
9679 if ((features & NETIF_F_HW_CSUM) &&
9680 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9681 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9682 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9685 /* TSO requires that SG is present as well. */
9686 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9687 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9688 features &= ~NETIF_F_ALL_TSO;
9691 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9692 !(features & NETIF_F_IP_CSUM)) {
9693 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9694 features &= ~NETIF_F_TSO;
9695 features &= ~NETIF_F_TSO_ECN;
9698 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9699 !(features & NETIF_F_IPV6_CSUM)) {
9700 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9701 features &= ~NETIF_F_TSO6;
9704 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9705 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9706 features &= ~NETIF_F_TSO_MANGLEID;
9708 /* TSO ECN requires that TSO is present as well. */
9709 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9710 features &= ~NETIF_F_TSO_ECN;
9712 /* Software GSO depends on SG. */
9713 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9714 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9715 features &= ~NETIF_F_GSO;
9718 /* GSO partial features require GSO partial be set */
9719 if ((features & dev->gso_partial_features) &&
9720 !(features & NETIF_F_GSO_PARTIAL)) {
9722 "Dropping partially supported GSO features since no GSO partial.\n");
9723 features &= ~dev->gso_partial_features;
9726 if (!(features & NETIF_F_RXCSUM)) {
9727 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9728 * successfully merged by hardware must also have the
9729 * checksum verified by hardware. If the user does not
9730 * want to enable RXCSUM, logically, we should disable GRO_HW.
9732 if (features & NETIF_F_GRO_HW) {
9733 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9734 features &= ~NETIF_F_GRO_HW;
9738 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9739 if (features & NETIF_F_RXFCS) {
9740 if (features & NETIF_F_LRO) {
9741 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
9742 features &= ~NETIF_F_LRO;
9745 if (features & NETIF_F_GRO_HW) {
9746 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
9747 features &= ~NETIF_F_GRO_HW;
9751 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
9752 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
9753 features &= ~NETIF_F_LRO;
9756 if (features & NETIF_F_HW_TLS_TX) {
9757 bool ip_csum = (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) ==
9758 (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
9759 bool hw_csum = features & NETIF_F_HW_CSUM;
9761 if (!ip_csum && !hw_csum) {
9762 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
9763 features &= ~NETIF_F_HW_TLS_TX;
9767 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
9768 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
9769 features &= ~NETIF_F_HW_TLS_RX;
9775 int __netdev_update_features(struct net_device *dev)
9777 struct net_device *upper, *lower;
9778 netdev_features_t features;
9779 struct list_head *iter;
9784 features = netdev_get_wanted_features(dev);
9786 if (dev->netdev_ops->ndo_fix_features)
9787 features = dev->netdev_ops->ndo_fix_features(dev, features);
9789 /* driver might be less strict about feature dependencies */
9790 features = netdev_fix_features(dev, features);
9792 /* some features can't be enabled if they're off on an upper device */
9793 netdev_for_each_upper_dev_rcu(dev, upper, iter)
9794 features = netdev_sync_upper_features(dev, upper, features);
9796 if (dev->features == features)
9799 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
9800 &dev->features, &features);
9802 if (dev->netdev_ops->ndo_set_features)
9803 err = dev->netdev_ops->ndo_set_features(dev, features);
9807 if (unlikely(err < 0)) {
9809 "set_features() failed (%d); wanted %pNF, left %pNF\n",
9810 err, &features, &dev->features);
9811 /* return non-0 since some features might have changed and
9812 * it's better to fire a spurious notification than miss it
9818 /* some features must be disabled on lower devices when disabled
9819 * on an upper device (think: bonding master or bridge)
9821 netdev_for_each_lower_dev(dev, lower, iter)
9822 netdev_sync_lower_features(dev, lower, features);
9825 netdev_features_t diff = features ^ dev->features;
9827 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
9828 /* udp_tunnel_{get,drop}_rx_info both need
9829 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
9830 * device, or they won't do anything.
9831 * Thus we need to update dev->features
9832 * *before* calling udp_tunnel_get_rx_info,
9833 * but *after* calling udp_tunnel_drop_rx_info.
9835 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
9836 dev->features = features;
9837 udp_tunnel_get_rx_info(dev);
9839 udp_tunnel_drop_rx_info(dev);
9843 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
9844 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
9845 dev->features = features;
9846 err |= vlan_get_rx_ctag_filter_info(dev);
9848 vlan_drop_rx_ctag_filter_info(dev);
9852 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
9853 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
9854 dev->features = features;
9855 err |= vlan_get_rx_stag_filter_info(dev);
9857 vlan_drop_rx_stag_filter_info(dev);
9861 dev->features = features;
9864 return err < 0 ? 0 : 1;
9868 * netdev_update_features - recalculate device features
9869 * @dev: the device to check
9871 * Recalculate dev->features set and send notifications if it
9872 * has changed. Should be called after driver or hardware dependent
9873 * conditions might have changed that influence the features.
9875 void netdev_update_features(struct net_device *dev)
9877 if (__netdev_update_features(dev))
9878 netdev_features_change(dev);
9880 EXPORT_SYMBOL(netdev_update_features);
9883 * netdev_change_features - recalculate device features
9884 * @dev: the device to check
9886 * Recalculate dev->features set and send notifications even
9887 * if they have not changed. Should be called instead of
9888 * netdev_update_features() if also dev->vlan_features might
9889 * have changed to allow the changes to be propagated to stacked
9892 void netdev_change_features(struct net_device *dev)
9894 __netdev_update_features(dev);
9895 netdev_features_change(dev);
9897 EXPORT_SYMBOL(netdev_change_features);
9900 * netif_stacked_transfer_operstate - transfer operstate
9901 * @rootdev: the root or lower level device to transfer state from
9902 * @dev: the device to transfer operstate to
9904 * Transfer operational state from root to device. This is normally
9905 * called when a stacking relationship exists between the root
9906 * device and the device(a leaf device).
9908 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
9909 struct net_device *dev)
9911 if (rootdev->operstate == IF_OPER_DORMANT)
9912 netif_dormant_on(dev);
9914 netif_dormant_off(dev);
9916 if (rootdev->operstate == IF_OPER_TESTING)
9917 netif_testing_on(dev);
9919 netif_testing_off(dev);
9921 if (netif_carrier_ok(rootdev))
9922 netif_carrier_on(dev);
9924 netif_carrier_off(dev);
9926 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
9928 static int netif_alloc_rx_queues(struct net_device *dev)
9930 unsigned int i, count = dev->num_rx_queues;
9931 struct netdev_rx_queue *rx;
9932 size_t sz = count * sizeof(*rx);
9937 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
9943 for (i = 0; i < count; i++) {
9946 /* XDP RX-queue setup */
9947 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
9954 /* Rollback successful reg's and free other resources */
9956 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
9962 static void netif_free_rx_queues(struct net_device *dev)
9964 unsigned int i, count = dev->num_rx_queues;
9966 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
9970 for (i = 0; i < count; i++)
9971 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
9976 static void netdev_init_one_queue(struct net_device *dev,
9977 struct netdev_queue *queue, void *_unused)
9979 /* Initialize queue lock */
9980 spin_lock_init(&queue->_xmit_lock);
9981 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
9982 queue->xmit_lock_owner = -1;
9983 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
9986 dql_init(&queue->dql, HZ);
9990 static void netif_free_tx_queues(struct net_device *dev)
9995 static int netif_alloc_netdev_queues(struct net_device *dev)
9997 unsigned int count = dev->num_tx_queues;
9998 struct netdev_queue *tx;
9999 size_t sz = count * sizeof(*tx);
10001 if (count < 1 || count > 0xffff)
10004 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10010 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
10011 spin_lock_init(&dev->tx_global_lock);
10016 void netif_tx_stop_all_queues(struct net_device *dev)
10020 for (i = 0; i < dev->num_tx_queues; i++) {
10021 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
10023 netif_tx_stop_queue(txq);
10026 EXPORT_SYMBOL(netif_tx_stop_all_queues);
10029 * register_netdevice() - register a network device
10030 * @dev: device to register
10032 * Take a prepared network device structure and make it externally accessible.
10033 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10034 * Callers must hold the rtnl lock - you may want register_netdev()
10037 int register_netdevice(struct net_device *dev)
10040 struct net *net = dev_net(dev);
10042 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10043 NETDEV_FEATURE_COUNT);
10044 BUG_ON(dev_boot_phase);
10049 /* When net_device's are persistent, this will be fatal. */
10050 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10053 ret = ethtool_check_ops(dev->ethtool_ops);
10057 spin_lock_init(&dev->addr_list_lock);
10058 netdev_set_addr_lockdep_class(dev);
10060 ret = dev_get_valid_name(net, dev, dev->name);
10065 dev->name_node = netdev_name_node_head_alloc(dev);
10066 if (!dev->name_node)
10069 /* Init, if this function is available */
10070 if (dev->netdev_ops->ndo_init) {
10071 ret = dev->netdev_ops->ndo_init(dev);
10075 goto err_free_name;
10079 if (((dev->hw_features | dev->features) &
10080 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10081 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10082 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10083 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10088 ret = dev_index_reserve(net, dev->ifindex);
10091 dev->ifindex = ret;
10093 /* Transfer changeable features to wanted_features and enable
10094 * software offloads (GSO and GRO).
10096 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10097 dev->features |= NETIF_F_SOFT_FEATURES;
10099 if (dev->udp_tunnel_nic_info) {
10100 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10101 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10104 dev->wanted_features = dev->features & dev->hw_features;
10106 if (!(dev->flags & IFF_LOOPBACK))
10107 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10109 /* If IPv4 TCP segmentation offload is supported we should also
10110 * allow the device to enable segmenting the frame with the option
10111 * of ignoring a static IP ID value. This doesn't enable the
10112 * feature itself but allows the user to enable it later.
10114 if (dev->hw_features & NETIF_F_TSO)
10115 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10116 if (dev->vlan_features & NETIF_F_TSO)
10117 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10118 if (dev->mpls_features & NETIF_F_TSO)
10119 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10120 if (dev->hw_enc_features & NETIF_F_TSO)
10121 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10123 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10125 dev->vlan_features |= NETIF_F_HIGHDMA;
10127 /* Make NETIF_F_SG inheritable to tunnel devices.
10129 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10131 /* Make NETIF_F_SG inheritable to MPLS.
10133 dev->mpls_features |= NETIF_F_SG;
10135 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10136 ret = notifier_to_errno(ret);
10138 goto err_ifindex_release;
10140 ret = netdev_register_kobject(dev);
10141 write_lock(&dev_base_lock);
10142 dev->reg_state = ret ? NETREG_UNREGISTERED : NETREG_REGISTERED;
10143 write_unlock(&dev_base_lock);
10145 goto err_uninit_notify;
10147 __netdev_update_features(dev);
10150 * Default initial state at registry is that the
10151 * device is present.
10154 set_bit(__LINK_STATE_PRESENT, &dev->state);
10156 linkwatch_init_dev(dev);
10158 dev_init_scheduler(dev);
10160 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10161 list_netdevice(dev);
10163 add_device_randomness(dev->dev_addr, dev->addr_len);
10165 /* If the device has permanent device address, driver should
10166 * set dev_addr and also addr_assign_type should be set to
10167 * NET_ADDR_PERM (default value).
10169 if (dev->addr_assign_type == NET_ADDR_PERM)
10170 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10172 /* Notify protocols, that a new device appeared. */
10173 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10174 ret = notifier_to_errno(ret);
10176 /* Expect explicit free_netdev() on failure */
10177 dev->needs_free_netdev = false;
10178 unregister_netdevice_queue(dev, NULL);
10182 * Prevent userspace races by waiting until the network
10183 * device is fully setup before sending notifications.
10185 if (!dev->rtnl_link_ops ||
10186 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10187 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10193 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10194 err_ifindex_release:
10195 dev_index_release(net, dev->ifindex);
10197 if (dev->netdev_ops->ndo_uninit)
10198 dev->netdev_ops->ndo_uninit(dev);
10199 if (dev->priv_destructor)
10200 dev->priv_destructor(dev);
10202 netdev_name_node_free(dev->name_node);
10205 EXPORT_SYMBOL(register_netdevice);
10208 * init_dummy_netdev - init a dummy network device for NAPI
10209 * @dev: device to init
10211 * This takes a network device structure and initialize the minimum
10212 * amount of fields so it can be used to schedule NAPI polls without
10213 * registering a full blown interface. This is to be used by drivers
10214 * that need to tie several hardware interfaces to a single NAPI
10215 * poll scheduler due to HW limitations.
10217 int init_dummy_netdev(struct net_device *dev)
10219 /* Clear everything. Note we don't initialize spinlocks
10220 * are they aren't supposed to be taken by any of the
10221 * NAPI code and this dummy netdev is supposed to be
10222 * only ever used for NAPI polls
10224 memset(dev, 0, sizeof(struct net_device));
10226 /* make sure we BUG if trying to hit standard
10227 * register/unregister code path
10229 dev->reg_state = NETREG_DUMMY;
10231 /* NAPI wants this */
10232 INIT_LIST_HEAD(&dev->napi_list);
10234 /* a dummy interface is started by default */
10235 set_bit(__LINK_STATE_PRESENT, &dev->state);
10236 set_bit(__LINK_STATE_START, &dev->state);
10238 /* napi_busy_loop stats accounting wants this */
10239 dev_net_set(dev, &init_net);
10241 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10242 * because users of this 'device' dont need to change
10248 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10252 * register_netdev - register a network device
10253 * @dev: device to register
10255 * Take a completed network device structure and add it to the kernel
10256 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10257 * chain. 0 is returned on success. A negative errno code is returned
10258 * on a failure to set up the device, or if the name is a duplicate.
10260 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10261 * and expands the device name if you passed a format string to
10264 int register_netdev(struct net_device *dev)
10268 if (rtnl_lock_killable())
10270 err = register_netdevice(dev);
10274 EXPORT_SYMBOL(register_netdev);
10276 int netdev_refcnt_read(const struct net_device *dev)
10278 #ifdef CONFIG_PCPU_DEV_REFCNT
10281 for_each_possible_cpu(i)
10282 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10285 return refcount_read(&dev->dev_refcnt);
10288 EXPORT_SYMBOL(netdev_refcnt_read);
10290 int netdev_unregister_timeout_secs __read_mostly = 10;
10292 #define WAIT_REFS_MIN_MSECS 1
10293 #define WAIT_REFS_MAX_MSECS 250
10295 * netdev_wait_allrefs_any - wait until all references are gone.
10296 * @list: list of net_devices to wait on
10298 * This is called when unregistering network devices.
10300 * Any protocol or device that holds a reference should register
10301 * for netdevice notification, and cleanup and put back the
10302 * reference if they receive an UNREGISTER event.
10303 * We can get stuck here if buggy protocols don't correctly
10306 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10308 unsigned long rebroadcast_time, warning_time;
10309 struct net_device *dev;
10312 rebroadcast_time = warning_time = jiffies;
10314 list_for_each_entry(dev, list, todo_list)
10315 if (netdev_refcnt_read(dev) == 1)
10319 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10322 /* Rebroadcast unregister notification */
10323 list_for_each_entry(dev, list, todo_list)
10324 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10330 list_for_each_entry(dev, list, todo_list)
10331 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10333 /* We must not have linkwatch events
10334 * pending on unregister. If this
10335 * happens, we simply run the queue
10336 * unscheduled, resulting in a noop
10339 linkwatch_run_queue();
10345 rebroadcast_time = jiffies;
10350 wait = WAIT_REFS_MIN_MSECS;
10353 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10356 list_for_each_entry(dev, list, todo_list)
10357 if (netdev_refcnt_read(dev) == 1)
10360 if (time_after(jiffies, warning_time +
10361 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10362 list_for_each_entry(dev, list, todo_list) {
10363 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10364 dev->name, netdev_refcnt_read(dev));
10365 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10368 warning_time = jiffies;
10373 /* The sequence is:
10377 * register_netdevice(x1);
10378 * register_netdevice(x2);
10380 * unregister_netdevice(y1);
10381 * unregister_netdevice(y2);
10387 * We are invoked by rtnl_unlock().
10388 * This allows us to deal with problems:
10389 * 1) We can delete sysfs objects which invoke hotplug
10390 * without deadlocking with linkwatch via keventd.
10391 * 2) Since we run with the RTNL semaphore not held, we can sleep
10392 * safely in order to wait for the netdev refcnt to drop to zero.
10394 * We must not return until all unregister events added during
10395 * the interval the lock was held have been completed.
10397 void netdev_run_todo(void)
10399 struct net_device *dev, *tmp;
10400 struct list_head list;
10401 #ifdef CONFIG_LOCKDEP
10402 struct list_head unlink_list;
10404 list_replace_init(&net_unlink_list, &unlink_list);
10406 while (!list_empty(&unlink_list)) {
10407 struct net_device *dev = list_first_entry(&unlink_list,
10410 list_del_init(&dev->unlink_list);
10411 dev->nested_level = dev->lower_level - 1;
10415 /* Snapshot list, allow later requests */
10416 list_replace_init(&net_todo_list, &list);
10420 /* Wait for rcu callbacks to finish before next phase */
10421 if (!list_empty(&list))
10424 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10425 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10426 netdev_WARN(dev, "run_todo but not unregistering\n");
10427 list_del(&dev->todo_list);
10431 write_lock(&dev_base_lock);
10432 dev->reg_state = NETREG_UNREGISTERED;
10433 write_unlock(&dev_base_lock);
10434 linkwatch_forget_dev(dev);
10437 while (!list_empty(&list)) {
10438 dev = netdev_wait_allrefs_any(&list);
10439 list_del(&dev->todo_list);
10442 BUG_ON(netdev_refcnt_read(dev) != 1);
10443 BUG_ON(!list_empty(&dev->ptype_all));
10444 BUG_ON(!list_empty(&dev->ptype_specific));
10445 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10446 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10448 if (dev->priv_destructor)
10449 dev->priv_destructor(dev);
10450 if (dev->needs_free_netdev)
10453 if (atomic_dec_and_test(&dev_net(dev)->dev_unreg_count))
10454 wake_up(&netdev_unregistering_wq);
10456 /* Free network device */
10457 kobject_put(&dev->dev.kobj);
10461 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10462 * all the same fields in the same order as net_device_stats, with only
10463 * the type differing, but rtnl_link_stats64 may have additional fields
10464 * at the end for newer counters.
10466 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10467 const struct net_device_stats *netdev_stats)
10469 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10470 const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10471 u64 *dst = (u64 *)stats64;
10473 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10474 for (i = 0; i < n; i++)
10475 dst[i] = (unsigned long)atomic_long_read(&src[i]);
10476 /* zero out counters that only exist in rtnl_link_stats64 */
10477 memset((char *)stats64 + n * sizeof(u64), 0,
10478 sizeof(*stats64) - n * sizeof(u64));
10480 EXPORT_SYMBOL(netdev_stats_to_stats64);
10482 struct net_device_core_stats __percpu *netdev_core_stats_alloc(struct net_device *dev)
10484 struct net_device_core_stats __percpu *p;
10486 p = alloc_percpu_gfp(struct net_device_core_stats,
10487 GFP_ATOMIC | __GFP_NOWARN);
10489 if (p && cmpxchg(&dev->core_stats, NULL, p))
10492 /* This READ_ONCE() pairs with the cmpxchg() above */
10493 return READ_ONCE(dev->core_stats);
10495 EXPORT_SYMBOL(netdev_core_stats_alloc);
10498 * dev_get_stats - get network device statistics
10499 * @dev: device to get statistics from
10500 * @storage: place to store stats
10502 * Get network statistics from device. Return @storage.
10503 * The device driver may provide its own method by setting
10504 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10505 * otherwise the internal statistics structure is used.
10507 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10508 struct rtnl_link_stats64 *storage)
10510 const struct net_device_ops *ops = dev->netdev_ops;
10511 const struct net_device_core_stats __percpu *p;
10513 if (ops->ndo_get_stats64) {
10514 memset(storage, 0, sizeof(*storage));
10515 ops->ndo_get_stats64(dev, storage);
10516 } else if (ops->ndo_get_stats) {
10517 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10519 netdev_stats_to_stats64(storage, &dev->stats);
10522 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10523 p = READ_ONCE(dev->core_stats);
10525 const struct net_device_core_stats *core_stats;
10528 for_each_possible_cpu(i) {
10529 core_stats = per_cpu_ptr(p, i);
10530 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10531 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10532 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10533 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10538 EXPORT_SYMBOL(dev_get_stats);
10541 * dev_fetch_sw_netstats - get per-cpu network device statistics
10542 * @s: place to store stats
10543 * @netstats: per-cpu network stats to read from
10545 * Read per-cpu network statistics and populate the related fields in @s.
10547 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10548 const struct pcpu_sw_netstats __percpu *netstats)
10552 for_each_possible_cpu(cpu) {
10553 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10554 const struct pcpu_sw_netstats *stats;
10555 unsigned int start;
10557 stats = per_cpu_ptr(netstats, cpu);
10559 start = u64_stats_fetch_begin(&stats->syncp);
10560 rx_packets = u64_stats_read(&stats->rx_packets);
10561 rx_bytes = u64_stats_read(&stats->rx_bytes);
10562 tx_packets = u64_stats_read(&stats->tx_packets);
10563 tx_bytes = u64_stats_read(&stats->tx_bytes);
10564 } while (u64_stats_fetch_retry(&stats->syncp, start));
10566 s->rx_packets += rx_packets;
10567 s->rx_bytes += rx_bytes;
10568 s->tx_packets += tx_packets;
10569 s->tx_bytes += tx_bytes;
10572 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10575 * dev_get_tstats64 - ndo_get_stats64 implementation
10576 * @dev: device to get statistics from
10577 * @s: place to store stats
10579 * Populate @s from dev->stats and dev->tstats. Can be used as
10580 * ndo_get_stats64() callback.
10582 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10584 netdev_stats_to_stats64(s, &dev->stats);
10585 dev_fetch_sw_netstats(s, dev->tstats);
10587 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10589 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10591 struct netdev_queue *queue = dev_ingress_queue(dev);
10593 #ifdef CONFIG_NET_CLS_ACT
10596 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
10599 netdev_init_one_queue(dev, queue, NULL);
10600 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
10601 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
10602 rcu_assign_pointer(dev->ingress_queue, queue);
10607 static const struct ethtool_ops default_ethtool_ops;
10609 void netdev_set_default_ethtool_ops(struct net_device *dev,
10610 const struct ethtool_ops *ops)
10612 if (dev->ethtool_ops == &default_ethtool_ops)
10613 dev->ethtool_ops = ops;
10615 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
10618 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
10619 * @dev: netdev to enable the IRQ coalescing on
10621 * Sets a conservative default for SW IRQ coalescing. Users can use
10622 * sysfs attributes to override the default values.
10624 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
10626 WARN_ON(dev->reg_state == NETREG_REGISTERED);
10628 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
10629 dev->gro_flush_timeout = 20000;
10630 dev->napi_defer_hard_irqs = 1;
10633 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
10635 void netdev_freemem(struct net_device *dev)
10637 char *addr = (char *)dev - dev->padded;
10643 * alloc_netdev_mqs - allocate network device
10644 * @sizeof_priv: size of private data to allocate space for
10645 * @name: device name format string
10646 * @name_assign_type: origin of device name
10647 * @setup: callback to initialize device
10648 * @txqs: the number of TX subqueues to allocate
10649 * @rxqs: the number of RX subqueues to allocate
10651 * Allocates a struct net_device with private data area for driver use
10652 * and performs basic initialization. Also allocates subqueue structs
10653 * for each queue on the device.
10655 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
10656 unsigned char name_assign_type,
10657 void (*setup)(struct net_device *),
10658 unsigned int txqs, unsigned int rxqs)
10660 struct net_device *dev;
10661 unsigned int alloc_size;
10662 struct net_device *p;
10664 BUG_ON(strlen(name) >= sizeof(dev->name));
10667 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
10672 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
10676 alloc_size = sizeof(struct net_device);
10678 /* ensure 32-byte alignment of private area */
10679 alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
10680 alloc_size += sizeof_priv;
10682 /* ensure 32-byte alignment of whole construct */
10683 alloc_size += NETDEV_ALIGN - 1;
10685 p = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10689 dev = PTR_ALIGN(p, NETDEV_ALIGN);
10690 dev->padded = (char *)dev - (char *)p;
10692 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
10693 #ifdef CONFIG_PCPU_DEV_REFCNT
10694 dev->pcpu_refcnt = alloc_percpu(int);
10695 if (!dev->pcpu_refcnt)
10699 refcount_set(&dev->dev_refcnt, 1);
10702 if (dev_addr_init(dev))
10708 dev_net_set(dev, &init_net);
10710 dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
10711 dev->xdp_zc_max_segs = 1;
10712 dev->gso_max_segs = GSO_MAX_SEGS;
10713 dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
10714 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
10715 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
10716 dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
10717 dev->tso_max_segs = TSO_MAX_SEGS;
10718 dev->upper_level = 1;
10719 dev->lower_level = 1;
10720 #ifdef CONFIG_LOCKDEP
10721 dev->nested_level = 0;
10722 INIT_LIST_HEAD(&dev->unlink_list);
10725 INIT_LIST_HEAD(&dev->napi_list);
10726 INIT_LIST_HEAD(&dev->unreg_list);
10727 INIT_LIST_HEAD(&dev->close_list);
10728 INIT_LIST_HEAD(&dev->link_watch_list);
10729 INIT_LIST_HEAD(&dev->adj_list.upper);
10730 INIT_LIST_HEAD(&dev->adj_list.lower);
10731 INIT_LIST_HEAD(&dev->ptype_all);
10732 INIT_LIST_HEAD(&dev->ptype_specific);
10733 INIT_LIST_HEAD(&dev->net_notifier_list);
10734 #ifdef CONFIG_NET_SCHED
10735 hash_init(dev->qdisc_hash);
10737 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
10740 if (!dev->tx_queue_len) {
10741 dev->priv_flags |= IFF_NO_QUEUE;
10742 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
10745 dev->num_tx_queues = txqs;
10746 dev->real_num_tx_queues = txqs;
10747 if (netif_alloc_netdev_queues(dev))
10750 dev->num_rx_queues = rxqs;
10751 dev->real_num_rx_queues = rxqs;
10752 if (netif_alloc_rx_queues(dev))
10755 strcpy(dev->name, name);
10756 dev->name_assign_type = name_assign_type;
10757 dev->group = INIT_NETDEV_GROUP;
10758 if (!dev->ethtool_ops)
10759 dev->ethtool_ops = &default_ethtool_ops;
10761 nf_hook_netdev_init(dev);
10770 #ifdef CONFIG_PCPU_DEV_REFCNT
10771 free_percpu(dev->pcpu_refcnt);
10774 netdev_freemem(dev);
10777 EXPORT_SYMBOL(alloc_netdev_mqs);
10780 * free_netdev - free network device
10783 * This function does the last stage of destroying an allocated device
10784 * interface. The reference to the device object is released. If this
10785 * is the last reference then it will be freed.Must be called in process
10788 void free_netdev(struct net_device *dev)
10790 struct napi_struct *p, *n;
10794 /* When called immediately after register_netdevice() failed the unwind
10795 * handling may still be dismantling the device. Handle that case by
10796 * deferring the free.
10798 if (dev->reg_state == NETREG_UNREGISTERING) {
10800 dev->needs_free_netdev = true;
10804 netif_free_tx_queues(dev);
10805 netif_free_rx_queues(dev);
10807 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
10809 /* Flush device addresses */
10810 dev_addr_flush(dev);
10812 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
10815 ref_tracker_dir_exit(&dev->refcnt_tracker);
10816 #ifdef CONFIG_PCPU_DEV_REFCNT
10817 free_percpu(dev->pcpu_refcnt);
10818 dev->pcpu_refcnt = NULL;
10820 free_percpu(dev->core_stats);
10821 dev->core_stats = NULL;
10822 free_percpu(dev->xdp_bulkq);
10823 dev->xdp_bulkq = NULL;
10825 /* Compatibility with error handling in drivers */
10826 if (dev->reg_state == NETREG_UNINITIALIZED) {
10827 netdev_freemem(dev);
10831 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
10832 dev->reg_state = NETREG_RELEASED;
10834 /* will free via device release */
10835 put_device(&dev->dev);
10837 EXPORT_SYMBOL(free_netdev);
10840 * synchronize_net - Synchronize with packet receive processing
10842 * Wait for packets currently being received to be done.
10843 * Does not block later packets from starting.
10845 void synchronize_net(void)
10848 if (rtnl_is_locked())
10849 synchronize_rcu_expedited();
10853 EXPORT_SYMBOL(synchronize_net);
10856 * unregister_netdevice_queue - remove device from the kernel
10860 * This function shuts down a device interface and removes it
10861 * from the kernel tables.
10862 * If head not NULL, device is queued to be unregistered later.
10864 * Callers must hold the rtnl semaphore. You may want
10865 * unregister_netdev() instead of this.
10868 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
10873 list_move_tail(&dev->unreg_list, head);
10877 list_add(&dev->unreg_list, &single);
10878 unregister_netdevice_many(&single);
10881 EXPORT_SYMBOL(unregister_netdevice_queue);
10883 void unregister_netdevice_many_notify(struct list_head *head,
10884 u32 portid, const struct nlmsghdr *nlh)
10886 struct net_device *dev, *tmp;
10887 LIST_HEAD(close_head);
10889 BUG_ON(dev_boot_phase);
10892 if (list_empty(head))
10895 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
10896 /* Some devices call without registering
10897 * for initialization unwind. Remove those
10898 * devices and proceed with the remaining.
10900 if (dev->reg_state == NETREG_UNINITIALIZED) {
10901 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
10905 list_del(&dev->unreg_list);
10908 dev->dismantle = true;
10909 BUG_ON(dev->reg_state != NETREG_REGISTERED);
10912 /* If device is running, close it first. */
10913 list_for_each_entry(dev, head, unreg_list)
10914 list_add_tail(&dev->close_list, &close_head);
10915 dev_close_many(&close_head, true);
10917 list_for_each_entry(dev, head, unreg_list) {
10918 /* And unlink it from device chain. */
10919 write_lock(&dev_base_lock);
10920 unlist_netdevice(dev, false);
10921 dev->reg_state = NETREG_UNREGISTERING;
10922 write_unlock(&dev_base_lock);
10924 flush_all_backlogs();
10928 list_for_each_entry(dev, head, unreg_list) {
10929 struct sk_buff *skb = NULL;
10931 /* Shutdown queueing discipline. */
10933 dev_tcx_uninstall(dev);
10934 dev_xdp_uninstall(dev);
10935 bpf_dev_bound_netdev_unregister(dev);
10937 netdev_offload_xstats_disable_all(dev);
10939 /* Notify protocols, that we are about to destroy
10940 * this device. They should clean all the things.
10942 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10944 if (!dev->rtnl_link_ops ||
10945 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10946 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
10947 GFP_KERNEL, NULL, 0,
10951 * Flush the unicast and multicast chains
10956 netdev_name_node_alt_flush(dev);
10957 netdev_name_node_free(dev->name_node);
10959 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10961 if (dev->netdev_ops->ndo_uninit)
10962 dev->netdev_ops->ndo_uninit(dev);
10965 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
10967 /* Notifier chain MUST detach us all upper devices. */
10968 WARN_ON(netdev_has_any_upper_dev(dev));
10969 WARN_ON(netdev_has_any_lower_dev(dev));
10971 /* Remove entries from kobject tree */
10972 netdev_unregister_kobject(dev);
10974 /* Remove XPS queueing entries */
10975 netif_reset_xps_queues_gt(dev, 0);
10981 list_for_each_entry(dev, head, unreg_list) {
10982 netdev_put(dev, &dev->dev_registered_tracker);
10990 * unregister_netdevice_many - unregister many devices
10991 * @head: list of devices
10993 * Note: As most callers use a stack allocated list_head,
10994 * we force a list_del() to make sure stack wont be corrupted later.
10996 void unregister_netdevice_many(struct list_head *head)
10998 unregister_netdevice_many_notify(head, 0, NULL);
11000 EXPORT_SYMBOL(unregister_netdevice_many);
11003 * unregister_netdev - remove device from the kernel
11006 * This function shuts down a device interface and removes it
11007 * from the kernel tables.
11009 * This is just a wrapper for unregister_netdevice that takes
11010 * the rtnl semaphore. In general you want to use this and not
11011 * unregister_netdevice.
11013 void unregister_netdev(struct net_device *dev)
11016 unregister_netdevice(dev);
11019 EXPORT_SYMBOL(unregister_netdev);
11022 * __dev_change_net_namespace - move device to different nethost namespace
11024 * @net: network namespace
11025 * @pat: If not NULL name pattern to try if the current device name
11026 * is already taken in the destination network namespace.
11027 * @new_ifindex: If not zero, specifies device index in the target
11030 * This function shuts down a device interface and moves it
11031 * to a new network namespace. On success 0 is returned, on
11032 * a failure a netagive errno code is returned.
11034 * Callers must hold the rtnl semaphore.
11037 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
11038 const char *pat, int new_ifindex)
11040 struct net *net_old = dev_net(dev);
11045 /* Don't allow namespace local devices to be moved. */
11047 if (dev->features & NETIF_F_NETNS_LOCAL)
11050 /* Ensure the device has been registrered */
11051 if (dev->reg_state != NETREG_REGISTERED)
11054 /* Get out if there is nothing todo */
11056 if (net_eq(net_old, net))
11059 /* Pick the destination device name, and ensure
11060 * we can use it in the destination network namespace.
11063 if (netdev_name_in_use(net, dev->name)) {
11064 /* We get here if we can't use the current device name */
11067 err = dev_get_valid_name(net, dev, pat);
11072 /* Check that new_ifindex isn't used yet. */
11074 err = dev_index_reserve(net, new_ifindex);
11078 /* If there is an ifindex conflict assign a new one */
11079 err = dev_index_reserve(net, dev->ifindex);
11081 err = dev_index_reserve(net, 0);
11088 * And now a mini version of register_netdevice unregister_netdevice.
11091 /* If device is running close it first. */
11094 /* And unlink it from device chain */
11095 unlist_netdevice(dev, true);
11099 /* Shutdown queueing discipline. */
11102 /* Notify protocols, that we are about to destroy
11103 * this device. They should clean all the things.
11105 * Note that dev->reg_state stays at NETREG_REGISTERED.
11106 * This is wanted because this way 8021q and macvlan know
11107 * the device is just moving and can keep their slaves up.
11109 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11112 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11114 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11118 * Flush the unicast and multicast chains
11123 /* Send a netdev-removed uevent to the old namespace */
11124 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11125 netdev_adjacent_del_links(dev);
11127 /* Move per-net netdevice notifiers that are following the netdevice */
11128 move_netdevice_notifiers_dev_net(dev, net);
11130 /* Actually switch the network namespace */
11131 dev_net_set(dev, net);
11132 dev->ifindex = new_ifindex;
11134 /* Send a netdev-add uevent to the new namespace */
11135 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11136 netdev_adjacent_add_links(dev);
11138 /* Fixup kobjects */
11139 err = device_rename(&dev->dev, dev->name);
11142 /* Adapt owner in case owning user namespace of target network
11143 * namespace is different from the original one.
11145 err = netdev_change_owner(dev, net_old, net);
11148 /* Add the device back in the hashes */
11149 list_netdevice(dev);
11151 /* Notify protocols, that a new device appeared. */
11152 call_netdevice_notifiers(NETDEV_REGISTER, dev);
11155 * Prevent userspace races by waiting until the network
11156 * device is fully setup before sending notifications.
11158 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11165 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11167 static int dev_cpu_dead(unsigned int oldcpu)
11169 struct sk_buff **list_skb;
11170 struct sk_buff *skb;
11172 struct softnet_data *sd, *oldsd, *remsd = NULL;
11174 local_irq_disable();
11175 cpu = smp_processor_id();
11176 sd = &per_cpu(softnet_data, cpu);
11177 oldsd = &per_cpu(softnet_data, oldcpu);
11179 /* Find end of our completion_queue. */
11180 list_skb = &sd->completion_queue;
11182 list_skb = &(*list_skb)->next;
11183 /* Append completion queue from offline CPU. */
11184 *list_skb = oldsd->completion_queue;
11185 oldsd->completion_queue = NULL;
11187 /* Append output queue from offline CPU. */
11188 if (oldsd->output_queue) {
11189 *sd->output_queue_tailp = oldsd->output_queue;
11190 sd->output_queue_tailp = oldsd->output_queue_tailp;
11191 oldsd->output_queue = NULL;
11192 oldsd->output_queue_tailp = &oldsd->output_queue;
11194 /* Append NAPI poll list from offline CPU, with one exception :
11195 * process_backlog() must be called by cpu owning percpu backlog.
11196 * We properly handle process_queue & input_pkt_queue later.
11198 while (!list_empty(&oldsd->poll_list)) {
11199 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11200 struct napi_struct,
11203 list_del_init(&napi->poll_list);
11204 if (napi->poll == process_backlog)
11207 ____napi_schedule(sd, napi);
11210 raise_softirq_irqoff(NET_TX_SOFTIRQ);
11211 local_irq_enable();
11214 remsd = oldsd->rps_ipi_list;
11215 oldsd->rps_ipi_list = NULL;
11217 /* send out pending IPI's on offline CPU */
11218 net_rps_send_ipi(remsd);
11220 /* Process offline CPU's input_pkt_queue */
11221 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11223 input_queue_head_incr(oldsd);
11225 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11227 input_queue_head_incr(oldsd);
11234 * netdev_increment_features - increment feature set by one
11235 * @all: current feature set
11236 * @one: new feature set
11237 * @mask: mask feature set
11239 * Computes a new feature set after adding a device with feature set
11240 * @one to the master device with current feature set @all. Will not
11241 * enable anything that is off in @mask. Returns the new feature set.
11243 netdev_features_t netdev_increment_features(netdev_features_t all,
11244 netdev_features_t one, netdev_features_t mask)
11246 if (mask & NETIF_F_HW_CSUM)
11247 mask |= NETIF_F_CSUM_MASK;
11248 mask |= NETIF_F_VLAN_CHALLENGED;
11250 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11251 all &= one | ~NETIF_F_ALL_FOR_ALL;
11253 /* If one device supports hw checksumming, set for all. */
11254 if (all & NETIF_F_HW_CSUM)
11255 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11259 EXPORT_SYMBOL(netdev_increment_features);
11261 static struct hlist_head * __net_init netdev_create_hash(void)
11264 struct hlist_head *hash;
11266 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11268 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11269 INIT_HLIST_HEAD(&hash[i]);
11274 /* Initialize per network namespace state */
11275 static int __net_init netdev_init(struct net *net)
11277 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11278 8 * sizeof_field(struct napi_struct, gro_bitmask));
11280 INIT_LIST_HEAD(&net->dev_base_head);
11282 net->dev_name_head = netdev_create_hash();
11283 if (net->dev_name_head == NULL)
11286 net->dev_index_head = netdev_create_hash();
11287 if (net->dev_index_head == NULL)
11290 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
11292 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11297 kfree(net->dev_name_head);
11303 * netdev_drivername - network driver for the device
11304 * @dev: network device
11306 * Determine network driver for device.
11308 const char *netdev_drivername(const struct net_device *dev)
11310 const struct device_driver *driver;
11311 const struct device *parent;
11312 const char *empty = "";
11314 parent = dev->dev.parent;
11318 driver = parent->driver;
11319 if (driver && driver->name)
11320 return driver->name;
11324 static void __netdev_printk(const char *level, const struct net_device *dev,
11325 struct va_format *vaf)
11327 if (dev && dev->dev.parent) {
11328 dev_printk_emit(level[1] - '0',
11331 dev_driver_string(dev->dev.parent),
11332 dev_name(dev->dev.parent),
11333 netdev_name(dev), netdev_reg_state(dev),
11336 printk("%s%s%s: %pV",
11337 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11339 printk("%s(NULL net_device): %pV", level, vaf);
11343 void netdev_printk(const char *level, const struct net_device *dev,
11344 const char *format, ...)
11346 struct va_format vaf;
11349 va_start(args, format);
11354 __netdev_printk(level, dev, &vaf);
11358 EXPORT_SYMBOL(netdev_printk);
11360 #define define_netdev_printk_level(func, level) \
11361 void func(const struct net_device *dev, const char *fmt, ...) \
11363 struct va_format vaf; \
11366 va_start(args, fmt); \
11371 __netdev_printk(level, dev, &vaf); \
11375 EXPORT_SYMBOL(func);
11377 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11378 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11379 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11380 define_netdev_printk_level(netdev_err, KERN_ERR);
11381 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11382 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11383 define_netdev_printk_level(netdev_info, KERN_INFO);
11385 static void __net_exit netdev_exit(struct net *net)
11387 kfree(net->dev_name_head);
11388 kfree(net->dev_index_head);
11389 xa_destroy(&net->dev_by_index);
11390 if (net != &init_net)
11391 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11394 static struct pernet_operations __net_initdata netdev_net_ops = {
11395 .init = netdev_init,
11396 .exit = netdev_exit,
11399 static void __net_exit default_device_exit_net(struct net *net)
11401 struct net_device *dev, *aux;
11403 * Push all migratable network devices back to the
11404 * initial network namespace
11407 for_each_netdev_safe(net, dev, aux) {
11409 char fb_name[IFNAMSIZ];
11411 /* Ignore unmoveable devices (i.e. loopback) */
11412 if (dev->features & NETIF_F_NETNS_LOCAL)
11415 /* Leave virtual devices for the generic cleanup */
11416 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11419 /* Push remaining network devices to init_net */
11420 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11421 if (netdev_name_in_use(&init_net, fb_name))
11422 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11423 err = dev_change_net_namespace(dev, &init_net, fb_name);
11425 pr_emerg("%s: failed to move %s to init_net: %d\n",
11426 __func__, dev->name, err);
11432 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11434 /* At exit all network devices most be removed from a network
11435 * namespace. Do this in the reverse order of registration.
11436 * Do this across as many network namespaces as possible to
11437 * improve batching efficiency.
11439 struct net_device *dev;
11441 LIST_HEAD(dev_kill_list);
11444 list_for_each_entry(net, net_list, exit_list) {
11445 default_device_exit_net(net);
11449 list_for_each_entry(net, net_list, exit_list) {
11450 for_each_netdev_reverse(net, dev) {
11451 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11452 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11454 unregister_netdevice_queue(dev, &dev_kill_list);
11457 unregister_netdevice_many(&dev_kill_list);
11461 static struct pernet_operations __net_initdata default_device_ops = {
11462 .exit_batch = default_device_exit_batch,
11466 * Initialize the DEV module. At boot time this walks the device list and
11467 * unhooks any devices that fail to initialise (normally hardware not
11468 * present) and leaves us with a valid list of present and active devices.
11473 * This is called single threaded during boot, so no need
11474 * to take the rtnl semaphore.
11476 static int __init net_dev_init(void)
11478 int i, rc = -ENOMEM;
11480 BUG_ON(!dev_boot_phase);
11482 if (dev_proc_init())
11485 if (netdev_kobject_init())
11488 INIT_LIST_HEAD(&ptype_all);
11489 for (i = 0; i < PTYPE_HASH_SIZE; i++)
11490 INIT_LIST_HEAD(&ptype_base[i]);
11492 if (register_pernet_subsys(&netdev_net_ops))
11496 * Initialise the packet receive queues.
11499 for_each_possible_cpu(i) {
11500 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
11501 struct softnet_data *sd = &per_cpu(softnet_data, i);
11503 INIT_WORK(flush, flush_backlog);
11505 skb_queue_head_init(&sd->input_pkt_queue);
11506 skb_queue_head_init(&sd->process_queue);
11507 #ifdef CONFIG_XFRM_OFFLOAD
11508 skb_queue_head_init(&sd->xfrm_backlog);
11510 INIT_LIST_HEAD(&sd->poll_list);
11511 sd->output_queue_tailp = &sd->output_queue;
11513 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
11516 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
11517 spin_lock_init(&sd->defer_lock);
11519 init_gro_hash(&sd->backlog);
11520 sd->backlog.poll = process_backlog;
11521 sd->backlog.weight = weight_p;
11524 dev_boot_phase = 0;
11526 /* The loopback device is special if any other network devices
11527 * is present in a network namespace the loopback device must
11528 * be present. Since we now dynamically allocate and free the
11529 * loopback device ensure this invariant is maintained by
11530 * keeping the loopback device as the first device on the
11531 * list of network devices. Ensuring the loopback devices
11532 * is the first device that appears and the last network device
11535 if (register_pernet_device(&loopback_net_ops))
11538 if (register_pernet_device(&default_device_ops))
11541 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
11542 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
11544 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
11545 NULL, dev_cpu_dead);
11552 subsys_initcall(net_dev_init);