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
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/isolation.h>
81 #include <linux/sched/mm.h>
82 #include <linux/smpboot.h>
83 #include <linux/mutex.h>
84 #include <linux/rwsem.h>
85 #include <linux/string.h>
87 #include <linux/socket.h>
88 #include <linux/sockios.h>
89 #include <linux/errno.h>
90 #include <linux/interrupt.h>
91 #include <linux/if_ether.h>
92 #include <linux/netdevice.h>
93 #include <linux/etherdevice.h>
94 #include <linux/ethtool.h>
95 #include <linux/skbuff.h>
96 #include <linux/kthread.h>
97 #include <linux/bpf.h>
98 #include <linux/bpf_trace.h>
99 #include <net/net_namespace.h>
100 #include <net/sock.h>
101 #include <net/busy_poll.h>
102 #include <linux/rtnetlink.h>
103 #include <linux/stat.h>
106 #include <net/dst_metadata.h>
108 #include <net/pkt_sched.h>
109 #include <net/pkt_cls.h>
110 #include <net/checksum.h>
111 #include <net/xfrm.h>
113 #include <linux/highmem.h>
114 #include <linux/init.h>
115 #include <linux/module.h>
116 #include <linux/netpoll.h>
117 #include <linux/rcupdate.h>
118 #include <linux/delay.h>
119 #include <net/iw_handler.h>
120 #include <asm/current.h>
121 #include <linux/audit.h>
122 #include <linux/dmaengine.h>
123 #include <linux/err.h>
124 #include <linux/ctype.h>
125 #include <linux/if_arp.h>
126 #include <linux/if_vlan.h>
127 #include <linux/ip.h>
129 #include <net/mpls.h>
130 #include <linux/ipv6.h>
131 #include <linux/in.h>
132 #include <linux/jhash.h>
133 #include <linux/random.h>
134 #include <trace/events/napi.h>
135 #include <trace/events/net.h>
136 #include <trace/events/skb.h>
137 #include <trace/events/qdisc.h>
138 #include <trace/events/xdp.h>
139 #include <linux/inetdevice.h>
140 #include <linux/cpu_rmap.h>
141 #include <linux/static_key.h>
142 #include <linux/hashtable.h>
143 #include <linux/vmalloc.h>
144 #include <linux/if_macvlan.h>
145 #include <linux/errqueue.h>
146 #include <linux/hrtimer.h>
147 #include <linux/netfilter_netdev.h>
148 #include <linux/crash_dump.h>
149 #include <linux/sctp.h>
150 #include <net/udp_tunnel.h>
151 #include <linux/net_namespace.h>
152 #include <linux/indirect_call_wrapper.h>
153 #include <net/devlink.h>
154 #include <linux/pm_runtime.h>
155 #include <linux/prandom.h>
156 #include <linux/once_lite.h>
157 #include <net/netdev_rx_queue.h>
158 #include <net/page_pool/types.h>
159 #include <net/page_pool/helpers.h>
161 #include <linux/phy_link_topology.h>
165 #include "net-sysfs.h"
167 static DEFINE_SPINLOCK(ptype_lock);
168 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
170 static int netif_rx_internal(struct sk_buff *skb);
171 static int call_netdevice_notifiers_extack(unsigned long val,
172 struct net_device *dev,
173 struct netlink_ext_ack *extack);
175 static DEFINE_MUTEX(ifalias_mutex);
177 /* protects napi_hash addition/deletion and napi_gen_id */
178 static DEFINE_SPINLOCK(napi_hash_lock);
180 static unsigned int napi_gen_id = NR_CPUS;
181 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
183 static DECLARE_RWSEM(devnet_rename_sem);
185 static inline void dev_base_seq_inc(struct net *net)
187 unsigned int val = net->dev_base_seq + 1;
189 WRITE_ONCE(net->dev_base_seq, val ?: 1);
192 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
194 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
196 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
199 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
201 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
204 #ifndef CONFIG_PREEMPT_RT
206 static DEFINE_STATIC_KEY_FALSE(use_backlog_threads_key);
208 static int __init setup_backlog_napi_threads(char *arg)
210 static_branch_enable(&use_backlog_threads_key);
213 early_param("thread_backlog_napi", setup_backlog_napi_threads);
215 static bool use_backlog_threads(void)
217 return static_branch_unlikely(&use_backlog_threads_key);
222 static bool use_backlog_threads(void)
229 static inline void backlog_lock_irq_save(struct softnet_data *sd,
230 unsigned long *flags)
232 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
233 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
235 local_irq_save(*flags);
238 static inline void backlog_lock_irq_disable(struct softnet_data *sd)
240 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
241 spin_lock_irq(&sd->input_pkt_queue.lock);
246 static inline void backlog_unlock_irq_restore(struct softnet_data *sd,
247 unsigned long *flags)
249 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
250 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
252 local_irq_restore(*flags);
255 static inline void backlog_unlock_irq_enable(struct softnet_data *sd)
257 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
258 spin_unlock_irq(&sd->input_pkt_queue.lock);
263 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
266 struct netdev_name_node *name_node;
268 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
271 INIT_HLIST_NODE(&name_node->hlist);
272 name_node->dev = dev;
273 name_node->name = name;
277 static struct netdev_name_node *
278 netdev_name_node_head_alloc(struct net_device *dev)
280 struct netdev_name_node *name_node;
282 name_node = netdev_name_node_alloc(dev, dev->name);
285 INIT_LIST_HEAD(&name_node->list);
289 static void netdev_name_node_free(struct netdev_name_node *name_node)
294 static void netdev_name_node_add(struct net *net,
295 struct netdev_name_node *name_node)
297 hlist_add_head_rcu(&name_node->hlist,
298 dev_name_hash(net, name_node->name));
301 static void netdev_name_node_del(struct netdev_name_node *name_node)
303 hlist_del_rcu(&name_node->hlist);
306 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
309 struct hlist_head *head = dev_name_hash(net, name);
310 struct netdev_name_node *name_node;
312 hlist_for_each_entry(name_node, head, hlist)
313 if (!strcmp(name_node->name, name))
318 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
321 struct hlist_head *head = dev_name_hash(net, name);
322 struct netdev_name_node *name_node;
324 hlist_for_each_entry_rcu(name_node, head, hlist)
325 if (!strcmp(name_node->name, name))
330 bool netdev_name_in_use(struct net *net, const char *name)
332 return netdev_name_node_lookup(net, name);
334 EXPORT_SYMBOL(netdev_name_in_use);
336 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
338 struct netdev_name_node *name_node;
339 struct net *net = dev_net(dev);
341 name_node = netdev_name_node_lookup(net, name);
344 name_node = netdev_name_node_alloc(dev, name);
347 netdev_name_node_add(net, name_node);
348 /* The node that holds dev->name acts as a head of per-device list. */
349 list_add_tail_rcu(&name_node->list, &dev->name_node->list);
354 static void netdev_name_node_alt_free(struct rcu_head *head)
356 struct netdev_name_node *name_node =
357 container_of(head, struct netdev_name_node, rcu);
359 kfree(name_node->name);
360 netdev_name_node_free(name_node);
363 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
365 netdev_name_node_del(name_node);
366 list_del(&name_node->list);
367 call_rcu(&name_node->rcu, netdev_name_node_alt_free);
370 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
372 struct netdev_name_node *name_node;
373 struct net *net = dev_net(dev);
375 name_node = netdev_name_node_lookup(net, name);
378 /* lookup might have found our primary name or a name belonging
381 if (name_node == dev->name_node || name_node->dev != dev)
384 __netdev_name_node_alt_destroy(name_node);
388 static void netdev_name_node_alt_flush(struct net_device *dev)
390 struct netdev_name_node *name_node, *tmp;
392 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list) {
393 list_del(&name_node->list);
394 netdev_name_node_alt_free(&name_node->rcu);
398 /* Device list insertion */
399 static void list_netdevice(struct net_device *dev)
401 struct netdev_name_node *name_node;
402 struct net *net = dev_net(dev);
406 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
407 netdev_name_node_add(net, dev->name_node);
408 hlist_add_head_rcu(&dev->index_hlist,
409 dev_index_hash(net, dev->ifindex));
411 netdev_for_each_altname(dev, name_node)
412 netdev_name_node_add(net, name_node);
414 /* We reserved the ifindex, this can't fail */
415 WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL));
417 dev_base_seq_inc(net);
420 /* Device list removal
421 * caller must respect a RCU grace period before freeing/reusing dev
423 static void unlist_netdevice(struct net_device *dev)
425 struct netdev_name_node *name_node;
426 struct net *net = dev_net(dev);
430 xa_erase(&net->dev_by_index, dev->ifindex);
432 netdev_for_each_altname(dev, name_node)
433 netdev_name_node_del(name_node);
435 /* Unlink dev from the device chain */
436 list_del_rcu(&dev->dev_list);
437 netdev_name_node_del(dev->name_node);
438 hlist_del_rcu(&dev->index_hlist);
440 dev_base_seq_inc(dev_net(dev));
447 static RAW_NOTIFIER_HEAD(netdev_chain);
450 * Device drivers call our routines to queue packets here. We empty the
451 * queue in the local softnet handler.
454 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data) = {
455 .process_queue_bh_lock = INIT_LOCAL_LOCK(process_queue_bh_lock),
457 EXPORT_PER_CPU_SYMBOL(softnet_data);
459 /* Page_pool has a lockless array/stack to alloc/recycle pages.
460 * PP consumers must pay attention to run APIs in the appropriate context
461 * (e.g. NAPI context).
463 static DEFINE_PER_CPU(struct page_pool *, system_page_pool);
465 #ifdef CONFIG_LOCKDEP
467 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
468 * according to dev->type
470 static const unsigned short netdev_lock_type[] = {
471 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
472 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
473 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
474 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
475 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
476 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
477 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
478 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
479 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
480 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
481 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
482 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
483 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
484 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
485 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
487 static const char *const netdev_lock_name[] = {
488 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
489 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
490 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
491 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
492 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
493 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
494 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
495 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
496 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
497 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
498 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
499 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
500 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
501 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
502 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
504 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
505 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
507 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
511 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
512 if (netdev_lock_type[i] == dev_type)
514 /* the last key is used by default */
515 return ARRAY_SIZE(netdev_lock_type) - 1;
518 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
519 unsigned short dev_type)
523 i = netdev_lock_pos(dev_type);
524 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
525 netdev_lock_name[i]);
528 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
532 i = netdev_lock_pos(dev->type);
533 lockdep_set_class_and_name(&dev->addr_list_lock,
534 &netdev_addr_lock_key[i],
535 netdev_lock_name[i]);
538 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
539 unsigned short dev_type)
543 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
548 /*******************************************************************************
550 * Protocol management and registration routines
552 *******************************************************************************/
556 * Add a protocol ID to the list. Now that the input handler is
557 * smarter we can dispense with all the messy stuff that used to be
560 * BEWARE!!! Protocol handlers, mangling input packets,
561 * MUST BE last in hash buckets and checking protocol handlers
562 * MUST start from promiscuous ptype_all chain in net_bh.
563 * It is true now, do not change it.
564 * Explanation follows: if protocol handler, mangling packet, will
565 * be the first on list, it is not able to sense, that packet
566 * is cloned and should be copied-on-write, so that it will
567 * change it and subsequent readers will get broken packet.
571 static inline struct list_head *ptype_head(const struct packet_type *pt)
573 if (pt->type == htons(ETH_P_ALL))
574 return pt->dev ? &pt->dev->ptype_all : &net_hotdata.ptype_all;
576 return pt->dev ? &pt->dev->ptype_specific :
577 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
581 * dev_add_pack - add packet handler
582 * @pt: packet type declaration
584 * Add a protocol handler to the networking stack. The passed &packet_type
585 * is linked into kernel lists and may not be freed until it has been
586 * removed from the kernel lists.
588 * This call does not sleep therefore it can not
589 * guarantee all CPU's that are in middle of receiving packets
590 * will see the new packet type (until the next received packet).
593 void dev_add_pack(struct packet_type *pt)
595 struct list_head *head = ptype_head(pt);
597 spin_lock(&ptype_lock);
598 list_add_rcu(&pt->list, head);
599 spin_unlock(&ptype_lock);
601 EXPORT_SYMBOL(dev_add_pack);
604 * __dev_remove_pack - remove packet handler
605 * @pt: packet type declaration
607 * Remove a protocol handler that was previously added to the kernel
608 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
609 * from the kernel lists and can be freed or reused once this function
612 * The packet type might still be in use by receivers
613 * and must not be freed until after all the CPU's have gone
614 * through a quiescent state.
616 void __dev_remove_pack(struct packet_type *pt)
618 struct list_head *head = ptype_head(pt);
619 struct packet_type *pt1;
621 spin_lock(&ptype_lock);
623 list_for_each_entry(pt1, head, list) {
625 list_del_rcu(&pt->list);
630 pr_warn("dev_remove_pack: %p not found\n", pt);
632 spin_unlock(&ptype_lock);
634 EXPORT_SYMBOL(__dev_remove_pack);
637 * dev_remove_pack - remove packet handler
638 * @pt: packet type declaration
640 * Remove a protocol handler that was previously added to the kernel
641 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
642 * from the kernel lists and can be freed or reused once this function
645 * This call sleeps to guarantee that no CPU is looking at the packet
648 void dev_remove_pack(struct packet_type *pt)
650 __dev_remove_pack(pt);
654 EXPORT_SYMBOL(dev_remove_pack);
657 /*******************************************************************************
659 * Device Interface Subroutines
661 *******************************************************************************/
664 * dev_get_iflink - get 'iflink' value of a interface
665 * @dev: targeted interface
667 * Indicates the ifindex the interface is linked to.
668 * Physical interfaces have the same 'ifindex' and 'iflink' values.
671 int dev_get_iflink(const struct net_device *dev)
673 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
674 return dev->netdev_ops->ndo_get_iflink(dev);
676 return READ_ONCE(dev->ifindex);
678 EXPORT_SYMBOL(dev_get_iflink);
681 * dev_fill_metadata_dst - Retrieve tunnel egress information.
682 * @dev: targeted interface
685 * For better visibility of tunnel traffic OVS needs to retrieve
686 * egress tunnel information for a packet. Following API allows
687 * user to get this info.
689 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
691 struct ip_tunnel_info *info;
693 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
696 info = skb_tunnel_info_unclone(skb);
699 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
702 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
704 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
706 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
708 int k = stack->num_paths++;
710 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
713 return &stack->path[k];
716 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
717 struct net_device_path_stack *stack)
719 const struct net_device *last_dev;
720 struct net_device_path_ctx ctx = {
723 struct net_device_path *path;
726 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
727 stack->num_paths = 0;
728 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
730 path = dev_fwd_path(stack);
734 memset(path, 0, sizeof(struct net_device_path));
735 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
739 if (WARN_ON_ONCE(last_dev == ctx.dev))
746 path = dev_fwd_path(stack);
749 path->type = DEV_PATH_ETHERNET;
754 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
757 * __dev_get_by_name - find a device by its name
758 * @net: the applicable net namespace
759 * @name: name to find
761 * Find an interface by name. Must be called under RTNL semaphore.
762 * If the name is found a pointer to the device is returned.
763 * If the name is not found then %NULL is returned. The
764 * reference counters are not incremented so the caller must be
765 * careful with locks.
768 struct net_device *__dev_get_by_name(struct net *net, const char *name)
770 struct netdev_name_node *node_name;
772 node_name = netdev_name_node_lookup(net, name);
773 return node_name ? node_name->dev : NULL;
775 EXPORT_SYMBOL(__dev_get_by_name);
778 * dev_get_by_name_rcu - find a device by its name
779 * @net: the applicable net namespace
780 * @name: name to find
782 * Find an interface by name.
783 * If the name is found a pointer to the device is returned.
784 * If the name is not found then %NULL is returned.
785 * The reference counters are not incremented so the caller must be
786 * careful with locks. The caller must hold RCU lock.
789 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
791 struct netdev_name_node *node_name;
793 node_name = netdev_name_node_lookup_rcu(net, name);
794 return node_name ? node_name->dev : NULL;
796 EXPORT_SYMBOL(dev_get_by_name_rcu);
798 /* Deprecated for new users, call netdev_get_by_name() instead */
799 struct net_device *dev_get_by_name(struct net *net, const char *name)
801 struct net_device *dev;
804 dev = dev_get_by_name_rcu(net, name);
809 EXPORT_SYMBOL(dev_get_by_name);
812 * netdev_get_by_name() - find a device by its name
813 * @net: the applicable net namespace
814 * @name: name to find
815 * @tracker: tracking object for the acquired reference
816 * @gfp: allocation flags for the tracker
818 * Find an interface by name. This can be called from any
819 * context and does its own locking. The returned handle has
820 * the usage count incremented and the caller must use netdev_put() to
821 * release it when it is no longer needed. %NULL is returned if no
822 * matching device is found.
824 struct net_device *netdev_get_by_name(struct net *net, const char *name,
825 netdevice_tracker *tracker, gfp_t gfp)
827 struct net_device *dev;
829 dev = dev_get_by_name(net, name);
831 netdev_tracker_alloc(dev, tracker, gfp);
834 EXPORT_SYMBOL(netdev_get_by_name);
837 * __dev_get_by_index - find a device by its ifindex
838 * @net: the applicable net namespace
839 * @ifindex: index of device
841 * Search for an interface by index. Returns %NULL if the device
842 * is not found or a pointer to the device. The device has not
843 * had its reference counter increased so the caller must be careful
844 * about locking. The caller must hold the RTNL semaphore.
847 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
849 struct net_device *dev;
850 struct hlist_head *head = dev_index_hash(net, ifindex);
852 hlist_for_each_entry(dev, head, index_hlist)
853 if (dev->ifindex == ifindex)
858 EXPORT_SYMBOL(__dev_get_by_index);
861 * dev_get_by_index_rcu - find a device by its ifindex
862 * @net: the applicable net namespace
863 * @ifindex: index of device
865 * Search for an interface by index. Returns %NULL if the device
866 * is not found or a pointer to the device. The device has not
867 * had its reference counter increased so the caller must be careful
868 * about locking. The caller must hold RCU lock.
871 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
873 struct net_device *dev;
874 struct hlist_head *head = dev_index_hash(net, ifindex);
876 hlist_for_each_entry_rcu(dev, head, index_hlist)
877 if (dev->ifindex == ifindex)
882 EXPORT_SYMBOL(dev_get_by_index_rcu);
884 /* Deprecated for new users, call netdev_get_by_index() instead */
885 struct net_device *dev_get_by_index(struct net *net, int ifindex)
887 struct net_device *dev;
890 dev = dev_get_by_index_rcu(net, ifindex);
895 EXPORT_SYMBOL(dev_get_by_index);
898 * netdev_get_by_index() - find a device by its ifindex
899 * @net: the applicable net namespace
900 * @ifindex: index of device
901 * @tracker: tracking object for the acquired reference
902 * @gfp: allocation flags for the tracker
904 * Search for an interface by index. Returns NULL if the device
905 * is not found or a pointer to the device. The device returned has
906 * had a reference added and the pointer is safe until the user calls
907 * netdev_put() to indicate they have finished with it.
909 struct net_device *netdev_get_by_index(struct net *net, int ifindex,
910 netdevice_tracker *tracker, gfp_t gfp)
912 struct net_device *dev;
914 dev = dev_get_by_index(net, ifindex);
916 netdev_tracker_alloc(dev, tracker, gfp);
919 EXPORT_SYMBOL(netdev_get_by_index);
922 * dev_get_by_napi_id - find a device by napi_id
923 * @napi_id: ID of the NAPI struct
925 * Search for an interface by NAPI ID. Returns %NULL if the device
926 * is not found or a pointer to the device. The device has not had
927 * its reference counter increased so the caller must be careful
928 * about locking. The caller must hold RCU lock.
931 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
933 struct napi_struct *napi;
935 WARN_ON_ONCE(!rcu_read_lock_held());
937 if (napi_id < MIN_NAPI_ID)
940 napi = napi_by_id(napi_id);
942 return napi ? napi->dev : NULL;
944 EXPORT_SYMBOL(dev_get_by_napi_id);
946 static DEFINE_SEQLOCK(netdev_rename_lock);
948 void netdev_copy_name(struct net_device *dev, char *name)
953 seq = read_seqbegin(&netdev_rename_lock);
954 strscpy(name, dev->name, IFNAMSIZ);
955 } while (read_seqretry(&netdev_rename_lock, seq));
959 * netdev_get_name - get a netdevice name, knowing its ifindex.
960 * @net: network namespace
961 * @name: a pointer to the buffer where the name will be stored.
962 * @ifindex: the ifindex of the interface to get the name from.
964 int netdev_get_name(struct net *net, char *name, int ifindex)
966 struct net_device *dev;
971 dev = dev_get_by_index_rcu(net, ifindex);
977 netdev_copy_name(dev, name);
986 * dev_getbyhwaddr_rcu - find a device by its hardware address
987 * @net: the applicable net namespace
988 * @type: media type of device
989 * @ha: hardware address
991 * Search for an interface by MAC address. Returns NULL if the device
992 * is not found or a pointer to the device.
993 * The caller must hold RCU or RTNL.
994 * The returned device has not had its ref count increased
995 * and the caller must therefore be careful about locking
999 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
1002 struct net_device *dev;
1004 for_each_netdev_rcu(net, dev)
1005 if (dev->type == type &&
1006 !memcmp(dev->dev_addr, ha, dev->addr_len))
1011 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
1013 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1015 struct net_device *dev, *ret = NULL;
1018 for_each_netdev_rcu(net, dev)
1019 if (dev->type == type) {
1027 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1030 * __dev_get_by_flags - find any device with given flags
1031 * @net: the applicable net namespace
1032 * @if_flags: IFF_* values
1033 * @mask: bitmask of bits in if_flags to check
1035 * Search for any interface with the given flags. Returns NULL if a device
1036 * is not found or a pointer to the device. Must be called inside
1037 * rtnl_lock(), and result refcount is unchanged.
1040 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1041 unsigned short mask)
1043 struct net_device *dev, *ret;
1048 for_each_netdev(net, dev) {
1049 if (((dev->flags ^ if_flags) & mask) == 0) {
1056 EXPORT_SYMBOL(__dev_get_by_flags);
1059 * dev_valid_name - check if name is okay for network device
1060 * @name: name string
1062 * Network device names need to be valid file names to
1063 * allow sysfs to work. We also disallow any kind of
1066 bool dev_valid_name(const char *name)
1070 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1072 if (!strcmp(name, ".") || !strcmp(name, ".."))
1076 if (*name == '/' || *name == ':' || isspace(*name))
1082 EXPORT_SYMBOL(dev_valid_name);
1085 * __dev_alloc_name - allocate a name for a device
1086 * @net: network namespace to allocate the device name in
1087 * @name: name format string
1088 * @res: result name string
1090 * Passed a format string - eg "lt%d" it will try and find a suitable
1091 * id. It scans list of devices to build up a free map, then chooses
1092 * the first empty slot. The caller must hold the dev_base or rtnl lock
1093 * while allocating the name and adding the device in order to avoid
1095 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1096 * Returns the number of the unit assigned or a negative errno code.
1099 static int __dev_alloc_name(struct net *net, const char *name, char *res)
1103 const int max_netdevices = 8*PAGE_SIZE;
1104 unsigned long *inuse;
1105 struct net_device *d;
1108 /* Verify the string as this thing may have come from the user.
1109 * There must be one "%d" and no other "%" characters.
1111 p = strchr(name, '%');
1112 if (!p || p[1] != 'd' || strchr(p + 2, '%'))
1115 /* Use one page as a bit array of possible slots */
1116 inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
1120 for_each_netdev(net, d) {
1121 struct netdev_name_node *name_node;
1123 netdev_for_each_altname(d, name_node) {
1124 if (!sscanf(name_node->name, name, &i))
1126 if (i < 0 || i >= max_netdevices)
1129 /* avoid cases where sscanf is not exact inverse of printf */
1130 snprintf(buf, IFNAMSIZ, name, i);
1131 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1132 __set_bit(i, inuse);
1134 if (!sscanf(d->name, name, &i))
1136 if (i < 0 || i >= max_netdevices)
1139 /* avoid cases where sscanf is not exact inverse of printf */
1140 snprintf(buf, IFNAMSIZ, name, i);
1141 if (!strncmp(buf, d->name, IFNAMSIZ))
1142 __set_bit(i, inuse);
1145 i = find_first_zero_bit(inuse, max_netdevices);
1147 if (i == max_netdevices)
1150 /* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */
1151 strscpy(buf, name, IFNAMSIZ);
1152 snprintf(res, IFNAMSIZ, buf, i);
1156 /* Returns negative errno or allocated unit id (see __dev_alloc_name()) */
1157 static int dev_prep_valid_name(struct net *net, struct net_device *dev,
1158 const char *want_name, char *out_name,
1161 if (!dev_valid_name(want_name))
1164 if (strchr(want_name, '%'))
1165 return __dev_alloc_name(net, want_name, out_name);
1167 if (netdev_name_in_use(net, want_name))
1169 if (out_name != want_name)
1170 strscpy(out_name, want_name, IFNAMSIZ);
1175 * dev_alloc_name - allocate a name for a device
1177 * @name: name format string
1179 * Passed a format string - eg "lt%d" it will try and find a suitable
1180 * id. It scans list of devices to build up a free map, then chooses
1181 * the first empty slot. The caller must hold the dev_base or rtnl lock
1182 * while allocating the name and adding the device in order to avoid
1184 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1185 * Returns the number of the unit assigned or a negative errno code.
1188 int dev_alloc_name(struct net_device *dev, const char *name)
1190 return dev_prep_valid_name(dev_net(dev), dev, name, dev->name, ENFILE);
1192 EXPORT_SYMBOL(dev_alloc_name);
1194 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1199 ret = dev_prep_valid_name(net, dev, name, dev->name, EEXIST);
1200 return ret < 0 ? ret : 0;
1204 * dev_change_name - change name of a device
1206 * @newname: name (or format string) must be at least IFNAMSIZ
1208 * Change name of a device, can pass format strings "eth%d".
1211 int dev_change_name(struct net_device *dev, const char *newname)
1213 unsigned char old_assign_type;
1214 char oldname[IFNAMSIZ];
1220 BUG_ON(!dev_net(dev));
1224 down_write(&devnet_rename_sem);
1226 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1227 up_write(&devnet_rename_sem);
1231 memcpy(oldname, dev->name, IFNAMSIZ);
1233 write_seqlock_bh(&netdev_rename_lock);
1234 err = dev_get_valid_name(net, dev, newname);
1235 write_sequnlock_bh(&netdev_rename_lock);
1238 up_write(&devnet_rename_sem);
1242 if (oldname[0] && !strchr(oldname, '%'))
1243 netdev_info(dev, "renamed from %s%s\n", oldname,
1244 dev->flags & IFF_UP ? " (while UP)" : "");
1246 old_assign_type = dev->name_assign_type;
1247 WRITE_ONCE(dev->name_assign_type, NET_NAME_RENAMED);
1250 ret = device_rename(&dev->dev, dev->name);
1252 memcpy(dev->name, oldname, IFNAMSIZ);
1253 WRITE_ONCE(dev->name_assign_type, old_assign_type);
1254 up_write(&devnet_rename_sem);
1258 up_write(&devnet_rename_sem);
1260 netdev_adjacent_rename_links(dev, oldname);
1262 netdev_name_node_del(dev->name_node);
1266 netdev_name_node_add(net, dev->name_node);
1268 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1269 ret = notifier_to_errno(ret);
1272 /* err >= 0 after dev_alloc_name() or stores the first errno */
1275 down_write(&devnet_rename_sem);
1276 write_seqlock_bh(&netdev_rename_lock);
1277 memcpy(dev->name, oldname, IFNAMSIZ);
1278 write_sequnlock_bh(&netdev_rename_lock);
1279 memcpy(oldname, newname, IFNAMSIZ);
1280 WRITE_ONCE(dev->name_assign_type, old_assign_type);
1281 old_assign_type = NET_NAME_RENAMED;
1284 netdev_err(dev, "name change rollback failed: %d\n",
1293 * dev_set_alias - change ifalias of a device
1295 * @alias: name up to IFALIASZ
1296 * @len: limit of bytes to copy from info
1298 * Set ifalias for a device,
1300 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1302 struct dev_ifalias *new_alias = NULL;
1304 if (len >= IFALIASZ)
1308 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1312 memcpy(new_alias->ifalias, alias, len);
1313 new_alias->ifalias[len] = 0;
1316 mutex_lock(&ifalias_mutex);
1317 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1318 mutex_is_locked(&ifalias_mutex));
1319 mutex_unlock(&ifalias_mutex);
1322 kfree_rcu(new_alias, rcuhead);
1326 EXPORT_SYMBOL(dev_set_alias);
1329 * dev_get_alias - get ifalias of a device
1331 * @name: buffer to store name of ifalias
1332 * @len: size of buffer
1334 * get ifalias for a device. Caller must make sure dev cannot go
1335 * away, e.g. rcu read lock or own a reference count to device.
1337 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1339 const struct dev_ifalias *alias;
1343 alias = rcu_dereference(dev->ifalias);
1345 ret = snprintf(name, len, "%s", alias->ifalias);
1352 * netdev_features_change - device changes features
1353 * @dev: device to cause notification
1355 * Called to indicate a device has changed features.
1357 void netdev_features_change(struct net_device *dev)
1359 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1361 EXPORT_SYMBOL(netdev_features_change);
1364 * netdev_state_change - device changes state
1365 * @dev: device to cause notification
1367 * Called to indicate a device has changed state. This function calls
1368 * the notifier chains for netdev_chain and sends a NEWLINK message
1369 * to the routing socket.
1371 void netdev_state_change(struct net_device *dev)
1373 if (dev->flags & IFF_UP) {
1374 struct netdev_notifier_change_info change_info = {
1378 call_netdevice_notifiers_info(NETDEV_CHANGE,
1380 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1383 EXPORT_SYMBOL(netdev_state_change);
1386 * __netdev_notify_peers - notify network peers about existence of @dev,
1387 * to be called when rtnl lock is already held.
1388 * @dev: network device
1390 * Generate traffic such that interested network peers are aware of
1391 * @dev, such as by generating a gratuitous ARP. This may be used when
1392 * a device wants to inform the rest of the network about some sort of
1393 * reconfiguration such as a failover event or virtual machine
1396 void __netdev_notify_peers(struct net_device *dev)
1399 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1400 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1402 EXPORT_SYMBOL(__netdev_notify_peers);
1405 * netdev_notify_peers - notify network peers about existence of @dev
1406 * @dev: network device
1408 * Generate traffic such that interested network peers are aware of
1409 * @dev, such as by generating a gratuitous ARP. This may be used when
1410 * a device wants to inform the rest of the network about some sort of
1411 * reconfiguration such as a failover event or virtual machine
1414 void netdev_notify_peers(struct net_device *dev)
1417 __netdev_notify_peers(dev);
1420 EXPORT_SYMBOL(netdev_notify_peers);
1422 static int napi_threaded_poll(void *data);
1424 static int napi_kthread_create(struct napi_struct *n)
1428 /* Create and wake up the kthread once to put it in
1429 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1430 * warning and work with loadavg.
1432 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1433 n->dev->name, n->napi_id);
1434 if (IS_ERR(n->thread)) {
1435 err = PTR_ERR(n->thread);
1436 pr_err("kthread_run failed with err %d\n", err);
1443 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1445 const struct net_device_ops *ops = dev->netdev_ops;
1449 dev_addr_check(dev);
1451 if (!netif_device_present(dev)) {
1452 /* may be detached because parent is runtime-suspended */
1453 if (dev->dev.parent)
1454 pm_runtime_resume(dev->dev.parent);
1455 if (!netif_device_present(dev))
1459 /* Block netpoll from trying to do any rx path servicing.
1460 * If we don't do this there is a chance ndo_poll_controller
1461 * or ndo_poll may be running while we open the device
1463 netpoll_poll_disable(dev);
1465 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1466 ret = notifier_to_errno(ret);
1470 set_bit(__LINK_STATE_START, &dev->state);
1472 if (ops->ndo_validate_addr)
1473 ret = ops->ndo_validate_addr(dev);
1475 if (!ret && ops->ndo_open)
1476 ret = ops->ndo_open(dev);
1478 netpoll_poll_enable(dev);
1481 clear_bit(__LINK_STATE_START, &dev->state);
1483 dev->flags |= IFF_UP;
1484 dev_set_rx_mode(dev);
1486 add_device_randomness(dev->dev_addr, dev->addr_len);
1493 * dev_open - prepare an interface for use.
1494 * @dev: device to open
1495 * @extack: netlink extended ack
1497 * Takes a device from down to up state. The device's private open
1498 * function is invoked and then the multicast lists are loaded. Finally
1499 * the device is moved into the up state and a %NETDEV_UP message is
1500 * sent to the netdev notifier chain.
1502 * Calling this function on an active interface is a nop. On a failure
1503 * a negative errno code is returned.
1505 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1509 if (dev->flags & IFF_UP)
1512 ret = __dev_open(dev, extack);
1516 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1517 call_netdevice_notifiers(NETDEV_UP, dev);
1521 EXPORT_SYMBOL(dev_open);
1523 static void __dev_close_many(struct list_head *head)
1525 struct net_device *dev;
1530 list_for_each_entry(dev, head, close_list) {
1531 /* Temporarily disable netpoll until the interface is down */
1532 netpoll_poll_disable(dev);
1534 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1536 clear_bit(__LINK_STATE_START, &dev->state);
1538 /* Synchronize to scheduled poll. We cannot touch poll list, it
1539 * can be even on different cpu. So just clear netif_running().
1541 * dev->stop() will invoke napi_disable() on all of it's
1542 * napi_struct instances on this device.
1544 smp_mb__after_atomic(); /* Commit netif_running(). */
1547 dev_deactivate_many(head);
1549 list_for_each_entry(dev, head, close_list) {
1550 const struct net_device_ops *ops = dev->netdev_ops;
1553 * Call the device specific close. This cannot fail.
1554 * Only if device is UP
1556 * We allow it to be called even after a DETACH hot-plug
1562 dev->flags &= ~IFF_UP;
1563 netpoll_poll_enable(dev);
1567 static void __dev_close(struct net_device *dev)
1571 list_add(&dev->close_list, &single);
1572 __dev_close_many(&single);
1576 void dev_close_many(struct list_head *head, bool unlink)
1578 struct net_device *dev, *tmp;
1580 /* Remove the devices that don't need to be closed */
1581 list_for_each_entry_safe(dev, tmp, head, close_list)
1582 if (!(dev->flags & IFF_UP))
1583 list_del_init(&dev->close_list);
1585 __dev_close_many(head);
1587 list_for_each_entry_safe(dev, tmp, head, close_list) {
1588 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1589 call_netdevice_notifiers(NETDEV_DOWN, dev);
1591 list_del_init(&dev->close_list);
1594 EXPORT_SYMBOL(dev_close_many);
1597 * dev_close - shutdown an interface.
1598 * @dev: device to shutdown
1600 * This function moves an active device into down state. A
1601 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1602 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1605 void dev_close(struct net_device *dev)
1607 if (dev->flags & IFF_UP) {
1610 list_add(&dev->close_list, &single);
1611 dev_close_many(&single, true);
1615 EXPORT_SYMBOL(dev_close);
1619 * dev_disable_lro - disable Large Receive Offload on a device
1622 * Disable Large Receive Offload (LRO) on a net device. Must be
1623 * called under RTNL. This is needed if received packets may be
1624 * forwarded to another interface.
1626 void dev_disable_lro(struct net_device *dev)
1628 struct net_device *lower_dev;
1629 struct list_head *iter;
1631 dev->wanted_features &= ~NETIF_F_LRO;
1632 netdev_update_features(dev);
1634 if (unlikely(dev->features & NETIF_F_LRO))
1635 netdev_WARN(dev, "failed to disable LRO!\n");
1637 netdev_for_each_lower_dev(dev, lower_dev, iter)
1638 dev_disable_lro(lower_dev);
1640 EXPORT_SYMBOL(dev_disable_lro);
1643 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1646 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1647 * called under RTNL. This is needed if Generic XDP is installed on
1650 static void dev_disable_gro_hw(struct net_device *dev)
1652 dev->wanted_features &= ~NETIF_F_GRO_HW;
1653 netdev_update_features(dev);
1655 if (unlikely(dev->features & NETIF_F_GRO_HW))
1656 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1659 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1662 case NETDEV_##val: \
1663 return "NETDEV_" __stringify(val);
1665 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1666 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1667 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1668 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1669 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1670 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1671 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1672 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1673 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1674 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1675 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1679 return "UNKNOWN_NETDEV_EVENT";
1681 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1683 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1684 struct net_device *dev)
1686 struct netdev_notifier_info info = {
1690 return nb->notifier_call(nb, val, &info);
1693 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1694 struct net_device *dev)
1698 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1699 err = notifier_to_errno(err);
1703 if (!(dev->flags & IFF_UP))
1706 call_netdevice_notifier(nb, NETDEV_UP, dev);
1710 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1711 struct net_device *dev)
1713 if (dev->flags & IFF_UP) {
1714 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1716 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1718 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1721 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1724 struct net_device *dev;
1727 for_each_netdev(net, dev) {
1728 err = call_netdevice_register_notifiers(nb, dev);
1735 for_each_netdev_continue_reverse(net, dev)
1736 call_netdevice_unregister_notifiers(nb, dev);
1740 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1743 struct net_device *dev;
1745 for_each_netdev(net, dev)
1746 call_netdevice_unregister_notifiers(nb, dev);
1749 static int dev_boot_phase = 1;
1752 * register_netdevice_notifier - register a network notifier block
1755 * Register a notifier to be called when network device events occur.
1756 * The notifier passed is linked into the kernel structures and must
1757 * not be reused until it has been unregistered. A negative errno code
1758 * is returned on a failure.
1760 * When registered all registration and up events are replayed
1761 * to the new notifier to allow device to have a race free
1762 * view of the network device list.
1765 int register_netdevice_notifier(struct notifier_block *nb)
1770 /* Close race with setup_net() and cleanup_net() */
1771 down_write(&pernet_ops_rwsem);
1773 err = raw_notifier_chain_register(&netdev_chain, nb);
1779 err = call_netdevice_register_net_notifiers(nb, net);
1786 up_write(&pernet_ops_rwsem);
1790 for_each_net_continue_reverse(net)
1791 call_netdevice_unregister_net_notifiers(nb, net);
1793 raw_notifier_chain_unregister(&netdev_chain, nb);
1796 EXPORT_SYMBOL(register_netdevice_notifier);
1799 * unregister_netdevice_notifier - unregister a network notifier block
1802 * Unregister a notifier previously registered by
1803 * register_netdevice_notifier(). The notifier is unlinked into the
1804 * kernel structures and may then be reused. A negative errno code
1805 * is returned on a failure.
1807 * After unregistering unregister and down device events are synthesized
1808 * for all devices on the device list to the removed notifier to remove
1809 * the need for special case cleanup code.
1812 int unregister_netdevice_notifier(struct notifier_block *nb)
1817 /* Close race with setup_net() and cleanup_net() */
1818 down_write(&pernet_ops_rwsem);
1820 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1825 call_netdevice_unregister_net_notifiers(nb, net);
1829 up_write(&pernet_ops_rwsem);
1832 EXPORT_SYMBOL(unregister_netdevice_notifier);
1834 static int __register_netdevice_notifier_net(struct net *net,
1835 struct notifier_block *nb,
1836 bool ignore_call_fail)
1840 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1846 err = call_netdevice_register_net_notifiers(nb, net);
1847 if (err && !ignore_call_fail)
1848 goto chain_unregister;
1853 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1857 static int __unregister_netdevice_notifier_net(struct net *net,
1858 struct notifier_block *nb)
1862 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1866 call_netdevice_unregister_net_notifiers(nb, net);
1871 * register_netdevice_notifier_net - register a per-netns network notifier block
1872 * @net: network namespace
1875 * Register a notifier to be called when network device events occur.
1876 * The notifier passed is linked into the kernel structures and must
1877 * not be reused until it has been unregistered. A negative errno code
1878 * is returned on a failure.
1880 * When registered all registration and up events are replayed
1881 * to the new notifier to allow device to have a race free
1882 * view of the network device list.
1885 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1890 err = __register_netdevice_notifier_net(net, nb, false);
1894 EXPORT_SYMBOL(register_netdevice_notifier_net);
1897 * unregister_netdevice_notifier_net - unregister a per-netns
1898 * network notifier block
1899 * @net: network namespace
1902 * Unregister a notifier previously registered by
1903 * register_netdevice_notifier_net(). The notifier is unlinked from the
1904 * kernel structures and may then be reused. A negative errno code
1905 * is returned on a failure.
1907 * After unregistering unregister and down device events are synthesized
1908 * for all devices on the device list to the removed notifier to remove
1909 * the need for special case cleanup code.
1912 int unregister_netdevice_notifier_net(struct net *net,
1913 struct notifier_block *nb)
1918 err = __unregister_netdevice_notifier_net(net, nb);
1922 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1924 static void __move_netdevice_notifier_net(struct net *src_net,
1925 struct net *dst_net,
1926 struct notifier_block *nb)
1928 __unregister_netdevice_notifier_net(src_net, nb);
1929 __register_netdevice_notifier_net(dst_net, nb, true);
1932 int register_netdevice_notifier_dev_net(struct net_device *dev,
1933 struct notifier_block *nb,
1934 struct netdev_net_notifier *nn)
1939 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1942 list_add(&nn->list, &dev->net_notifier_list);
1947 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1949 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1950 struct notifier_block *nb,
1951 struct netdev_net_notifier *nn)
1956 list_del(&nn->list);
1957 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1961 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1963 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1966 struct netdev_net_notifier *nn;
1968 list_for_each_entry(nn, &dev->net_notifier_list, list)
1969 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
1973 * call_netdevice_notifiers_info - call all network notifier blocks
1974 * @val: value passed unmodified to notifier function
1975 * @info: notifier information data
1977 * Call all network notifier blocks. Parameters and return value
1978 * are as for raw_notifier_call_chain().
1981 int call_netdevice_notifiers_info(unsigned long val,
1982 struct netdev_notifier_info *info)
1984 struct net *net = dev_net(info->dev);
1989 /* Run per-netns notifier block chain first, then run the global one.
1990 * Hopefully, one day, the global one is going to be removed after
1991 * all notifier block registrators get converted to be per-netns.
1993 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1994 if (ret & NOTIFY_STOP_MASK)
1996 return raw_notifier_call_chain(&netdev_chain, val, info);
2000 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
2001 * for and rollback on error
2002 * @val_up: value passed unmodified to notifier function
2003 * @val_down: value passed unmodified to the notifier function when
2004 * recovering from an error on @val_up
2005 * @info: notifier information data
2007 * Call all per-netns network notifier blocks, but not notifier blocks on
2008 * the global notifier chain. Parameters and return value are as for
2009 * raw_notifier_call_chain_robust().
2013 call_netdevice_notifiers_info_robust(unsigned long val_up,
2014 unsigned long val_down,
2015 struct netdev_notifier_info *info)
2017 struct net *net = dev_net(info->dev);
2021 return raw_notifier_call_chain_robust(&net->netdev_chain,
2022 val_up, val_down, info);
2025 static int call_netdevice_notifiers_extack(unsigned long val,
2026 struct net_device *dev,
2027 struct netlink_ext_ack *extack)
2029 struct netdev_notifier_info info = {
2034 return call_netdevice_notifiers_info(val, &info);
2038 * call_netdevice_notifiers - call all network notifier blocks
2039 * @val: value passed unmodified to notifier function
2040 * @dev: net_device pointer passed unmodified to notifier function
2042 * Call all network notifier blocks. Parameters and return value
2043 * are as for raw_notifier_call_chain().
2046 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2048 return call_netdevice_notifiers_extack(val, dev, NULL);
2050 EXPORT_SYMBOL(call_netdevice_notifiers);
2053 * call_netdevice_notifiers_mtu - call all network notifier blocks
2054 * @val: value passed unmodified to notifier function
2055 * @dev: net_device pointer passed unmodified to notifier function
2056 * @arg: additional u32 argument passed to the notifier function
2058 * Call all network notifier blocks. Parameters and return value
2059 * are as for raw_notifier_call_chain().
2061 static int call_netdevice_notifiers_mtu(unsigned long val,
2062 struct net_device *dev, u32 arg)
2064 struct netdev_notifier_info_ext info = {
2069 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2071 return call_netdevice_notifiers_info(val, &info.info);
2074 #ifdef CONFIG_NET_INGRESS
2075 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2077 void net_inc_ingress_queue(void)
2079 static_branch_inc(&ingress_needed_key);
2081 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2083 void net_dec_ingress_queue(void)
2085 static_branch_dec(&ingress_needed_key);
2087 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2090 #ifdef CONFIG_NET_EGRESS
2091 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2093 void net_inc_egress_queue(void)
2095 static_branch_inc(&egress_needed_key);
2097 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2099 void net_dec_egress_queue(void)
2101 static_branch_dec(&egress_needed_key);
2103 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2106 #ifdef CONFIG_NET_CLS_ACT
2107 DEFINE_STATIC_KEY_FALSE(tcf_bypass_check_needed_key);
2108 EXPORT_SYMBOL(tcf_bypass_check_needed_key);
2111 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2112 EXPORT_SYMBOL(netstamp_needed_key);
2113 #ifdef CONFIG_JUMP_LABEL
2114 static atomic_t netstamp_needed_deferred;
2115 static atomic_t netstamp_wanted;
2116 static void netstamp_clear(struct work_struct *work)
2118 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2121 wanted = atomic_add_return(deferred, &netstamp_wanted);
2123 static_branch_enable(&netstamp_needed_key);
2125 static_branch_disable(&netstamp_needed_key);
2127 static DECLARE_WORK(netstamp_work, netstamp_clear);
2130 void net_enable_timestamp(void)
2132 #ifdef CONFIG_JUMP_LABEL
2133 int wanted = atomic_read(&netstamp_wanted);
2135 while (wanted > 0) {
2136 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2139 atomic_inc(&netstamp_needed_deferred);
2140 schedule_work(&netstamp_work);
2142 static_branch_inc(&netstamp_needed_key);
2145 EXPORT_SYMBOL(net_enable_timestamp);
2147 void net_disable_timestamp(void)
2149 #ifdef CONFIG_JUMP_LABEL
2150 int wanted = atomic_read(&netstamp_wanted);
2152 while (wanted > 1) {
2153 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2156 atomic_dec(&netstamp_needed_deferred);
2157 schedule_work(&netstamp_work);
2159 static_branch_dec(&netstamp_needed_key);
2162 EXPORT_SYMBOL(net_disable_timestamp);
2164 static inline void net_timestamp_set(struct sk_buff *skb)
2167 skb->tstamp_type = SKB_CLOCK_REALTIME;
2168 if (static_branch_unlikely(&netstamp_needed_key))
2169 skb->tstamp = ktime_get_real();
2172 #define net_timestamp_check(COND, SKB) \
2173 if (static_branch_unlikely(&netstamp_needed_key)) { \
2174 if ((COND) && !(SKB)->tstamp) \
2175 (SKB)->tstamp = ktime_get_real(); \
2178 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2180 return __is_skb_forwardable(dev, skb, true);
2182 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2184 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2187 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2190 skb->protocol = eth_type_trans(skb, dev);
2191 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2197 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2199 return __dev_forward_skb2(dev, skb, true);
2201 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2204 * dev_forward_skb - loopback an skb to another netif
2206 * @dev: destination network device
2207 * @skb: buffer to forward
2210 * NET_RX_SUCCESS (no congestion)
2211 * NET_RX_DROP (packet was dropped, but freed)
2213 * dev_forward_skb can be used for injecting an skb from the
2214 * start_xmit function of one device into the receive queue
2215 * of another device.
2217 * The receiving device may be in another namespace, so
2218 * we have to clear all information in the skb that could
2219 * impact namespace isolation.
2221 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2223 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2225 EXPORT_SYMBOL_GPL(dev_forward_skb);
2227 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2229 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2232 static inline int deliver_skb(struct sk_buff *skb,
2233 struct packet_type *pt_prev,
2234 struct net_device *orig_dev)
2236 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2238 refcount_inc(&skb->users);
2239 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2242 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2243 struct packet_type **pt,
2244 struct net_device *orig_dev,
2246 struct list_head *ptype_list)
2248 struct packet_type *ptype, *pt_prev = *pt;
2250 list_for_each_entry_rcu(ptype, ptype_list, list) {
2251 if (ptype->type != type)
2254 deliver_skb(skb, pt_prev, orig_dev);
2260 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2262 if (!ptype->af_packet_priv || !skb->sk)
2265 if (ptype->id_match)
2266 return ptype->id_match(ptype, skb->sk);
2267 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2274 * dev_nit_active - return true if any network interface taps are in use
2276 * @dev: network device to check for the presence of taps
2278 bool dev_nit_active(struct net_device *dev)
2280 return !list_empty(&net_hotdata.ptype_all) ||
2281 !list_empty(&dev->ptype_all);
2283 EXPORT_SYMBOL_GPL(dev_nit_active);
2286 * Support routine. Sends outgoing frames to any network
2287 * taps currently in use.
2290 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2292 struct list_head *ptype_list = &net_hotdata.ptype_all;
2293 struct packet_type *ptype, *pt_prev = NULL;
2294 struct sk_buff *skb2 = NULL;
2298 list_for_each_entry_rcu(ptype, ptype_list, list) {
2299 if (READ_ONCE(ptype->ignore_outgoing))
2302 /* Never send packets back to the socket
2305 if (skb_loop_sk(ptype, skb))
2309 deliver_skb(skb2, pt_prev, skb->dev);
2314 /* need to clone skb, done only once */
2315 skb2 = skb_clone(skb, GFP_ATOMIC);
2319 net_timestamp_set(skb2);
2321 /* skb->nh should be correctly
2322 * set by sender, so that the second statement is
2323 * just protection against buggy protocols.
2325 skb_reset_mac_header(skb2);
2327 if (skb_network_header(skb2) < skb2->data ||
2328 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2329 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2330 ntohs(skb2->protocol),
2332 skb_reset_network_header(skb2);
2335 skb2->transport_header = skb2->network_header;
2336 skb2->pkt_type = PACKET_OUTGOING;
2340 if (ptype_list == &net_hotdata.ptype_all) {
2341 ptype_list = &dev->ptype_all;
2346 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2347 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2353 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2356 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2357 * @dev: Network device
2358 * @txq: number of queues available
2360 * If real_num_tx_queues is changed the tc mappings may no longer be
2361 * valid. To resolve this verify the tc mapping remains valid and if
2362 * not NULL the mapping. With no priorities mapping to this
2363 * offset/count pair it will no longer be used. In the worst case TC0
2364 * is invalid nothing can be done so disable priority mappings. If is
2365 * expected that drivers will fix this mapping if they can before
2366 * calling netif_set_real_num_tx_queues.
2368 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2371 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2373 /* If TC0 is invalidated disable TC mapping */
2374 if (tc->offset + tc->count > txq) {
2375 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2380 /* Invalidated prio to tc mappings set to TC0 */
2381 for (i = 1; i < TC_BITMASK + 1; i++) {
2382 int q = netdev_get_prio_tc_map(dev, i);
2384 tc = &dev->tc_to_txq[q];
2385 if (tc->offset + tc->count > txq) {
2386 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",
2388 netdev_set_prio_tc_map(dev, i, 0);
2393 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2396 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2399 /* walk through the TCs and see if it falls into any of them */
2400 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2401 if ((txq - tc->offset) < tc->count)
2405 /* didn't find it, just return -1 to indicate no match */
2411 EXPORT_SYMBOL(netdev_txq_to_tc);
2414 static struct static_key xps_needed __read_mostly;
2415 static struct static_key xps_rxqs_needed __read_mostly;
2416 static DEFINE_MUTEX(xps_map_mutex);
2417 #define xmap_dereference(P) \
2418 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2420 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2421 struct xps_dev_maps *old_maps, int tci, u16 index)
2423 struct xps_map *map = NULL;
2426 map = xmap_dereference(dev_maps->attr_map[tci]);
2430 for (pos = map->len; pos--;) {
2431 if (map->queues[pos] != index)
2435 map->queues[pos] = map->queues[--map->len];
2440 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2441 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2442 kfree_rcu(map, rcu);
2449 static bool remove_xps_queue_cpu(struct net_device *dev,
2450 struct xps_dev_maps *dev_maps,
2451 int cpu, u16 offset, u16 count)
2453 int num_tc = dev_maps->num_tc;
2454 bool active = false;
2457 for (tci = cpu * num_tc; num_tc--; tci++) {
2460 for (i = count, j = offset; i--; j++) {
2461 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2471 static void reset_xps_maps(struct net_device *dev,
2472 struct xps_dev_maps *dev_maps,
2473 enum xps_map_type type)
2475 static_key_slow_dec_cpuslocked(&xps_needed);
2476 if (type == XPS_RXQS)
2477 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2479 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2481 kfree_rcu(dev_maps, rcu);
2484 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2485 u16 offset, u16 count)
2487 struct xps_dev_maps *dev_maps;
2488 bool active = false;
2491 dev_maps = xmap_dereference(dev->xps_maps[type]);
2495 for (j = 0; j < dev_maps->nr_ids; j++)
2496 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2498 reset_xps_maps(dev, dev_maps, type);
2500 if (type == XPS_CPUS) {
2501 for (i = offset + (count - 1); count--; i--)
2502 netdev_queue_numa_node_write(
2503 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2507 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2510 if (!static_key_false(&xps_needed))
2514 mutex_lock(&xps_map_mutex);
2516 if (static_key_false(&xps_rxqs_needed))
2517 clean_xps_maps(dev, XPS_RXQS, offset, count);
2519 clean_xps_maps(dev, XPS_CPUS, offset, count);
2521 mutex_unlock(&xps_map_mutex);
2525 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2527 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2530 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2531 u16 index, bool is_rxqs_map)
2533 struct xps_map *new_map;
2534 int alloc_len = XPS_MIN_MAP_ALLOC;
2537 for (pos = 0; map && pos < map->len; pos++) {
2538 if (map->queues[pos] != index)
2543 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2545 if (pos < map->alloc_len)
2548 alloc_len = map->alloc_len * 2;
2551 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2555 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2557 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2558 cpu_to_node(attr_index));
2562 for (i = 0; i < pos; i++)
2563 new_map->queues[i] = map->queues[i];
2564 new_map->alloc_len = alloc_len;
2570 /* Copy xps maps at a given index */
2571 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2572 struct xps_dev_maps *new_dev_maps, int index,
2573 int tc, bool skip_tc)
2575 int i, tci = index * dev_maps->num_tc;
2576 struct xps_map *map;
2578 /* copy maps belonging to foreign traffic classes */
2579 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2580 if (i == tc && skip_tc)
2583 /* fill in the new device map from the old device map */
2584 map = xmap_dereference(dev_maps->attr_map[tci]);
2585 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2589 /* Must be called under cpus_read_lock */
2590 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2591 u16 index, enum xps_map_type type)
2593 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2594 const unsigned long *online_mask = NULL;
2595 bool active = false, copy = false;
2596 int i, j, tci, numa_node_id = -2;
2597 int maps_sz, num_tc = 1, tc = 0;
2598 struct xps_map *map, *new_map;
2599 unsigned int nr_ids;
2601 WARN_ON_ONCE(index >= dev->num_tx_queues);
2604 /* Do not allow XPS on subordinate device directly */
2605 num_tc = dev->num_tc;
2609 /* If queue belongs to subordinate dev use its map */
2610 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2612 tc = netdev_txq_to_tc(dev, index);
2617 mutex_lock(&xps_map_mutex);
2619 dev_maps = xmap_dereference(dev->xps_maps[type]);
2620 if (type == XPS_RXQS) {
2621 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2622 nr_ids = dev->num_rx_queues;
2624 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2625 if (num_possible_cpus() > 1)
2626 online_mask = cpumask_bits(cpu_online_mask);
2627 nr_ids = nr_cpu_ids;
2630 if (maps_sz < L1_CACHE_BYTES)
2631 maps_sz = L1_CACHE_BYTES;
2633 /* The old dev_maps could be larger or smaller than the one we're
2634 * setting up now, as dev->num_tc or nr_ids could have been updated in
2635 * between. We could try to be smart, but let's be safe instead and only
2636 * copy foreign traffic classes if the two map sizes match.
2639 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2642 /* allocate memory for queue storage */
2643 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2645 if (!new_dev_maps) {
2646 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2647 if (!new_dev_maps) {
2648 mutex_unlock(&xps_map_mutex);
2652 new_dev_maps->nr_ids = nr_ids;
2653 new_dev_maps->num_tc = num_tc;
2656 tci = j * num_tc + tc;
2657 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2659 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2663 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2667 goto out_no_new_maps;
2670 /* Increment static keys at most once per type */
2671 static_key_slow_inc_cpuslocked(&xps_needed);
2672 if (type == XPS_RXQS)
2673 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2676 for (j = 0; j < nr_ids; j++) {
2677 bool skip_tc = false;
2679 tci = j * num_tc + tc;
2680 if (netif_attr_test_mask(j, mask, nr_ids) &&
2681 netif_attr_test_online(j, online_mask, nr_ids)) {
2682 /* add tx-queue to CPU/rx-queue maps */
2687 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2688 while ((pos < map->len) && (map->queues[pos] != index))
2691 if (pos == map->len)
2692 map->queues[map->len++] = index;
2694 if (type == XPS_CPUS) {
2695 if (numa_node_id == -2)
2696 numa_node_id = cpu_to_node(j);
2697 else if (numa_node_id != cpu_to_node(j))
2704 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2708 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2710 /* Cleanup old maps */
2712 goto out_no_old_maps;
2714 for (j = 0; j < dev_maps->nr_ids; j++) {
2715 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2716 map = xmap_dereference(dev_maps->attr_map[tci]);
2721 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2726 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2727 kfree_rcu(map, rcu);
2731 old_dev_maps = dev_maps;
2734 dev_maps = new_dev_maps;
2738 if (type == XPS_CPUS)
2739 /* update Tx queue numa node */
2740 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2741 (numa_node_id >= 0) ?
2742 numa_node_id : NUMA_NO_NODE);
2747 /* removes tx-queue from unused CPUs/rx-queues */
2748 for (j = 0; j < dev_maps->nr_ids; j++) {
2749 tci = j * dev_maps->num_tc;
2751 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2753 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2754 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2757 active |= remove_xps_queue(dev_maps,
2758 copy ? old_dev_maps : NULL,
2764 kfree_rcu(old_dev_maps, rcu);
2766 /* free map if not active */
2768 reset_xps_maps(dev, dev_maps, type);
2771 mutex_unlock(&xps_map_mutex);
2775 /* remove any maps that we added */
2776 for (j = 0; j < nr_ids; j++) {
2777 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2778 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2780 xmap_dereference(dev_maps->attr_map[tci]) :
2782 if (new_map && new_map != map)
2787 mutex_unlock(&xps_map_mutex);
2789 kfree(new_dev_maps);
2792 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2794 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2800 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2805 EXPORT_SYMBOL(netif_set_xps_queue);
2808 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2810 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2812 /* Unbind any subordinate channels */
2813 while (txq-- != &dev->_tx[0]) {
2815 netdev_unbind_sb_channel(dev, txq->sb_dev);
2819 void netdev_reset_tc(struct net_device *dev)
2822 netif_reset_xps_queues_gt(dev, 0);
2824 netdev_unbind_all_sb_channels(dev);
2826 /* Reset TC configuration of device */
2828 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2829 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2831 EXPORT_SYMBOL(netdev_reset_tc);
2833 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2835 if (tc >= dev->num_tc)
2839 netif_reset_xps_queues(dev, offset, count);
2841 dev->tc_to_txq[tc].count = count;
2842 dev->tc_to_txq[tc].offset = offset;
2845 EXPORT_SYMBOL(netdev_set_tc_queue);
2847 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2849 if (num_tc > TC_MAX_QUEUE)
2853 netif_reset_xps_queues_gt(dev, 0);
2855 netdev_unbind_all_sb_channels(dev);
2857 dev->num_tc = num_tc;
2860 EXPORT_SYMBOL(netdev_set_num_tc);
2862 void netdev_unbind_sb_channel(struct net_device *dev,
2863 struct net_device *sb_dev)
2865 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2868 netif_reset_xps_queues_gt(sb_dev, 0);
2870 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2871 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2873 while (txq-- != &dev->_tx[0]) {
2874 if (txq->sb_dev == sb_dev)
2878 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2880 int netdev_bind_sb_channel_queue(struct net_device *dev,
2881 struct net_device *sb_dev,
2882 u8 tc, u16 count, u16 offset)
2884 /* Make certain the sb_dev and dev are already configured */
2885 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2888 /* We cannot hand out queues we don't have */
2889 if ((offset + count) > dev->real_num_tx_queues)
2892 /* Record the mapping */
2893 sb_dev->tc_to_txq[tc].count = count;
2894 sb_dev->tc_to_txq[tc].offset = offset;
2896 /* Provide a way for Tx queue to find the tc_to_txq map or
2897 * XPS map for itself.
2900 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2904 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2906 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2908 /* Do not use a multiqueue device to represent a subordinate channel */
2909 if (netif_is_multiqueue(dev))
2912 /* We allow channels 1 - 32767 to be used for subordinate channels.
2913 * Channel 0 is meant to be "native" mode and used only to represent
2914 * the main root device. We allow writing 0 to reset the device back
2915 * to normal mode after being used as a subordinate channel.
2917 if (channel > S16_MAX)
2920 dev->num_tc = -channel;
2924 EXPORT_SYMBOL(netdev_set_sb_channel);
2927 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2928 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2930 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2935 disabling = txq < dev->real_num_tx_queues;
2937 if (txq < 1 || txq > dev->num_tx_queues)
2940 if (dev->reg_state == NETREG_REGISTERED ||
2941 dev->reg_state == NETREG_UNREGISTERING) {
2944 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2950 netif_setup_tc(dev, txq);
2952 dev_qdisc_change_real_num_tx(dev, txq);
2954 dev->real_num_tx_queues = txq;
2958 qdisc_reset_all_tx_gt(dev, txq);
2960 netif_reset_xps_queues_gt(dev, txq);
2964 dev->real_num_tx_queues = txq;
2969 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2973 * netif_set_real_num_rx_queues - set actual number of RX queues used
2974 * @dev: Network device
2975 * @rxq: Actual number of RX queues
2977 * This must be called either with the rtnl_lock held or before
2978 * registration of the net device. Returns 0 on success, or a
2979 * negative error code. If called before registration, it always
2982 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2986 if (rxq < 1 || rxq > dev->num_rx_queues)
2989 if (dev->reg_state == NETREG_REGISTERED) {
2992 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2998 dev->real_num_rx_queues = rxq;
3001 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3005 * netif_set_real_num_queues - set actual number of RX and TX queues used
3006 * @dev: Network device
3007 * @txq: Actual number of TX queues
3008 * @rxq: Actual number of RX queues
3010 * Set the real number of both TX and RX queues.
3011 * Does nothing if the number of queues is already correct.
3013 int netif_set_real_num_queues(struct net_device *dev,
3014 unsigned int txq, unsigned int rxq)
3016 unsigned int old_rxq = dev->real_num_rx_queues;
3019 if (txq < 1 || txq > dev->num_tx_queues ||
3020 rxq < 1 || rxq > dev->num_rx_queues)
3023 /* Start from increases, so the error path only does decreases -
3024 * decreases can't fail.
3026 if (rxq > dev->real_num_rx_queues) {
3027 err = netif_set_real_num_rx_queues(dev, rxq);
3031 if (txq > dev->real_num_tx_queues) {
3032 err = netif_set_real_num_tx_queues(dev, txq);
3036 if (rxq < dev->real_num_rx_queues)
3037 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3038 if (txq < dev->real_num_tx_queues)
3039 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3043 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3046 EXPORT_SYMBOL(netif_set_real_num_queues);
3049 * netif_set_tso_max_size() - set the max size of TSO frames supported
3050 * @dev: netdev to update
3051 * @size: max skb->len of a TSO frame
3053 * Set the limit on the size of TSO super-frames the device can handle.
3054 * Unless explicitly set the stack will assume the value of
3055 * %GSO_LEGACY_MAX_SIZE.
3057 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3059 dev->tso_max_size = min(GSO_MAX_SIZE, size);
3060 if (size < READ_ONCE(dev->gso_max_size))
3061 netif_set_gso_max_size(dev, size);
3062 if (size < READ_ONCE(dev->gso_ipv4_max_size))
3063 netif_set_gso_ipv4_max_size(dev, size);
3065 EXPORT_SYMBOL(netif_set_tso_max_size);
3068 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3069 * @dev: netdev to update
3070 * @segs: max number of TCP segments
3072 * Set the limit on the number of TCP segments the device can generate from
3073 * a single TSO super-frame.
3074 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3076 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3078 dev->tso_max_segs = segs;
3079 if (segs < READ_ONCE(dev->gso_max_segs))
3080 netif_set_gso_max_segs(dev, segs);
3082 EXPORT_SYMBOL(netif_set_tso_max_segs);
3085 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3086 * @to: netdev to update
3087 * @from: netdev from which to copy the limits
3089 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3091 netif_set_tso_max_size(to, from->tso_max_size);
3092 netif_set_tso_max_segs(to, from->tso_max_segs);
3094 EXPORT_SYMBOL(netif_inherit_tso_max);
3097 * netif_get_num_default_rss_queues - default number of RSS queues
3099 * Default value is the number of physical cores if there are only 1 or 2, or
3100 * divided by 2 if there are more.
3102 int netif_get_num_default_rss_queues(void)
3107 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3110 cpumask_copy(cpus, cpu_online_mask);
3111 for_each_cpu(cpu, cpus) {
3113 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3115 free_cpumask_var(cpus);
3117 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3119 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3121 static void __netif_reschedule(struct Qdisc *q)
3123 struct softnet_data *sd;
3124 unsigned long flags;
3126 local_irq_save(flags);
3127 sd = this_cpu_ptr(&softnet_data);
3128 q->next_sched = NULL;
3129 *sd->output_queue_tailp = q;
3130 sd->output_queue_tailp = &q->next_sched;
3131 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3132 local_irq_restore(flags);
3135 void __netif_schedule(struct Qdisc *q)
3137 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3138 __netif_reschedule(q);
3140 EXPORT_SYMBOL(__netif_schedule);
3142 struct dev_kfree_skb_cb {
3143 enum skb_drop_reason reason;
3146 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3148 return (struct dev_kfree_skb_cb *)skb->cb;
3151 void netif_schedule_queue(struct netdev_queue *txq)
3154 if (!netif_xmit_stopped(txq)) {
3155 struct Qdisc *q = rcu_dereference(txq->qdisc);
3157 __netif_schedule(q);
3161 EXPORT_SYMBOL(netif_schedule_queue);
3163 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3165 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3169 q = rcu_dereference(dev_queue->qdisc);
3170 __netif_schedule(q);
3174 EXPORT_SYMBOL(netif_tx_wake_queue);
3176 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3178 unsigned long flags;
3183 if (likely(refcount_read(&skb->users) == 1)) {
3185 refcount_set(&skb->users, 0);
3186 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3189 get_kfree_skb_cb(skb)->reason = reason;
3190 local_irq_save(flags);
3191 skb->next = __this_cpu_read(softnet_data.completion_queue);
3192 __this_cpu_write(softnet_data.completion_queue, skb);
3193 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3194 local_irq_restore(flags);
3196 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3198 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3200 if (in_hardirq() || irqs_disabled())
3201 dev_kfree_skb_irq_reason(skb, reason);
3203 kfree_skb_reason(skb, reason);
3205 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3209 * netif_device_detach - mark device as removed
3210 * @dev: network device
3212 * Mark device as removed from system and therefore no longer available.
3214 void netif_device_detach(struct net_device *dev)
3216 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3217 netif_running(dev)) {
3218 netif_tx_stop_all_queues(dev);
3221 EXPORT_SYMBOL(netif_device_detach);
3224 * netif_device_attach - mark device as attached
3225 * @dev: network device
3227 * Mark device as attached from system and restart if needed.
3229 void netif_device_attach(struct net_device *dev)
3231 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3232 netif_running(dev)) {
3233 netif_tx_wake_all_queues(dev);
3234 __netdev_watchdog_up(dev);
3237 EXPORT_SYMBOL(netif_device_attach);
3240 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3241 * to be used as a distribution range.
3243 static u16 skb_tx_hash(const struct net_device *dev,
3244 const struct net_device *sb_dev,
3245 struct sk_buff *skb)
3249 u16 qcount = dev->real_num_tx_queues;
3252 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3254 qoffset = sb_dev->tc_to_txq[tc].offset;
3255 qcount = sb_dev->tc_to_txq[tc].count;
3256 if (unlikely(!qcount)) {
3257 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3258 sb_dev->name, qoffset, tc);
3260 qcount = dev->real_num_tx_queues;
3264 if (skb_rx_queue_recorded(skb)) {
3265 DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3266 hash = skb_get_rx_queue(skb);
3267 if (hash >= qoffset)
3269 while (unlikely(hash >= qcount))
3271 return hash + qoffset;
3274 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3277 void skb_warn_bad_offload(const struct sk_buff *skb)
3279 static const netdev_features_t null_features;
3280 struct net_device *dev = skb->dev;
3281 const char *name = "";
3283 if (!net_ratelimit())
3287 if (dev->dev.parent)
3288 name = dev_driver_string(dev->dev.parent);
3290 name = netdev_name(dev);
3292 skb_dump(KERN_WARNING, skb, false);
3293 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3294 name, dev ? &dev->features : &null_features,
3295 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3299 * Invalidate hardware checksum when packet is to be mangled, and
3300 * complete checksum manually on outgoing path.
3302 int skb_checksum_help(struct sk_buff *skb)
3305 int ret = 0, offset;
3307 if (skb->ip_summed == CHECKSUM_COMPLETE)
3308 goto out_set_summed;
3310 if (unlikely(skb_is_gso(skb))) {
3311 skb_warn_bad_offload(skb);
3315 if (!skb_frags_readable(skb)) {
3319 /* Before computing a checksum, we should make sure no frag could
3320 * be modified by an external entity : checksum could be wrong.
3322 if (skb_has_shared_frag(skb)) {
3323 ret = __skb_linearize(skb);
3328 offset = skb_checksum_start_offset(skb);
3330 if (unlikely(offset >= skb_headlen(skb))) {
3331 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3332 WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
3333 offset, skb_headlen(skb));
3336 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3338 offset += skb->csum_offset;
3339 if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
3340 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3341 WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
3342 offset + sizeof(__sum16), skb_headlen(skb));
3345 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3349 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3351 skb->ip_summed = CHECKSUM_NONE;
3355 EXPORT_SYMBOL(skb_checksum_help);
3357 int skb_crc32c_csum_help(struct sk_buff *skb)
3360 int ret = 0, offset, start;
3362 if (skb->ip_summed != CHECKSUM_PARTIAL)
3365 if (unlikely(skb_is_gso(skb)))
3368 /* Before computing a checksum, we should make sure no frag could
3369 * be modified by an external entity : checksum could be wrong.
3371 if (unlikely(skb_has_shared_frag(skb))) {
3372 ret = __skb_linearize(skb);
3376 start = skb_checksum_start_offset(skb);
3377 offset = start + offsetof(struct sctphdr, checksum);
3378 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3383 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3387 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3388 skb->len - start, ~(__u32)0,
3390 *(__le32 *)(skb->data + offset) = crc32c_csum;
3391 skb_reset_csum_not_inet(skb);
3395 EXPORT_SYMBOL(skb_crc32c_csum_help);
3397 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3399 __be16 type = skb->protocol;
3401 /* Tunnel gso handlers can set protocol to ethernet. */
3402 if (type == htons(ETH_P_TEB)) {
3405 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3408 eth = (struct ethhdr *)skb->data;
3409 type = eth->h_proto;
3412 return vlan_get_protocol_and_depth(skb, type, depth);
3416 /* Take action when hardware reception checksum errors are detected. */
3418 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3420 netdev_err(dev, "hw csum failure\n");
3421 skb_dump(KERN_ERR, skb, true);
3425 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3427 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3429 EXPORT_SYMBOL(netdev_rx_csum_fault);
3432 /* XXX: check that highmem exists at all on the given machine. */
3433 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3435 #ifdef CONFIG_HIGHMEM
3438 if (!(dev->features & NETIF_F_HIGHDMA)) {
3439 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3440 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3441 struct page *page = skb_frag_page(frag);
3443 if (page && PageHighMem(page))
3451 /* If MPLS offload request, verify we are testing hardware MPLS features
3452 * instead of standard features for the netdev.
3454 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3455 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3456 netdev_features_t features,
3459 if (eth_p_mpls(type))
3460 features &= skb->dev->mpls_features;
3465 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3466 netdev_features_t features,
3473 static netdev_features_t harmonize_features(struct sk_buff *skb,
3474 netdev_features_t features)
3478 type = skb_network_protocol(skb, NULL);
3479 features = net_mpls_features(skb, features, type);
3481 if (skb->ip_summed != CHECKSUM_NONE &&
3482 !can_checksum_protocol(features, type)) {
3483 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3485 if (illegal_highdma(skb->dev, skb))
3486 features &= ~NETIF_F_SG;
3491 netdev_features_t passthru_features_check(struct sk_buff *skb,
3492 struct net_device *dev,
3493 netdev_features_t features)
3497 EXPORT_SYMBOL(passthru_features_check);
3499 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3500 struct net_device *dev,
3501 netdev_features_t features)
3503 return vlan_features_check(skb, features);
3506 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3507 struct net_device *dev,
3508 netdev_features_t features)
3510 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3512 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3513 return features & ~NETIF_F_GSO_MASK;
3515 if (unlikely(skb->len >= READ_ONCE(dev->gso_max_size)))
3516 return features & ~NETIF_F_GSO_MASK;
3518 if (!skb_shinfo(skb)->gso_type) {
3519 skb_warn_bad_offload(skb);
3520 return features & ~NETIF_F_GSO_MASK;
3523 /* Support for GSO partial features requires software
3524 * intervention before we can actually process the packets
3525 * so we need to strip support for any partial features now
3526 * and we can pull them back in after we have partially
3527 * segmented the frame.
3529 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3530 features &= ~dev->gso_partial_features;
3532 /* Make sure to clear the IPv4 ID mangling feature if the
3533 * IPv4 header has the potential to be fragmented.
3535 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3536 struct iphdr *iph = skb->encapsulation ?
3537 inner_ip_hdr(skb) : ip_hdr(skb);
3539 if (!(iph->frag_off & htons(IP_DF)))
3540 features &= ~NETIF_F_TSO_MANGLEID;
3546 netdev_features_t netif_skb_features(struct sk_buff *skb)
3548 struct net_device *dev = skb->dev;
3549 netdev_features_t features = dev->features;
3551 if (skb_is_gso(skb))
3552 features = gso_features_check(skb, dev, features);
3554 /* If encapsulation offload request, verify we are testing
3555 * hardware encapsulation features instead of standard
3556 * features for the netdev
3558 if (skb->encapsulation)
3559 features &= dev->hw_enc_features;
3561 if (skb_vlan_tagged(skb))
3562 features = netdev_intersect_features(features,
3563 dev->vlan_features |
3564 NETIF_F_HW_VLAN_CTAG_TX |
3565 NETIF_F_HW_VLAN_STAG_TX);
3567 if (dev->netdev_ops->ndo_features_check)
3568 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3571 features &= dflt_features_check(skb, dev, features);
3573 return harmonize_features(skb, features);
3575 EXPORT_SYMBOL(netif_skb_features);
3577 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3578 struct netdev_queue *txq, bool more)
3583 if (dev_nit_active(dev))
3584 dev_queue_xmit_nit(skb, dev);
3587 trace_net_dev_start_xmit(skb, dev);
3588 rc = netdev_start_xmit(skb, dev, txq, more);
3589 trace_net_dev_xmit(skb, rc, dev, len);
3594 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3595 struct netdev_queue *txq, int *ret)
3597 struct sk_buff *skb = first;
3598 int rc = NETDEV_TX_OK;
3601 struct sk_buff *next = skb->next;
3603 skb_mark_not_on_list(skb);
3604 rc = xmit_one(skb, dev, txq, next != NULL);
3605 if (unlikely(!dev_xmit_complete(rc))) {
3611 if (netif_tx_queue_stopped(txq) && skb) {
3612 rc = NETDEV_TX_BUSY;
3622 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3623 netdev_features_t features)
3625 if (skb_vlan_tag_present(skb) &&
3626 !vlan_hw_offload_capable(features, skb->vlan_proto))
3627 skb = __vlan_hwaccel_push_inside(skb);
3631 int skb_csum_hwoffload_help(struct sk_buff *skb,
3632 const netdev_features_t features)
3634 if (unlikely(skb_csum_is_sctp(skb)))
3635 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3636 skb_crc32c_csum_help(skb);
3638 if (features & NETIF_F_HW_CSUM)
3641 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3642 switch (skb->csum_offset) {
3643 case offsetof(struct tcphdr, check):
3644 case offsetof(struct udphdr, check):
3649 return skb_checksum_help(skb);
3651 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3653 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3655 netdev_features_t features;
3657 features = netif_skb_features(skb);
3658 skb = validate_xmit_vlan(skb, features);
3662 skb = sk_validate_xmit_skb(skb, dev);
3666 if (netif_needs_gso(skb, features)) {
3667 struct sk_buff *segs;
3669 segs = skb_gso_segment(skb, features);
3677 if (skb_needs_linearize(skb, features) &&
3678 __skb_linearize(skb))
3681 /* If packet is not checksummed and device does not
3682 * support checksumming for this protocol, complete
3683 * checksumming here.
3685 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3686 if (skb->encapsulation)
3687 skb_set_inner_transport_header(skb,
3688 skb_checksum_start_offset(skb));
3690 skb_set_transport_header(skb,
3691 skb_checksum_start_offset(skb));
3692 if (skb_csum_hwoffload_help(skb, features))
3697 skb = validate_xmit_xfrm(skb, features, again);
3704 dev_core_stats_tx_dropped_inc(dev);
3708 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3710 struct sk_buff *next, *head = NULL, *tail;
3712 for (; skb != NULL; skb = next) {
3714 skb_mark_not_on_list(skb);
3716 /* in case skb won't be segmented, point to itself */
3719 skb = validate_xmit_skb(skb, dev, again);
3727 /* If skb was segmented, skb->prev points to
3728 * the last segment. If not, it still contains skb.
3734 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3736 static void qdisc_pkt_len_init(struct sk_buff *skb)
3738 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3740 qdisc_skb_cb(skb)->pkt_len = skb->len;
3742 /* To get more precise estimation of bytes sent on wire,
3743 * we add to pkt_len the headers size of all segments
3745 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3746 u16 gso_segs = shinfo->gso_segs;
3747 unsigned int hdr_len;
3749 /* mac layer + network layer */
3750 hdr_len = skb_transport_offset(skb);
3752 /* + transport layer */
3753 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3754 const struct tcphdr *th;
3755 struct tcphdr _tcphdr;
3757 th = skb_header_pointer(skb, hdr_len,
3758 sizeof(_tcphdr), &_tcphdr);
3760 hdr_len += __tcp_hdrlen(th);
3762 struct udphdr _udphdr;
3764 if (skb_header_pointer(skb, hdr_len,
3765 sizeof(_udphdr), &_udphdr))
3766 hdr_len += sizeof(struct udphdr);
3769 if (shinfo->gso_type & SKB_GSO_DODGY)
3770 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3773 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3777 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3778 struct sk_buff **to_free,
3779 struct netdev_queue *txq)
3783 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3784 if (rc == NET_XMIT_SUCCESS)
3785 trace_qdisc_enqueue(q, txq, skb);
3789 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3790 struct net_device *dev,
3791 struct netdev_queue *txq)
3793 spinlock_t *root_lock = qdisc_lock(q);
3794 struct sk_buff *to_free = NULL;
3798 qdisc_calculate_pkt_len(skb, q);
3800 tcf_set_drop_reason(skb, SKB_DROP_REASON_QDISC_DROP);
3802 if (q->flags & TCQ_F_NOLOCK) {
3803 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3804 qdisc_run_begin(q)) {
3805 /* Retest nolock_qdisc_is_empty() within the protection
3806 * of q->seqlock to protect from racing with requeuing.
3808 if (unlikely(!nolock_qdisc_is_empty(q))) {
3809 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3816 qdisc_bstats_cpu_update(q, skb);
3817 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3818 !nolock_qdisc_is_empty(q))
3822 return NET_XMIT_SUCCESS;
3825 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3829 if (unlikely(to_free))
3830 kfree_skb_list_reason(to_free,
3831 tcf_get_drop_reason(to_free));
3835 if (unlikely(READ_ONCE(q->owner) == smp_processor_id())) {
3836 kfree_skb_reason(skb, SKB_DROP_REASON_TC_RECLASSIFY_LOOP);
3837 return NET_XMIT_DROP;
3840 * Heuristic to force contended enqueues to serialize on a
3841 * separate lock before trying to get qdisc main lock.
3842 * This permits qdisc->running owner to get the lock more
3843 * often and dequeue packets faster.
3844 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3845 * and then other tasks will only enqueue packets. The packets will be
3846 * sent after the qdisc owner is scheduled again. To prevent this
3847 * scenario the task always serialize on the lock.
3849 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3850 if (unlikely(contended))
3851 spin_lock(&q->busylock);
3853 spin_lock(root_lock);
3854 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3855 __qdisc_drop(skb, &to_free);
3857 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3858 qdisc_run_begin(q)) {
3860 * This is a work-conserving queue; there are no old skbs
3861 * waiting to be sent out; and the qdisc is not running -
3862 * xmit the skb directly.
3865 qdisc_bstats_update(q, skb);
3867 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3868 if (unlikely(contended)) {
3869 spin_unlock(&q->busylock);
3876 rc = NET_XMIT_SUCCESS;
3878 WRITE_ONCE(q->owner, smp_processor_id());
3879 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3880 WRITE_ONCE(q->owner, -1);
3881 if (qdisc_run_begin(q)) {
3882 if (unlikely(contended)) {
3883 spin_unlock(&q->busylock);
3890 spin_unlock(root_lock);
3891 if (unlikely(to_free))
3892 kfree_skb_list_reason(to_free,
3893 tcf_get_drop_reason(to_free));
3894 if (unlikely(contended))
3895 spin_unlock(&q->busylock);
3899 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3900 static void skb_update_prio(struct sk_buff *skb)
3902 const struct netprio_map *map;
3903 const struct sock *sk;
3904 unsigned int prioidx;
3908 map = rcu_dereference_bh(skb->dev->priomap);
3911 sk = skb_to_full_sk(skb);
3915 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3917 if (prioidx < map->priomap_len)
3918 skb->priority = map->priomap[prioidx];
3921 #define skb_update_prio(skb)
3925 * dev_loopback_xmit - loop back @skb
3926 * @net: network namespace this loopback is happening in
3927 * @sk: sk needed to be a netfilter okfn
3928 * @skb: buffer to transmit
3930 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3932 skb_reset_mac_header(skb);
3933 __skb_pull(skb, skb_network_offset(skb));
3934 skb->pkt_type = PACKET_LOOPBACK;
3935 if (skb->ip_summed == CHECKSUM_NONE)
3936 skb->ip_summed = CHECKSUM_UNNECESSARY;
3937 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
3942 EXPORT_SYMBOL(dev_loopback_xmit);
3944 #ifdef CONFIG_NET_EGRESS
3945 static struct netdev_queue *
3946 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
3948 int qm = skb_get_queue_mapping(skb);
3950 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
3953 #ifndef CONFIG_PREEMPT_RT
3954 static bool netdev_xmit_txqueue_skipped(void)
3956 return __this_cpu_read(softnet_data.xmit.skip_txqueue);
3959 void netdev_xmit_skip_txqueue(bool skip)
3961 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
3963 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3966 static bool netdev_xmit_txqueue_skipped(void)
3968 return current->net_xmit.skip_txqueue;
3971 void netdev_xmit_skip_txqueue(bool skip)
3973 current->net_xmit.skip_txqueue = skip;
3975 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3977 #endif /* CONFIG_NET_EGRESS */
3979 #ifdef CONFIG_NET_XGRESS
3980 static int tc_run(struct tcx_entry *entry, struct sk_buff *skb,
3981 enum skb_drop_reason *drop_reason)
3983 int ret = TC_ACT_UNSPEC;
3984 #ifdef CONFIG_NET_CLS_ACT
3985 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
3986 struct tcf_result res;
3991 if (static_branch_unlikely(&tcf_bypass_check_needed_key)) {
3992 if (tcf_block_bypass_sw(miniq->block))
3996 tc_skb_cb(skb)->mru = 0;
3997 tc_skb_cb(skb)->post_ct = false;
3998 tcf_set_drop_reason(skb, *drop_reason);
4000 mini_qdisc_bstats_cpu_update(miniq, skb);
4001 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
4002 /* Only tcf related quirks below. */
4005 *drop_reason = tcf_get_drop_reason(skb);
4006 mini_qdisc_qstats_cpu_drop(miniq);
4009 case TC_ACT_RECLASSIFY:
4010 skb->tc_index = TC_H_MIN(res.classid);
4013 #endif /* CONFIG_NET_CLS_ACT */
4017 static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
4021 static_branch_inc(&tcx_needed_key);
4026 static_branch_dec(&tcx_needed_key);
4029 static __always_inline enum tcx_action_base
4030 tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
4031 const bool needs_mac)
4033 const struct bpf_mprog_fp *fp;
4034 const struct bpf_prog *prog;
4038 __skb_push(skb, skb->mac_len);
4039 bpf_mprog_foreach_prog(entry, fp, prog) {
4040 bpf_compute_data_pointers(skb);
4041 ret = bpf_prog_run(prog, skb);
4042 if (ret != TCX_NEXT)
4046 __skb_pull(skb, skb->mac_len);
4047 return tcx_action_code(skb, ret);
4050 static __always_inline struct sk_buff *
4051 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4052 struct net_device *orig_dev, bool *another)
4054 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
4055 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_INGRESS;
4056 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
4062 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
4064 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4068 qdisc_skb_cb(skb)->pkt_len = skb->len;
4069 tcx_set_ingress(skb, true);
4071 if (static_branch_unlikely(&tcx_needed_key)) {
4072 sch_ret = tcx_run(entry, skb, true);
4073 if (sch_ret != TC_ACT_UNSPEC)
4074 goto ingress_verdict;
4076 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
4079 case TC_ACT_REDIRECT:
4080 /* skb_mac_header check was done by BPF, so we can safely
4081 * push the L2 header back before redirecting to another
4084 __skb_push(skb, skb->mac_len);
4085 if (skb_do_redirect(skb) == -EAGAIN) {
4086 __skb_pull(skb, skb->mac_len);
4090 *ret = NET_RX_SUCCESS;
4091 bpf_net_ctx_clear(bpf_net_ctx);
4094 kfree_skb_reason(skb, drop_reason);
4096 bpf_net_ctx_clear(bpf_net_ctx);
4098 /* used by tc_run */
4104 case TC_ACT_CONSUMED:
4105 *ret = NET_RX_SUCCESS;
4106 bpf_net_ctx_clear(bpf_net_ctx);
4109 bpf_net_ctx_clear(bpf_net_ctx);
4114 static __always_inline struct sk_buff *
4115 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4117 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
4118 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_EGRESS;
4119 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
4125 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
4127 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
4128 * already set by the caller.
4130 if (static_branch_unlikely(&tcx_needed_key)) {
4131 sch_ret = tcx_run(entry, skb, false);
4132 if (sch_ret != TC_ACT_UNSPEC)
4133 goto egress_verdict;
4135 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
4138 case TC_ACT_REDIRECT:
4139 /* No need to push/pop skb's mac_header here on egress! */
4140 skb_do_redirect(skb);
4141 *ret = NET_XMIT_SUCCESS;
4142 bpf_net_ctx_clear(bpf_net_ctx);
4145 kfree_skb_reason(skb, drop_reason);
4146 *ret = NET_XMIT_DROP;
4147 bpf_net_ctx_clear(bpf_net_ctx);
4149 /* used by tc_run */
4155 case TC_ACT_CONSUMED:
4156 *ret = NET_XMIT_SUCCESS;
4157 bpf_net_ctx_clear(bpf_net_ctx);
4160 bpf_net_ctx_clear(bpf_net_ctx);
4165 static __always_inline struct sk_buff *
4166 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4167 struct net_device *orig_dev, bool *another)
4172 static __always_inline struct sk_buff *
4173 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4177 #endif /* CONFIG_NET_XGRESS */
4180 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
4181 struct xps_dev_maps *dev_maps, unsigned int tci)
4183 int tc = netdev_get_prio_tc_map(dev, skb->priority);
4184 struct xps_map *map;
4185 int queue_index = -1;
4187 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
4190 tci *= dev_maps->num_tc;
4193 map = rcu_dereference(dev_maps->attr_map[tci]);
4196 queue_index = map->queues[0];
4198 queue_index = map->queues[reciprocal_scale(
4199 skb_get_hash(skb), map->len)];
4200 if (unlikely(queue_index >= dev->real_num_tx_queues))
4207 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
4208 struct sk_buff *skb)
4211 struct xps_dev_maps *dev_maps;
4212 struct sock *sk = skb->sk;
4213 int queue_index = -1;
4215 if (!static_key_false(&xps_needed))
4219 if (!static_key_false(&xps_rxqs_needed))
4222 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
4224 int tci = sk_rx_queue_get(sk);
4227 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4232 if (queue_index < 0) {
4233 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
4235 unsigned int tci = skb->sender_cpu - 1;
4237 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4249 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
4250 struct net_device *sb_dev)
4254 EXPORT_SYMBOL(dev_pick_tx_zero);
4256 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4257 struct net_device *sb_dev)
4259 struct sock *sk = skb->sk;
4260 int queue_index = sk_tx_queue_get(sk);
4262 sb_dev = sb_dev ? : dev;
4264 if (queue_index < 0 || skb->ooo_okay ||
4265 queue_index >= dev->real_num_tx_queues) {
4266 int new_index = get_xps_queue(dev, sb_dev, skb);
4269 new_index = skb_tx_hash(dev, sb_dev, skb);
4271 if (queue_index != new_index && sk &&
4273 rcu_access_pointer(sk->sk_dst_cache))
4274 sk_tx_queue_set(sk, new_index);
4276 queue_index = new_index;
4281 EXPORT_SYMBOL(netdev_pick_tx);
4283 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4284 struct sk_buff *skb,
4285 struct net_device *sb_dev)
4287 int queue_index = 0;
4290 u32 sender_cpu = skb->sender_cpu - 1;
4292 if (sender_cpu >= (u32)NR_CPUS)
4293 skb->sender_cpu = raw_smp_processor_id() + 1;
4296 if (dev->real_num_tx_queues != 1) {
4297 const struct net_device_ops *ops = dev->netdev_ops;
4299 if (ops->ndo_select_queue)
4300 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4302 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4304 queue_index = netdev_cap_txqueue(dev, queue_index);
4307 skb_set_queue_mapping(skb, queue_index);
4308 return netdev_get_tx_queue(dev, queue_index);
4312 * __dev_queue_xmit() - transmit a buffer
4313 * @skb: buffer to transmit
4314 * @sb_dev: suboordinate device used for L2 forwarding offload
4316 * Queue a buffer for transmission to a network device. The caller must
4317 * have set the device and priority and built the buffer before calling
4318 * this function. The function can be called from an interrupt.
4320 * When calling this method, interrupts MUST be enabled. This is because
4321 * the BH enable code must have IRQs enabled so that it will not deadlock.
4323 * Regardless of the return value, the skb is consumed, so it is currently
4324 * difficult to retry a send to this method. (You can bump the ref count
4325 * before sending to hold a reference for retry if you are careful.)
4328 * * 0 - buffer successfully transmitted
4329 * * positive qdisc return code - NET_XMIT_DROP etc.
4330 * * negative errno - other errors
4332 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4334 struct net_device *dev = skb->dev;
4335 struct netdev_queue *txq = NULL;
4340 skb_reset_mac_header(skb);
4341 skb_assert_len(skb);
4343 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4344 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4346 /* Disable soft irqs for various locks below. Also
4347 * stops preemption for RCU.
4351 skb_update_prio(skb);
4353 qdisc_pkt_len_init(skb);
4354 tcx_set_ingress(skb, false);
4355 #ifdef CONFIG_NET_EGRESS
4356 if (static_branch_unlikely(&egress_needed_key)) {
4357 if (nf_hook_egress_active()) {
4358 skb = nf_hook_egress(skb, &rc, dev);
4363 netdev_xmit_skip_txqueue(false);
4365 nf_skip_egress(skb, true);
4366 skb = sch_handle_egress(skb, &rc, dev);
4369 nf_skip_egress(skb, false);
4371 if (netdev_xmit_txqueue_skipped())
4372 txq = netdev_tx_queue_mapping(dev, skb);
4375 /* If device/qdisc don't need skb->dst, release it right now while
4376 * its hot in this cpu cache.
4378 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4384 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4386 q = rcu_dereference_bh(txq->qdisc);
4388 trace_net_dev_queue(skb);
4390 rc = __dev_xmit_skb(skb, q, dev, txq);
4394 /* The device has no queue. Common case for software devices:
4395 * loopback, all the sorts of tunnels...
4397 * Really, it is unlikely that netif_tx_lock protection is necessary
4398 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4400 * However, it is possible, that they rely on protection
4403 * Check this and shot the lock. It is not prone from deadlocks.
4404 *Either shot noqueue qdisc, it is even simpler 8)
4406 if (dev->flags & IFF_UP) {
4407 int cpu = smp_processor_id(); /* ok because BHs are off */
4409 /* Other cpus might concurrently change txq->xmit_lock_owner
4410 * to -1 or to their cpu id, but not to our id.
4412 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4413 if (dev_xmit_recursion())
4414 goto recursion_alert;
4416 skb = validate_xmit_skb(skb, dev, &again);
4420 HARD_TX_LOCK(dev, txq, cpu);
4422 if (!netif_xmit_stopped(txq)) {
4423 dev_xmit_recursion_inc();
4424 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4425 dev_xmit_recursion_dec();
4426 if (dev_xmit_complete(rc)) {
4427 HARD_TX_UNLOCK(dev, txq);
4431 HARD_TX_UNLOCK(dev, txq);
4432 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4435 /* Recursion is detected! It is possible,
4439 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4445 rcu_read_unlock_bh();
4447 dev_core_stats_tx_dropped_inc(dev);
4448 kfree_skb_list(skb);
4451 rcu_read_unlock_bh();
4454 EXPORT_SYMBOL(__dev_queue_xmit);
4456 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4458 struct net_device *dev = skb->dev;
4459 struct sk_buff *orig_skb = skb;
4460 struct netdev_queue *txq;
4461 int ret = NETDEV_TX_BUSY;
4464 if (unlikely(!netif_running(dev) ||
4465 !netif_carrier_ok(dev)))
4468 skb = validate_xmit_skb_list(skb, dev, &again);
4469 if (skb != orig_skb)
4472 skb_set_queue_mapping(skb, queue_id);
4473 txq = skb_get_tx_queue(dev, skb);
4477 dev_xmit_recursion_inc();
4478 HARD_TX_LOCK(dev, txq, smp_processor_id());
4479 if (!netif_xmit_frozen_or_drv_stopped(txq))
4480 ret = netdev_start_xmit(skb, dev, txq, false);
4481 HARD_TX_UNLOCK(dev, txq);
4482 dev_xmit_recursion_dec();
4487 dev_core_stats_tx_dropped_inc(dev);
4488 kfree_skb_list(skb);
4489 return NET_XMIT_DROP;
4491 EXPORT_SYMBOL(__dev_direct_xmit);
4493 /*************************************************************************
4495 *************************************************************************/
4496 static DEFINE_PER_CPU(struct task_struct *, backlog_napi);
4498 int weight_p __read_mostly = 64; /* old backlog weight */
4499 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4500 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4502 /* Called with irq disabled */
4503 static inline void ____napi_schedule(struct softnet_data *sd,
4504 struct napi_struct *napi)
4506 struct task_struct *thread;
4508 lockdep_assert_irqs_disabled();
4510 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4511 /* Paired with smp_mb__before_atomic() in
4512 * napi_enable()/dev_set_threaded().
4513 * Use READ_ONCE() to guarantee a complete
4514 * read on napi->thread. Only call
4515 * wake_up_process() when it's not NULL.
4517 thread = READ_ONCE(napi->thread);
4519 if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi))
4520 goto use_local_napi;
4522 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4523 wake_up_process(thread);
4529 list_add_tail(&napi->poll_list, &sd->poll_list);
4530 WRITE_ONCE(napi->list_owner, smp_processor_id());
4531 /* If not called from net_rx_action()
4532 * we have to raise NET_RX_SOFTIRQ.
4534 if (!sd->in_net_rx_action)
4535 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4540 struct static_key_false rps_needed __read_mostly;
4541 EXPORT_SYMBOL(rps_needed);
4542 struct static_key_false rfs_needed __read_mostly;
4543 EXPORT_SYMBOL(rfs_needed);
4545 static struct rps_dev_flow *
4546 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4547 struct rps_dev_flow *rflow, u16 next_cpu)
4549 if (next_cpu < nr_cpu_ids) {
4551 #ifdef CONFIG_RFS_ACCEL
4552 struct netdev_rx_queue *rxqueue;
4553 struct rps_dev_flow_table *flow_table;
4554 struct rps_dev_flow *old_rflow;
4559 /* Should we steer this flow to a different hardware queue? */
4560 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4561 !(dev->features & NETIF_F_NTUPLE))
4563 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4564 if (rxq_index == skb_get_rx_queue(skb))
4567 rxqueue = dev->_rx + rxq_index;
4568 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4571 flow_id = skb_get_hash(skb) & flow_table->mask;
4572 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4573 rxq_index, flow_id);
4577 rflow = &flow_table->flows[flow_id];
4578 WRITE_ONCE(rflow->filter, rc);
4579 if (old_rflow->filter == rc)
4580 WRITE_ONCE(old_rflow->filter, RPS_NO_FILTER);
4583 head = READ_ONCE(per_cpu(softnet_data, next_cpu).input_queue_head);
4584 rps_input_queue_tail_save(&rflow->last_qtail, head);
4587 WRITE_ONCE(rflow->cpu, next_cpu);
4592 * get_rps_cpu is called from netif_receive_skb and returns the target
4593 * CPU from the RPS map of the receiving queue for a given skb.
4594 * rcu_read_lock must be held on entry.
4596 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4597 struct rps_dev_flow **rflowp)
4599 const struct rps_sock_flow_table *sock_flow_table;
4600 struct netdev_rx_queue *rxqueue = dev->_rx;
4601 struct rps_dev_flow_table *flow_table;
4602 struct rps_map *map;
4607 if (skb_rx_queue_recorded(skb)) {
4608 u16 index = skb_get_rx_queue(skb);
4610 if (unlikely(index >= dev->real_num_rx_queues)) {
4611 WARN_ONCE(dev->real_num_rx_queues > 1,
4612 "%s received packet on queue %u, but number "
4613 "of RX queues is %u\n",
4614 dev->name, index, dev->real_num_rx_queues);
4620 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4622 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4623 map = rcu_dereference(rxqueue->rps_map);
4624 if (!flow_table && !map)
4627 skb_reset_network_header(skb);
4628 hash = skb_get_hash(skb);
4632 sock_flow_table = rcu_dereference(net_hotdata.rps_sock_flow_table);
4633 if (flow_table && sock_flow_table) {
4634 struct rps_dev_flow *rflow;
4638 /* First check into global flow table if there is a match.
4639 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
4641 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
4642 if ((ident ^ hash) & ~net_hotdata.rps_cpu_mask)
4645 next_cpu = ident & net_hotdata.rps_cpu_mask;
4647 /* OK, now we know there is a match,
4648 * we can look at the local (per receive queue) flow table
4650 rflow = &flow_table->flows[hash & flow_table->mask];
4654 * If the desired CPU (where last recvmsg was done) is
4655 * different from current CPU (one in the rx-queue flow
4656 * table entry), switch if one of the following holds:
4657 * - Current CPU is unset (>= nr_cpu_ids).
4658 * - Current CPU is offline.
4659 * - The current CPU's queue tail has advanced beyond the
4660 * last packet that was enqueued using this table entry.
4661 * This guarantees that all previous packets for the flow
4662 * have been dequeued, thus preserving in order delivery.
4664 if (unlikely(tcpu != next_cpu) &&
4665 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4666 ((int)(READ_ONCE(per_cpu(softnet_data, tcpu).input_queue_head) -
4667 rflow->last_qtail)) >= 0)) {
4669 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4672 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4682 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4683 if (cpu_online(tcpu)) {
4693 #ifdef CONFIG_RFS_ACCEL
4696 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4697 * @dev: Device on which the filter was set
4698 * @rxq_index: RX queue index
4699 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4700 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4702 * Drivers that implement ndo_rx_flow_steer() should periodically call
4703 * this function for each installed filter and remove the filters for
4704 * which it returns %true.
4706 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4707 u32 flow_id, u16 filter_id)
4709 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4710 struct rps_dev_flow_table *flow_table;
4711 struct rps_dev_flow *rflow;
4716 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4717 if (flow_table && flow_id <= flow_table->mask) {
4718 rflow = &flow_table->flows[flow_id];
4719 cpu = READ_ONCE(rflow->cpu);
4720 if (READ_ONCE(rflow->filter) == filter_id && cpu < nr_cpu_ids &&
4721 ((int)(READ_ONCE(per_cpu(softnet_data, cpu).input_queue_head) -
4722 READ_ONCE(rflow->last_qtail)) <
4723 (int)(10 * flow_table->mask)))
4729 EXPORT_SYMBOL(rps_may_expire_flow);
4731 #endif /* CONFIG_RFS_ACCEL */
4733 /* Called from hardirq (IPI) context */
4734 static void rps_trigger_softirq(void *data)
4736 struct softnet_data *sd = data;
4738 ____napi_schedule(sd, &sd->backlog);
4742 #endif /* CONFIG_RPS */
4744 /* Called from hardirq (IPI) context */
4745 static void trigger_rx_softirq(void *data)
4747 struct softnet_data *sd = data;
4749 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4750 smp_store_release(&sd->defer_ipi_scheduled, 0);
4754 * After we queued a packet into sd->input_pkt_queue,
4755 * we need to make sure this queue is serviced soon.
4757 * - If this is another cpu queue, link it to our rps_ipi_list,
4758 * and make sure we will process rps_ipi_list from net_rx_action().
4760 * - If this is our own queue, NAPI schedule our backlog.
4761 * Note that this also raises NET_RX_SOFTIRQ.
4763 static void napi_schedule_rps(struct softnet_data *sd)
4765 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4769 if (use_backlog_threads()) {
4770 __napi_schedule_irqoff(&sd->backlog);
4774 sd->rps_ipi_next = mysd->rps_ipi_list;
4775 mysd->rps_ipi_list = sd;
4777 /* If not called from net_rx_action() or napi_threaded_poll()
4778 * we have to raise NET_RX_SOFTIRQ.
4780 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
4781 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4784 #endif /* CONFIG_RPS */
4785 __napi_schedule_irqoff(&mysd->backlog);
4788 void kick_defer_list_purge(struct softnet_data *sd, unsigned int cpu)
4790 unsigned long flags;
4792 if (use_backlog_threads()) {
4793 backlog_lock_irq_save(sd, &flags);
4795 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4796 __napi_schedule_irqoff(&sd->backlog);
4798 backlog_unlock_irq_restore(sd, &flags);
4800 } else if (!cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) {
4801 smp_call_function_single_async(cpu, &sd->defer_csd);
4805 #ifdef CONFIG_NET_FLOW_LIMIT
4806 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4809 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4811 #ifdef CONFIG_NET_FLOW_LIMIT
4812 struct sd_flow_limit *fl;
4813 struct softnet_data *sd;
4814 unsigned int old_flow, new_flow;
4816 if (qlen < (READ_ONCE(net_hotdata.max_backlog) >> 1))
4819 sd = this_cpu_ptr(&softnet_data);
4822 fl = rcu_dereference(sd->flow_limit);
4824 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4825 old_flow = fl->history[fl->history_head];
4826 fl->history[fl->history_head] = new_flow;
4829 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4831 if (likely(fl->buckets[old_flow]))
4832 fl->buckets[old_flow]--;
4834 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4846 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4847 * queue (may be a remote CPU queue).
4849 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4850 unsigned int *qtail)
4852 enum skb_drop_reason reason;
4853 struct softnet_data *sd;
4854 unsigned long flags;
4859 reason = SKB_DROP_REASON_DEV_READY;
4860 if (!netif_running(skb->dev))
4863 reason = SKB_DROP_REASON_CPU_BACKLOG;
4864 sd = &per_cpu(softnet_data, cpu);
4866 qlen = skb_queue_len_lockless(&sd->input_pkt_queue);
4867 max_backlog = READ_ONCE(net_hotdata.max_backlog);
4868 if (unlikely(qlen > max_backlog))
4869 goto cpu_backlog_drop;
4870 backlog_lock_irq_save(sd, &flags);
4871 qlen = skb_queue_len(&sd->input_pkt_queue);
4872 if (qlen <= max_backlog && !skb_flow_limit(skb, qlen)) {
4874 /* Schedule NAPI for backlog device. We can use
4875 * non atomic operation as we own the queue lock.
4877 if (!__test_and_set_bit(NAPI_STATE_SCHED,
4878 &sd->backlog.state))
4879 napi_schedule_rps(sd);
4881 __skb_queue_tail(&sd->input_pkt_queue, skb);
4882 tail = rps_input_queue_tail_incr(sd);
4883 backlog_unlock_irq_restore(sd, &flags);
4885 /* save the tail outside of the critical section */
4886 rps_input_queue_tail_save(qtail, tail);
4887 return NET_RX_SUCCESS;
4890 backlog_unlock_irq_restore(sd, &flags);
4893 atomic_inc(&sd->dropped);
4895 dev_core_stats_rx_dropped_inc(skb->dev);
4896 kfree_skb_reason(skb, reason);
4900 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4902 struct net_device *dev = skb->dev;
4903 struct netdev_rx_queue *rxqueue;
4907 if (skb_rx_queue_recorded(skb)) {
4908 u16 index = skb_get_rx_queue(skb);
4910 if (unlikely(index >= dev->real_num_rx_queues)) {
4911 WARN_ONCE(dev->real_num_rx_queues > 1,
4912 "%s received packet on queue %u, but number "
4913 "of RX queues is %u\n",
4914 dev->name, index, dev->real_num_rx_queues);
4916 return rxqueue; /* Return first rxqueue */
4923 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4924 struct bpf_prog *xdp_prog)
4926 void *orig_data, *orig_data_end, *hard_start;
4927 struct netdev_rx_queue *rxqueue;
4928 bool orig_bcast, orig_host;
4929 u32 mac_len, frame_sz;
4930 __be16 orig_eth_type;
4935 /* The XDP program wants to see the packet starting at the MAC
4938 mac_len = skb->data - skb_mac_header(skb);
4939 hard_start = skb->data - skb_headroom(skb);
4941 /* SKB "head" area always have tailroom for skb_shared_info */
4942 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4943 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4945 rxqueue = netif_get_rxqueue(skb);
4946 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4947 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4948 skb_headlen(skb) + mac_len, true);
4949 if (skb_is_nonlinear(skb)) {
4950 skb_shinfo(skb)->xdp_frags_size = skb->data_len;
4951 xdp_buff_set_frags_flag(xdp);
4953 xdp_buff_clear_frags_flag(xdp);
4956 orig_data_end = xdp->data_end;
4957 orig_data = xdp->data;
4958 eth = (struct ethhdr *)xdp->data;
4959 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4960 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4961 orig_eth_type = eth->h_proto;
4963 act = bpf_prog_run_xdp(xdp_prog, xdp);
4965 /* check if bpf_xdp_adjust_head was used */
4966 off = xdp->data - orig_data;
4969 __skb_pull(skb, off);
4971 __skb_push(skb, -off);
4973 skb->mac_header += off;
4974 skb_reset_network_header(skb);
4977 /* check if bpf_xdp_adjust_tail was used */
4978 off = xdp->data_end - orig_data_end;
4980 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4981 skb->len += off; /* positive on grow, negative on shrink */
4984 /* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers
4985 * (e.g. bpf_xdp_adjust_tail), we need to update data_len here.
4987 if (xdp_buff_has_frags(xdp))
4988 skb->data_len = skb_shinfo(skb)->xdp_frags_size;
4992 /* check if XDP changed eth hdr such SKB needs update */
4993 eth = (struct ethhdr *)xdp->data;
4994 if ((orig_eth_type != eth->h_proto) ||
4995 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4996 skb->dev->dev_addr)) ||
4997 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4998 __skb_push(skb, ETH_HLEN);
4999 skb->pkt_type = PACKET_HOST;
5000 skb->protocol = eth_type_trans(skb, skb->dev);
5003 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
5004 * before calling us again on redirect path. We do not call do_redirect
5005 * as we leave that up to the caller.
5007 * Caller is responsible for managing lifetime of skb (i.e. calling
5008 * kfree_skb in response to actions it cannot handle/XDP_DROP).
5013 __skb_push(skb, mac_len);
5016 metalen = xdp->data - xdp->data_meta;
5018 skb_metadata_set(skb, metalen);
5026 netif_skb_check_for_xdp(struct sk_buff **pskb, struct bpf_prog *prog)
5028 struct sk_buff *skb = *pskb;
5029 int err, hroom, troom;
5031 if (!skb_cow_data_for_xdp(this_cpu_read(system_page_pool), pskb, prog))
5034 /* In case we have to go down the path and also linearize,
5035 * then lets do the pskb_expand_head() work just once here.
5037 hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
5038 troom = skb->tail + skb->data_len - skb->end;
5039 err = pskb_expand_head(skb,
5040 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
5041 troom > 0 ? troom + 128 : 0, GFP_ATOMIC);
5045 return skb_linearize(skb);
5048 static u32 netif_receive_generic_xdp(struct sk_buff **pskb,
5049 struct xdp_buff *xdp,
5050 struct bpf_prog *xdp_prog)
5052 struct sk_buff *skb = *pskb;
5053 u32 mac_len, act = XDP_DROP;
5055 /* Reinjected packets coming from act_mirred or similar should
5056 * not get XDP generic processing.
5058 if (skb_is_redirected(skb))
5061 /* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM
5062 * bytes. This is the guarantee that also native XDP provides,
5063 * thus we need to do it here as well.
5065 mac_len = skb->data - skb_mac_header(skb);
5066 __skb_push(skb, mac_len);
5068 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
5069 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
5070 if (netif_skb_check_for_xdp(pskb, xdp_prog))
5074 __skb_pull(*pskb, mac_len);
5076 act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog);
5083 bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act);
5086 trace_xdp_exception((*pskb)->dev, xdp_prog, act);
5097 /* When doing generic XDP we have to bypass the qdisc layer and the
5098 * network taps in order to match in-driver-XDP behavior. This also means
5099 * that XDP packets are able to starve other packets going through a qdisc,
5100 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
5101 * queues, so they do not have this starvation issue.
5103 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
5105 struct net_device *dev = skb->dev;
5106 struct netdev_queue *txq;
5107 bool free_skb = true;
5110 txq = netdev_core_pick_tx(dev, skb, NULL);
5111 cpu = smp_processor_id();
5112 HARD_TX_LOCK(dev, txq, cpu);
5113 if (!netif_xmit_frozen_or_drv_stopped(txq)) {
5114 rc = netdev_start_xmit(skb, dev, txq, 0);
5115 if (dev_xmit_complete(rc))
5118 HARD_TX_UNLOCK(dev, txq);
5120 trace_xdp_exception(dev, xdp_prog, XDP_TX);
5121 dev_core_stats_tx_dropped_inc(dev);
5126 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
5128 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff **pskb)
5130 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
5133 struct xdp_buff xdp;
5137 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
5138 act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog);
5139 if (act != XDP_PASS) {
5142 err = xdp_do_generic_redirect((*pskb)->dev, *pskb,
5148 generic_xdp_tx(*pskb, xdp_prog);
5151 bpf_net_ctx_clear(bpf_net_ctx);
5154 bpf_net_ctx_clear(bpf_net_ctx);
5158 bpf_net_ctx_clear(bpf_net_ctx);
5159 kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP);
5162 EXPORT_SYMBOL_GPL(do_xdp_generic);
5164 static int netif_rx_internal(struct sk_buff *skb)
5168 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5170 trace_netif_rx(skb);
5173 if (static_branch_unlikely(&rps_needed)) {
5174 struct rps_dev_flow voidflow, *rflow = &voidflow;
5179 cpu = get_rps_cpu(skb->dev, skb, &rflow);
5181 cpu = smp_processor_id();
5183 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5191 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
5197 * __netif_rx - Slightly optimized version of netif_rx
5198 * @skb: buffer to post
5200 * This behaves as netif_rx except that it does not disable bottom halves.
5201 * As a result this function may only be invoked from the interrupt context
5202 * (either hard or soft interrupt).
5204 int __netif_rx(struct sk_buff *skb)
5208 lockdep_assert_once(hardirq_count() | softirq_count());
5210 trace_netif_rx_entry(skb);
5211 ret = netif_rx_internal(skb);
5212 trace_netif_rx_exit(ret);
5215 EXPORT_SYMBOL(__netif_rx);
5218 * netif_rx - post buffer to the network code
5219 * @skb: buffer to post
5221 * This function receives a packet from a device driver and queues it for
5222 * the upper (protocol) levels to process via the backlog NAPI device. It
5223 * always succeeds. The buffer may be dropped during processing for
5224 * congestion control or by the protocol layers.
5225 * The network buffer is passed via the backlog NAPI device. Modern NIC
5226 * driver should use NAPI and GRO.
5227 * This function can used from interrupt and from process context. The
5228 * caller from process context must not disable interrupts before invoking
5232 * NET_RX_SUCCESS (no congestion)
5233 * NET_RX_DROP (packet was dropped)
5236 int netif_rx(struct sk_buff *skb)
5238 bool need_bh_off = !(hardirq_count() | softirq_count());
5243 trace_netif_rx_entry(skb);
5244 ret = netif_rx_internal(skb);
5245 trace_netif_rx_exit(ret);
5250 EXPORT_SYMBOL(netif_rx);
5252 static __latent_entropy void net_tx_action(void)
5254 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
5256 if (sd->completion_queue) {
5257 struct sk_buff *clist;
5259 local_irq_disable();
5260 clist = sd->completion_queue;
5261 sd->completion_queue = NULL;
5265 struct sk_buff *skb = clist;
5267 clist = clist->next;
5269 WARN_ON(refcount_read(&skb->users));
5270 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
5271 trace_consume_skb(skb, net_tx_action);
5273 trace_kfree_skb(skb, net_tx_action,
5274 get_kfree_skb_cb(skb)->reason, NULL);
5276 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
5279 __napi_kfree_skb(skb,
5280 get_kfree_skb_cb(skb)->reason);
5284 if (sd->output_queue) {
5287 local_irq_disable();
5288 head = sd->output_queue;
5289 sd->output_queue = NULL;
5290 sd->output_queue_tailp = &sd->output_queue;
5296 struct Qdisc *q = head;
5297 spinlock_t *root_lock = NULL;
5299 head = head->next_sched;
5301 /* We need to make sure head->next_sched is read
5302 * before clearing __QDISC_STATE_SCHED
5304 smp_mb__before_atomic();
5306 if (!(q->flags & TCQ_F_NOLOCK)) {
5307 root_lock = qdisc_lock(q);
5308 spin_lock(root_lock);
5309 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
5311 /* There is a synchronize_net() between
5312 * STATE_DEACTIVATED flag being set and
5313 * qdisc_reset()/some_qdisc_is_busy() in
5314 * dev_deactivate(), so we can safely bail out
5315 * early here to avoid data race between
5316 * qdisc_deactivate() and some_qdisc_is_busy()
5317 * for lockless qdisc.
5319 clear_bit(__QDISC_STATE_SCHED, &q->state);
5323 clear_bit(__QDISC_STATE_SCHED, &q->state);
5326 spin_unlock(root_lock);
5332 xfrm_dev_backlog(sd);
5335 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5336 /* This hook is defined here for ATM LANE */
5337 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5338 unsigned char *addr) __read_mostly;
5339 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5343 * netdev_is_rx_handler_busy - check if receive handler is registered
5344 * @dev: device to check
5346 * Check if a receive handler is already registered for a given device.
5347 * Return true if there one.
5349 * The caller must hold the rtnl_mutex.
5351 bool netdev_is_rx_handler_busy(struct net_device *dev)
5354 return dev && rtnl_dereference(dev->rx_handler);
5356 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5359 * netdev_rx_handler_register - register receive handler
5360 * @dev: device to register a handler for
5361 * @rx_handler: receive handler to register
5362 * @rx_handler_data: data pointer that is used by rx handler
5364 * Register a receive handler for a device. This handler will then be
5365 * called from __netif_receive_skb. A negative errno code is returned
5368 * The caller must hold the rtnl_mutex.
5370 * For a general description of rx_handler, see enum rx_handler_result.
5372 int netdev_rx_handler_register(struct net_device *dev,
5373 rx_handler_func_t *rx_handler,
5374 void *rx_handler_data)
5376 if (netdev_is_rx_handler_busy(dev))
5379 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5382 /* Note: rx_handler_data must be set before rx_handler */
5383 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5384 rcu_assign_pointer(dev->rx_handler, rx_handler);
5388 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5391 * netdev_rx_handler_unregister - unregister receive handler
5392 * @dev: device to unregister a handler from
5394 * Unregister a receive handler from a device.
5396 * The caller must hold the rtnl_mutex.
5398 void netdev_rx_handler_unregister(struct net_device *dev)
5402 RCU_INIT_POINTER(dev->rx_handler, NULL);
5403 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5404 * section has a guarantee to see a non NULL rx_handler_data
5408 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5410 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5413 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5414 * the special handling of PFMEMALLOC skbs.
5416 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5418 switch (skb->protocol) {
5419 case htons(ETH_P_ARP):
5420 case htons(ETH_P_IP):
5421 case htons(ETH_P_IPV6):
5422 case htons(ETH_P_8021Q):
5423 case htons(ETH_P_8021AD):
5430 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5431 int *ret, struct net_device *orig_dev)
5433 if (nf_hook_ingress_active(skb)) {
5437 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5442 ingress_retval = nf_hook_ingress(skb);
5444 return ingress_retval;
5449 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5450 struct packet_type **ppt_prev)
5452 struct packet_type *ptype, *pt_prev;
5453 rx_handler_func_t *rx_handler;
5454 struct sk_buff *skb = *pskb;
5455 struct net_device *orig_dev;
5456 bool deliver_exact = false;
5457 int ret = NET_RX_DROP;
5460 net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5462 trace_netif_receive_skb(skb);
5464 orig_dev = skb->dev;
5466 skb_reset_network_header(skb);
5467 if (!skb_transport_header_was_set(skb))
5468 skb_reset_transport_header(skb);
5469 skb_reset_mac_len(skb);
5474 skb->skb_iif = skb->dev->ifindex;
5476 __this_cpu_inc(softnet_data.processed);
5478 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5482 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog),
5486 if (ret2 != XDP_PASS) {
5492 if (eth_type_vlan(skb->protocol)) {
5493 skb = skb_vlan_untag(skb);
5498 if (skb_skip_tc_classify(skb))
5504 list_for_each_entry_rcu(ptype, &net_hotdata.ptype_all, list) {
5506 ret = deliver_skb(skb, pt_prev, orig_dev);
5510 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5512 ret = deliver_skb(skb, pt_prev, orig_dev);
5517 #ifdef CONFIG_NET_INGRESS
5518 if (static_branch_unlikely(&ingress_needed_key)) {
5519 bool another = false;
5521 nf_skip_egress(skb, true);
5522 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5529 nf_skip_egress(skb, false);
5530 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5534 skb_reset_redirect(skb);
5536 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5539 if (skb_vlan_tag_present(skb)) {
5541 ret = deliver_skb(skb, pt_prev, orig_dev);
5544 if (vlan_do_receive(&skb))
5546 else if (unlikely(!skb))
5550 rx_handler = rcu_dereference(skb->dev->rx_handler);
5553 ret = deliver_skb(skb, pt_prev, orig_dev);
5556 switch (rx_handler(&skb)) {
5557 case RX_HANDLER_CONSUMED:
5558 ret = NET_RX_SUCCESS;
5560 case RX_HANDLER_ANOTHER:
5562 case RX_HANDLER_EXACT:
5563 deliver_exact = true;
5565 case RX_HANDLER_PASS:
5572 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5574 if (skb_vlan_tag_get_id(skb)) {
5575 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5578 skb->pkt_type = PACKET_OTHERHOST;
5579 } else if (eth_type_vlan(skb->protocol)) {
5580 /* Outer header is 802.1P with vlan 0, inner header is
5581 * 802.1Q or 802.1AD and vlan_do_receive() above could
5582 * not find vlan dev for vlan id 0.
5584 __vlan_hwaccel_clear_tag(skb);
5585 skb = skb_vlan_untag(skb);
5588 if (vlan_do_receive(&skb))
5589 /* After stripping off 802.1P header with vlan 0
5590 * vlan dev is found for inner header.
5593 else if (unlikely(!skb))
5596 /* We have stripped outer 802.1P vlan 0 header.
5597 * But could not find vlan dev.
5598 * check again for vlan id to set OTHERHOST.
5602 /* Note: we might in the future use prio bits
5603 * and set skb->priority like in vlan_do_receive()
5604 * For the time being, just ignore Priority Code Point
5606 __vlan_hwaccel_clear_tag(skb);
5609 type = skb->protocol;
5611 /* deliver only exact match when indicated */
5612 if (likely(!deliver_exact)) {
5613 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5614 &ptype_base[ntohs(type) &
5618 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5619 &orig_dev->ptype_specific);
5621 if (unlikely(skb->dev != orig_dev)) {
5622 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5623 &skb->dev->ptype_specific);
5627 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5629 *ppt_prev = pt_prev;
5633 dev_core_stats_rx_dropped_inc(skb->dev);
5635 dev_core_stats_rx_nohandler_inc(skb->dev);
5636 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5637 /* Jamal, now you will not able to escape explaining
5638 * me how you were going to use this. :-)
5644 /* The invariant here is that if *ppt_prev is not NULL
5645 * then skb should also be non-NULL.
5647 * Apparently *ppt_prev assignment above holds this invariant due to
5648 * skb dereferencing near it.
5654 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5656 struct net_device *orig_dev = skb->dev;
5657 struct packet_type *pt_prev = NULL;
5660 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5662 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5663 skb->dev, pt_prev, orig_dev);
5668 * netif_receive_skb_core - special purpose version of netif_receive_skb
5669 * @skb: buffer to process
5671 * More direct receive version of netif_receive_skb(). It should
5672 * only be used by callers that have a need to skip RPS and Generic XDP.
5673 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5675 * This function may only be called from softirq context and interrupts
5676 * should be enabled.
5678 * Return values (usually ignored):
5679 * NET_RX_SUCCESS: no congestion
5680 * NET_RX_DROP: packet was dropped
5682 int netif_receive_skb_core(struct sk_buff *skb)
5687 ret = __netif_receive_skb_one_core(skb, false);
5692 EXPORT_SYMBOL(netif_receive_skb_core);
5694 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5695 struct packet_type *pt_prev,
5696 struct net_device *orig_dev)
5698 struct sk_buff *skb, *next;
5702 if (list_empty(head))
5704 if (pt_prev->list_func != NULL)
5705 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5706 ip_list_rcv, head, pt_prev, orig_dev);
5708 list_for_each_entry_safe(skb, next, head, list) {
5709 skb_list_del_init(skb);
5710 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5714 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5716 /* Fast-path assumptions:
5717 * - There is no RX handler.
5718 * - Only one packet_type matches.
5719 * If either of these fails, we will end up doing some per-packet
5720 * processing in-line, then handling the 'last ptype' for the whole
5721 * sublist. This can't cause out-of-order delivery to any single ptype,
5722 * because the 'last ptype' must be constant across the sublist, and all
5723 * other ptypes are handled per-packet.
5725 /* Current (common) ptype of sublist */
5726 struct packet_type *pt_curr = NULL;
5727 /* Current (common) orig_dev of sublist */
5728 struct net_device *od_curr = NULL;
5729 struct sk_buff *skb, *next;
5732 list_for_each_entry_safe(skb, next, head, list) {
5733 struct net_device *orig_dev = skb->dev;
5734 struct packet_type *pt_prev = NULL;
5736 skb_list_del_init(skb);
5737 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5740 if (pt_curr != pt_prev || od_curr != orig_dev) {
5741 /* dispatch old sublist */
5742 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5743 /* start new sublist */
5744 INIT_LIST_HEAD(&sublist);
5748 list_add_tail(&skb->list, &sublist);
5751 /* dispatch final sublist */
5752 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5755 static int __netif_receive_skb(struct sk_buff *skb)
5759 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5760 unsigned int noreclaim_flag;
5763 * PFMEMALLOC skbs are special, they should
5764 * - be delivered to SOCK_MEMALLOC sockets only
5765 * - stay away from userspace
5766 * - have bounded memory usage
5768 * Use PF_MEMALLOC as this saves us from propagating the allocation
5769 * context down to all allocation sites.
5771 noreclaim_flag = memalloc_noreclaim_save();
5772 ret = __netif_receive_skb_one_core(skb, true);
5773 memalloc_noreclaim_restore(noreclaim_flag);
5775 ret = __netif_receive_skb_one_core(skb, false);
5780 static void __netif_receive_skb_list(struct list_head *head)
5782 unsigned long noreclaim_flag = 0;
5783 struct sk_buff *skb, *next;
5784 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5786 list_for_each_entry_safe(skb, next, head, list) {
5787 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5788 struct list_head sublist;
5790 /* Handle the previous sublist */
5791 list_cut_before(&sublist, head, &skb->list);
5792 if (!list_empty(&sublist))
5793 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5794 pfmemalloc = !pfmemalloc;
5795 /* See comments in __netif_receive_skb */
5797 noreclaim_flag = memalloc_noreclaim_save();
5799 memalloc_noreclaim_restore(noreclaim_flag);
5802 /* Handle the remaining sublist */
5803 if (!list_empty(head))
5804 __netif_receive_skb_list_core(head, pfmemalloc);
5805 /* Restore pflags */
5807 memalloc_noreclaim_restore(noreclaim_flag);
5810 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5812 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5813 struct bpf_prog *new = xdp->prog;
5816 switch (xdp->command) {
5817 case XDP_SETUP_PROG:
5818 rcu_assign_pointer(dev->xdp_prog, new);
5823 static_branch_dec(&generic_xdp_needed_key);
5824 } else if (new && !old) {
5825 static_branch_inc(&generic_xdp_needed_key);
5826 dev_disable_lro(dev);
5827 dev_disable_gro_hw(dev);
5839 static int netif_receive_skb_internal(struct sk_buff *skb)
5843 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5845 if (skb_defer_rx_timestamp(skb))
5846 return NET_RX_SUCCESS;
5850 if (static_branch_unlikely(&rps_needed)) {
5851 struct rps_dev_flow voidflow, *rflow = &voidflow;
5852 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5855 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5861 ret = __netif_receive_skb(skb);
5866 void netif_receive_skb_list_internal(struct list_head *head)
5868 struct sk_buff *skb, *next;
5871 list_for_each_entry_safe(skb, next, head, list) {
5872 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue),
5874 skb_list_del_init(skb);
5875 if (!skb_defer_rx_timestamp(skb))
5876 list_add_tail(&skb->list, &sublist);
5878 list_splice_init(&sublist, head);
5882 if (static_branch_unlikely(&rps_needed)) {
5883 list_for_each_entry_safe(skb, next, head, list) {
5884 struct rps_dev_flow voidflow, *rflow = &voidflow;
5885 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5888 /* Will be handled, remove from list */
5889 skb_list_del_init(skb);
5890 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5895 __netif_receive_skb_list(head);
5900 * netif_receive_skb - process receive buffer from network
5901 * @skb: buffer to process
5903 * netif_receive_skb() is the main receive data processing function.
5904 * It always succeeds. The buffer may be dropped during processing
5905 * for congestion control or by the protocol layers.
5907 * This function may only be called from softirq context and interrupts
5908 * should be enabled.
5910 * Return values (usually ignored):
5911 * NET_RX_SUCCESS: no congestion
5912 * NET_RX_DROP: packet was dropped
5914 int netif_receive_skb(struct sk_buff *skb)
5918 trace_netif_receive_skb_entry(skb);
5920 ret = netif_receive_skb_internal(skb);
5921 trace_netif_receive_skb_exit(ret);
5925 EXPORT_SYMBOL(netif_receive_skb);
5928 * netif_receive_skb_list - process many receive buffers from network
5929 * @head: list of skbs to process.
5931 * Since return value of netif_receive_skb() is normally ignored, and
5932 * wouldn't be meaningful for a list, this function returns void.
5934 * This function may only be called from softirq context and interrupts
5935 * should be enabled.
5937 void netif_receive_skb_list(struct list_head *head)
5939 struct sk_buff *skb;
5941 if (list_empty(head))
5943 if (trace_netif_receive_skb_list_entry_enabled()) {
5944 list_for_each_entry(skb, head, list)
5945 trace_netif_receive_skb_list_entry(skb);
5947 netif_receive_skb_list_internal(head);
5948 trace_netif_receive_skb_list_exit(0);
5950 EXPORT_SYMBOL(netif_receive_skb_list);
5952 static DEFINE_PER_CPU(struct work_struct, flush_works);
5954 /* Network device is going away, flush any packets still pending */
5955 static void flush_backlog(struct work_struct *work)
5957 struct sk_buff *skb, *tmp;
5958 struct softnet_data *sd;
5961 sd = this_cpu_ptr(&softnet_data);
5963 backlog_lock_irq_disable(sd);
5964 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5965 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5966 __skb_unlink(skb, &sd->input_pkt_queue);
5967 dev_kfree_skb_irq(skb);
5968 rps_input_queue_head_incr(sd);
5971 backlog_unlock_irq_enable(sd);
5973 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
5974 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5975 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5976 __skb_unlink(skb, &sd->process_queue);
5978 rps_input_queue_head_incr(sd);
5981 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
5985 static bool flush_required(int cpu)
5987 #if IS_ENABLED(CONFIG_RPS)
5988 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5991 backlog_lock_irq_disable(sd);
5993 /* as insertion into process_queue happens with the rps lock held,
5994 * process_queue access may race only with dequeue
5996 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
5997 !skb_queue_empty_lockless(&sd->process_queue);
5998 backlog_unlock_irq_enable(sd);
6002 /* without RPS we can't safely check input_pkt_queue: during a
6003 * concurrent remote skb_queue_splice() we can detect as empty both
6004 * input_pkt_queue and process_queue even if the latter could end-up
6005 * containing a lot of packets.
6010 static void flush_all_backlogs(void)
6012 static cpumask_t flush_cpus;
6015 /* since we are under rtnl lock protection we can use static data
6016 * for the cpumask and avoid allocating on stack the possibly
6023 cpumask_clear(&flush_cpus);
6024 for_each_online_cpu(cpu) {
6025 if (flush_required(cpu)) {
6026 queue_work_on(cpu, system_highpri_wq,
6027 per_cpu_ptr(&flush_works, cpu));
6028 cpumask_set_cpu(cpu, &flush_cpus);
6032 /* we can have in flight packet[s] on the cpus we are not flushing,
6033 * synchronize_net() in unregister_netdevice_many() will take care of
6036 for_each_cpu(cpu, &flush_cpus)
6037 flush_work(per_cpu_ptr(&flush_works, cpu));
6042 static void net_rps_send_ipi(struct softnet_data *remsd)
6046 struct softnet_data *next = remsd->rps_ipi_next;
6048 if (cpu_online(remsd->cpu))
6049 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6056 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6057 * Note: called with local irq disabled, but exits with local irq enabled.
6059 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6062 struct softnet_data *remsd = sd->rps_ipi_list;
6064 if (!use_backlog_threads() && remsd) {
6065 sd->rps_ipi_list = NULL;
6069 /* Send pending IPI's to kick RPS processing on remote cpus. */
6070 net_rps_send_ipi(remsd);
6076 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6079 return !use_backlog_threads() && sd->rps_ipi_list;
6085 static int process_backlog(struct napi_struct *napi, int quota)
6087 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6091 /* Check if we have pending ipi, its better to send them now,
6092 * not waiting net_rx_action() end.
6094 if (sd_has_rps_ipi_waiting(sd)) {
6095 local_irq_disable();
6096 net_rps_action_and_irq_enable(sd);
6099 napi->weight = READ_ONCE(net_hotdata.dev_rx_weight);
6101 struct sk_buff *skb;
6103 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6104 while ((skb = __skb_dequeue(&sd->process_queue))) {
6105 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6107 __netif_receive_skb(skb);
6109 if (++work >= quota) {
6110 rps_input_queue_head_add(sd, work);
6114 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6116 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6118 backlog_lock_irq_disable(sd);
6119 if (skb_queue_empty(&sd->input_pkt_queue)) {
6121 * Inline a custom version of __napi_complete().
6122 * only current cpu owns and manipulates this napi,
6123 * and NAPI_STATE_SCHED is the only possible flag set
6125 * We can use a plain write instead of clear_bit(),
6126 * and we dont need an smp_mb() memory barrier.
6128 napi->state &= NAPIF_STATE_THREADED;
6131 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6132 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6133 &sd->process_queue);
6134 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6136 backlog_unlock_irq_enable(sd);
6140 rps_input_queue_head_add(sd, work);
6145 * __napi_schedule - schedule for receive
6146 * @n: entry to schedule
6148 * The entry's receive function will be scheduled to run.
6149 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6151 void __napi_schedule(struct napi_struct *n)
6153 unsigned long flags;
6155 local_irq_save(flags);
6156 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6157 local_irq_restore(flags);
6159 EXPORT_SYMBOL(__napi_schedule);
6162 * napi_schedule_prep - check if napi can be scheduled
6165 * Test if NAPI routine is already running, and if not mark
6166 * it as running. This is used as a condition variable to
6167 * insure only one NAPI poll instance runs. We also make
6168 * sure there is no pending NAPI disable.
6170 bool napi_schedule_prep(struct napi_struct *n)
6172 unsigned long new, val = READ_ONCE(n->state);
6175 if (unlikely(val & NAPIF_STATE_DISABLE))
6177 new = val | NAPIF_STATE_SCHED;
6179 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6180 * This was suggested by Alexander Duyck, as compiler
6181 * emits better code than :
6182 * if (val & NAPIF_STATE_SCHED)
6183 * new |= NAPIF_STATE_MISSED;
6185 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6187 } while (!try_cmpxchg(&n->state, &val, new));
6189 return !(val & NAPIF_STATE_SCHED);
6191 EXPORT_SYMBOL(napi_schedule_prep);
6194 * __napi_schedule_irqoff - schedule for receive
6195 * @n: entry to schedule
6197 * Variant of __napi_schedule() assuming hard irqs are masked.
6199 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6200 * because the interrupt disabled assumption might not be true
6201 * due to force-threaded interrupts and spinlock substitution.
6203 void __napi_schedule_irqoff(struct napi_struct *n)
6205 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6206 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6210 EXPORT_SYMBOL(__napi_schedule_irqoff);
6212 bool napi_complete_done(struct napi_struct *n, int work_done)
6214 unsigned long flags, val, new, timeout = 0;
6218 * 1) Don't let napi dequeue from the cpu poll list
6219 * just in case its running on a different cpu.
6220 * 2) If we are busy polling, do nothing here, we have
6221 * the guarantee we will be called later.
6223 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6224 NAPIF_STATE_IN_BUSY_POLL)))
6229 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6230 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6232 if (n->defer_hard_irqs_count > 0) {
6233 n->defer_hard_irqs_count--;
6234 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6238 if (n->gro_bitmask) {
6239 /* When the NAPI instance uses a timeout and keeps postponing
6240 * it, we need to bound somehow the time packets are kept in
6243 napi_gro_flush(n, !!timeout);
6248 if (unlikely(!list_empty(&n->poll_list))) {
6249 /* If n->poll_list is not empty, we need to mask irqs */
6250 local_irq_save(flags);
6251 list_del_init(&n->poll_list);
6252 local_irq_restore(flags);
6254 WRITE_ONCE(n->list_owner, -1);
6256 val = READ_ONCE(n->state);
6258 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6260 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6261 NAPIF_STATE_SCHED_THREADED |
6262 NAPIF_STATE_PREFER_BUSY_POLL);
6264 /* If STATE_MISSED was set, leave STATE_SCHED set,
6265 * because we will call napi->poll() one more time.
6266 * This C code was suggested by Alexander Duyck to help gcc.
6268 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6270 } while (!try_cmpxchg(&n->state, &val, new));
6272 if (unlikely(val & NAPIF_STATE_MISSED)) {
6278 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6279 HRTIMER_MODE_REL_PINNED);
6282 EXPORT_SYMBOL(napi_complete_done);
6284 /* must be called under rcu_read_lock(), as we dont take a reference */
6285 struct napi_struct *napi_by_id(unsigned int napi_id)
6287 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6288 struct napi_struct *napi;
6290 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6291 if (napi->napi_id == napi_id)
6297 static void skb_defer_free_flush(struct softnet_data *sd)
6299 struct sk_buff *skb, *next;
6301 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6302 if (!READ_ONCE(sd->defer_list))
6305 spin_lock(&sd->defer_lock);
6306 skb = sd->defer_list;
6307 sd->defer_list = NULL;
6308 sd->defer_count = 0;
6309 spin_unlock(&sd->defer_lock);
6311 while (skb != NULL) {
6313 napi_consume_skb(skb, 1);
6318 #if defined(CONFIG_NET_RX_BUSY_POLL)
6320 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6322 if (!skip_schedule) {
6323 gro_normal_list(napi);
6324 __napi_schedule(napi);
6328 if (napi->gro_bitmask) {
6329 /* flush too old packets
6330 * If HZ < 1000, flush all packets.
6332 napi_gro_flush(napi, HZ >= 1000);
6335 gro_normal_list(napi);
6336 clear_bit(NAPI_STATE_SCHED, &napi->state);
6340 NAPI_F_PREFER_BUSY_POLL = 1,
6341 NAPI_F_END_ON_RESCHED = 2,
6344 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock,
6345 unsigned flags, u16 budget)
6347 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6348 bool skip_schedule = false;
6349 unsigned long timeout;
6352 /* Busy polling means there is a high chance device driver hard irq
6353 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6354 * set in napi_schedule_prep().
6355 * Since we are about to call napi->poll() once more, we can safely
6356 * clear NAPI_STATE_MISSED.
6358 * Note: x86 could use a single "lock and ..." instruction
6359 * to perform these two clear_bit()
6361 clear_bit(NAPI_STATE_MISSED, &napi->state);
6362 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6365 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6367 if (flags & NAPI_F_PREFER_BUSY_POLL) {
6368 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6369 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6370 if (napi->defer_hard_irqs_count && timeout) {
6371 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6372 skip_schedule = true;
6376 /* All we really want here is to re-enable device interrupts.
6377 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6379 rc = napi->poll(napi, budget);
6380 /* We can't gro_normal_list() here, because napi->poll() might have
6381 * rearmed the napi (napi_complete_done()) in which case it could
6382 * already be running on another CPU.
6384 trace_napi_poll(napi, rc, budget);
6385 netpoll_poll_unlock(have_poll_lock);
6387 __busy_poll_stop(napi, skip_schedule);
6388 bpf_net_ctx_clear(bpf_net_ctx);
6392 static void __napi_busy_loop(unsigned int napi_id,
6393 bool (*loop_end)(void *, unsigned long),
6394 void *loop_end_arg, unsigned flags, u16 budget)
6396 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6397 int (*napi_poll)(struct napi_struct *napi, int budget);
6398 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6399 void *have_poll_lock = NULL;
6400 struct napi_struct *napi;
6402 WARN_ON_ONCE(!rcu_read_lock_held());
6407 napi = napi_by_id(napi_id);
6411 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6417 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6419 unsigned long val = READ_ONCE(napi->state);
6421 /* If multiple threads are competing for this napi,
6422 * we avoid dirtying napi->state as much as we can.
6424 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6425 NAPIF_STATE_IN_BUSY_POLL)) {
6426 if (flags & NAPI_F_PREFER_BUSY_POLL)
6427 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6430 if (cmpxchg(&napi->state, val,
6431 val | NAPIF_STATE_IN_BUSY_POLL |
6432 NAPIF_STATE_SCHED) != val) {
6433 if (flags & NAPI_F_PREFER_BUSY_POLL)
6434 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6437 have_poll_lock = netpoll_poll_lock(napi);
6438 napi_poll = napi->poll;
6440 work = napi_poll(napi, budget);
6441 trace_napi_poll(napi, work, budget);
6442 gro_normal_list(napi);
6445 __NET_ADD_STATS(dev_net(napi->dev),
6446 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6447 skb_defer_free_flush(this_cpu_ptr(&softnet_data));
6448 bpf_net_ctx_clear(bpf_net_ctx);
6451 if (!loop_end || loop_end(loop_end_arg, start_time))
6454 if (unlikely(need_resched())) {
6455 if (flags & NAPI_F_END_ON_RESCHED)
6458 busy_poll_stop(napi, have_poll_lock, flags, budget);
6459 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6464 if (loop_end(loop_end_arg, start_time))
6471 busy_poll_stop(napi, have_poll_lock, flags, budget);
6472 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6476 void napi_busy_loop_rcu(unsigned int napi_id,
6477 bool (*loop_end)(void *, unsigned long),
6478 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6480 unsigned flags = NAPI_F_END_ON_RESCHED;
6482 if (prefer_busy_poll)
6483 flags |= NAPI_F_PREFER_BUSY_POLL;
6485 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
6488 void napi_busy_loop(unsigned int napi_id,
6489 bool (*loop_end)(void *, unsigned long),
6490 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6492 unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0;
6495 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
6498 EXPORT_SYMBOL(napi_busy_loop);
6500 #endif /* CONFIG_NET_RX_BUSY_POLL */
6502 static void napi_hash_add(struct napi_struct *napi)
6504 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6507 spin_lock(&napi_hash_lock);
6509 /* 0..NR_CPUS range is reserved for sender_cpu use */
6511 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6512 napi_gen_id = MIN_NAPI_ID;
6513 } while (napi_by_id(napi_gen_id));
6514 napi->napi_id = napi_gen_id;
6516 hlist_add_head_rcu(&napi->napi_hash_node,
6517 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6519 spin_unlock(&napi_hash_lock);
6522 /* Warning : caller is responsible to make sure rcu grace period
6523 * is respected before freeing memory containing @napi
6525 static void napi_hash_del(struct napi_struct *napi)
6527 spin_lock(&napi_hash_lock);
6529 hlist_del_init_rcu(&napi->napi_hash_node);
6531 spin_unlock(&napi_hash_lock);
6534 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6536 struct napi_struct *napi;
6538 napi = container_of(timer, struct napi_struct, timer);
6540 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6541 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6543 if (!napi_disable_pending(napi) &&
6544 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6545 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6546 __napi_schedule_irqoff(napi);
6549 return HRTIMER_NORESTART;
6552 static void init_gro_hash(struct napi_struct *napi)
6556 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6557 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6558 napi->gro_hash[i].count = 0;
6560 napi->gro_bitmask = 0;
6563 int dev_set_threaded(struct net_device *dev, bool threaded)
6565 struct napi_struct *napi;
6568 if (dev->threaded == threaded)
6572 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6573 if (!napi->thread) {
6574 err = napi_kthread_create(napi);
6583 WRITE_ONCE(dev->threaded, threaded);
6585 /* Make sure kthread is created before THREADED bit
6588 smp_mb__before_atomic();
6590 /* Setting/unsetting threaded mode on a napi might not immediately
6591 * take effect, if the current napi instance is actively being
6592 * polled. In this case, the switch between threaded mode and
6593 * softirq mode will happen in the next round of napi_schedule().
6594 * This should not cause hiccups/stalls to the live traffic.
6596 list_for_each_entry(napi, &dev->napi_list, dev_list)
6597 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6601 EXPORT_SYMBOL(dev_set_threaded);
6604 * netif_queue_set_napi - Associate queue with the napi
6605 * @dev: device to which NAPI and queue belong
6606 * @queue_index: Index of queue
6607 * @type: queue type as RX or TX
6608 * @napi: NAPI context, pass NULL to clear previously set NAPI
6610 * Set queue with its corresponding napi context. This should be done after
6611 * registering the NAPI handler for the queue-vector and the queues have been
6612 * mapped to the corresponding interrupt vector.
6614 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
6615 enum netdev_queue_type type, struct napi_struct *napi)
6617 struct netdev_rx_queue *rxq;
6618 struct netdev_queue *txq;
6620 if (WARN_ON_ONCE(napi && !napi->dev))
6622 if (dev->reg_state >= NETREG_REGISTERED)
6626 case NETDEV_QUEUE_TYPE_RX:
6627 rxq = __netif_get_rx_queue(dev, queue_index);
6630 case NETDEV_QUEUE_TYPE_TX:
6631 txq = netdev_get_tx_queue(dev, queue_index);
6638 EXPORT_SYMBOL(netif_queue_set_napi);
6640 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6641 int (*poll)(struct napi_struct *, int), int weight)
6643 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6646 INIT_LIST_HEAD(&napi->poll_list);
6647 INIT_HLIST_NODE(&napi->napi_hash_node);
6648 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6649 napi->timer.function = napi_watchdog;
6650 init_gro_hash(napi);
6652 INIT_LIST_HEAD(&napi->rx_list);
6655 if (weight > NAPI_POLL_WEIGHT)
6656 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6658 napi->weight = weight;
6660 #ifdef CONFIG_NETPOLL
6661 napi->poll_owner = -1;
6663 napi->list_owner = -1;
6664 set_bit(NAPI_STATE_SCHED, &napi->state);
6665 set_bit(NAPI_STATE_NPSVC, &napi->state);
6666 list_add_rcu(&napi->dev_list, &dev->napi_list);
6667 napi_hash_add(napi);
6668 napi_get_frags_check(napi);
6669 /* Create kthread for this napi if dev->threaded is set.
6670 * Clear dev->threaded if kthread creation failed so that
6671 * threaded mode will not be enabled in napi_enable().
6673 if (dev->threaded && napi_kthread_create(napi))
6674 dev->threaded = false;
6675 netif_napi_set_irq(napi, -1);
6677 EXPORT_SYMBOL(netif_napi_add_weight);
6679 void napi_disable(struct napi_struct *n)
6681 unsigned long val, new;
6684 set_bit(NAPI_STATE_DISABLE, &n->state);
6686 val = READ_ONCE(n->state);
6688 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6689 usleep_range(20, 200);
6690 val = READ_ONCE(n->state);
6693 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6694 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6695 } while (!try_cmpxchg(&n->state, &val, new));
6697 hrtimer_cancel(&n->timer);
6699 clear_bit(NAPI_STATE_DISABLE, &n->state);
6701 EXPORT_SYMBOL(napi_disable);
6704 * napi_enable - enable NAPI scheduling
6707 * Resume NAPI from being scheduled on this context.
6708 * Must be paired with napi_disable.
6710 void napi_enable(struct napi_struct *n)
6712 unsigned long new, val = READ_ONCE(n->state);
6715 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6717 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6718 if (n->dev->threaded && n->thread)
6719 new |= NAPIF_STATE_THREADED;
6720 } while (!try_cmpxchg(&n->state, &val, new));
6722 EXPORT_SYMBOL(napi_enable);
6724 static void flush_gro_hash(struct napi_struct *napi)
6728 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6729 struct sk_buff *skb, *n;
6731 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6733 napi->gro_hash[i].count = 0;
6737 /* Must be called in process context */
6738 void __netif_napi_del(struct napi_struct *napi)
6740 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6743 napi_hash_del(napi);
6744 list_del_rcu(&napi->dev_list);
6745 napi_free_frags(napi);
6747 flush_gro_hash(napi);
6748 napi->gro_bitmask = 0;
6751 kthread_stop(napi->thread);
6752 napi->thread = NULL;
6755 EXPORT_SYMBOL(__netif_napi_del);
6757 static int __napi_poll(struct napi_struct *n, bool *repoll)
6763 /* This NAPI_STATE_SCHED test is for avoiding a race
6764 * with netpoll's poll_napi(). Only the entity which
6765 * obtains the lock and sees NAPI_STATE_SCHED set will
6766 * actually make the ->poll() call. Therefore we avoid
6767 * accidentally calling ->poll() when NAPI is not scheduled.
6770 if (napi_is_scheduled(n)) {
6771 work = n->poll(n, weight);
6772 trace_napi_poll(n, work, weight);
6774 xdp_do_check_flushed(n);
6777 if (unlikely(work > weight))
6778 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6779 n->poll, work, weight);
6781 if (likely(work < weight))
6784 /* Drivers must not modify the NAPI state if they
6785 * consume the entire weight. In such cases this code
6786 * still "owns" the NAPI instance and therefore can
6787 * move the instance around on the list at-will.
6789 if (unlikely(napi_disable_pending(n))) {
6794 /* The NAPI context has more processing work, but busy-polling
6795 * is preferred. Exit early.
6797 if (napi_prefer_busy_poll(n)) {
6798 if (napi_complete_done(n, work)) {
6799 /* If timeout is not set, we need to make sure
6800 * that the NAPI is re-scheduled.
6807 if (n->gro_bitmask) {
6808 /* flush too old packets
6809 * If HZ < 1000, flush all packets.
6811 napi_gro_flush(n, HZ >= 1000);
6816 /* Some drivers may have called napi_schedule
6817 * prior to exhausting their budget.
6819 if (unlikely(!list_empty(&n->poll_list))) {
6820 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6821 n->dev ? n->dev->name : "backlog");
6830 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6832 bool do_repoll = false;
6836 list_del_init(&n->poll_list);
6838 have = netpoll_poll_lock(n);
6840 work = __napi_poll(n, &do_repoll);
6843 list_add_tail(&n->poll_list, repoll);
6845 netpoll_poll_unlock(have);
6850 static int napi_thread_wait(struct napi_struct *napi)
6852 set_current_state(TASK_INTERRUPTIBLE);
6854 while (!kthread_should_stop()) {
6855 /* Testing SCHED_THREADED bit here to make sure the current
6856 * kthread owns this napi and could poll on this napi.
6857 * Testing SCHED bit is not enough because SCHED bit might be
6858 * set by some other busy poll thread or by napi_disable().
6860 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) {
6861 WARN_ON(!list_empty(&napi->poll_list));
6862 __set_current_state(TASK_RUNNING);
6867 set_current_state(TASK_INTERRUPTIBLE);
6869 __set_current_state(TASK_RUNNING);
6874 static void napi_threaded_poll_loop(struct napi_struct *napi)
6876 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6877 struct softnet_data *sd;
6878 unsigned long last_qs = jiffies;
6881 bool repoll = false;
6885 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6887 sd = this_cpu_ptr(&softnet_data);
6888 sd->in_napi_threaded_poll = true;
6890 have = netpoll_poll_lock(napi);
6891 __napi_poll(napi, &repoll);
6892 netpoll_poll_unlock(have);
6894 sd->in_napi_threaded_poll = false;
6897 if (sd_has_rps_ipi_waiting(sd)) {
6898 local_irq_disable();
6899 net_rps_action_and_irq_enable(sd);
6901 skb_defer_free_flush(sd);
6902 bpf_net_ctx_clear(bpf_net_ctx);
6908 rcu_softirq_qs_periodic(last_qs);
6913 static int napi_threaded_poll(void *data)
6915 struct napi_struct *napi = data;
6917 while (!napi_thread_wait(napi))
6918 napi_threaded_poll_loop(napi);
6923 static __latent_entropy void net_rx_action(void)
6925 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6926 unsigned long time_limit = jiffies +
6927 usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs));
6928 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6929 int budget = READ_ONCE(net_hotdata.netdev_budget);
6933 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6935 sd->in_net_rx_action = true;
6936 local_irq_disable();
6937 list_splice_init(&sd->poll_list, &list);
6941 struct napi_struct *n;
6943 skb_defer_free_flush(sd);
6945 if (list_empty(&list)) {
6946 if (list_empty(&repoll)) {
6947 sd->in_net_rx_action = false;
6949 /* We need to check if ____napi_schedule()
6950 * had refilled poll_list while
6951 * sd->in_net_rx_action was true.
6953 if (!list_empty(&sd->poll_list))
6955 if (!sd_has_rps_ipi_waiting(sd))
6961 n = list_first_entry(&list, struct napi_struct, poll_list);
6962 budget -= napi_poll(n, &repoll);
6964 /* If softirq window is exhausted then punt.
6965 * Allow this to run for 2 jiffies since which will allow
6966 * an average latency of 1.5/HZ.
6968 if (unlikely(budget <= 0 ||
6969 time_after_eq(jiffies, time_limit))) {
6975 local_irq_disable();
6977 list_splice_tail_init(&sd->poll_list, &list);
6978 list_splice_tail(&repoll, &list);
6979 list_splice(&list, &sd->poll_list);
6980 if (!list_empty(&sd->poll_list))
6981 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6983 sd->in_net_rx_action = false;
6985 net_rps_action_and_irq_enable(sd);
6987 bpf_net_ctx_clear(bpf_net_ctx);
6990 struct netdev_adjacent {
6991 struct net_device *dev;
6992 netdevice_tracker dev_tracker;
6994 /* upper master flag, there can only be one master device per list */
6997 /* lookup ignore flag */
7000 /* counter for the number of times this device was added to us */
7003 /* private field for the users */
7006 struct list_head list;
7007 struct rcu_head rcu;
7010 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
7011 struct list_head *adj_list)
7013 struct netdev_adjacent *adj;
7015 list_for_each_entry(adj, adj_list, list) {
7016 if (adj->dev == adj_dev)
7022 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
7023 struct netdev_nested_priv *priv)
7025 struct net_device *dev = (struct net_device *)priv->data;
7027 return upper_dev == dev;
7031 * netdev_has_upper_dev - Check if device is linked to an upper device
7033 * @upper_dev: upper device to check
7035 * Find out if a device is linked to specified upper device and return true
7036 * in case it is. Note that this checks only immediate upper device,
7037 * not through a complete stack of devices. The caller must hold the RTNL lock.
7039 bool netdev_has_upper_dev(struct net_device *dev,
7040 struct net_device *upper_dev)
7042 struct netdev_nested_priv priv = {
7043 .data = (void *)upper_dev,
7048 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7051 EXPORT_SYMBOL(netdev_has_upper_dev);
7054 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
7056 * @upper_dev: upper device to check
7058 * Find out if a device is linked to specified upper device and return true
7059 * in case it is. Note that this checks the entire upper device chain.
7060 * The caller must hold rcu lock.
7063 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
7064 struct net_device *upper_dev)
7066 struct netdev_nested_priv priv = {
7067 .data = (void *)upper_dev,
7070 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7073 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
7076 * netdev_has_any_upper_dev - Check if device is linked to some device
7079 * Find out if a device is linked to an upper device and return true in case
7080 * it is. The caller must hold the RTNL lock.
7082 bool netdev_has_any_upper_dev(struct net_device *dev)
7086 return !list_empty(&dev->adj_list.upper);
7088 EXPORT_SYMBOL(netdev_has_any_upper_dev);
7091 * netdev_master_upper_dev_get - Get master upper device
7094 * Find a master upper device and return pointer to it or NULL in case
7095 * it's not there. The caller must hold the RTNL lock.
7097 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
7099 struct netdev_adjacent *upper;
7103 if (list_empty(&dev->adj_list.upper))
7106 upper = list_first_entry(&dev->adj_list.upper,
7107 struct netdev_adjacent, list);
7108 if (likely(upper->master))
7112 EXPORT_SYMBOL(netdev_master_upper_dev_get);
7114 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
7116 struct netdev_adjacent *upper;
7120 if (list_empty(&dev->adj_list.upper))
7123 upper = list_first_entry(&dev->adj_list.upper,
7124 struct netdev_adjacent, list);
7125 if (likely(upper->master) && !upper->ignore)
7131 * netdev_has_any_lower_dev - Check if device is linked to some device
7134 * Find out if a device is linked to a lower device and return true in case
7135 * it is. The caller must hold the RTNL lock.
7137 static bool netdev_has_any_lower_dev(struct net_device *dev)
7141 return !list_empty(&dev->adj_list.lower);
7144 void *netdev_adjacent_get_private(struct list_head *adj_list)
7146 struct netdev_adjacent *adj;
7148 adj = list_entry(adj_list, struct netdev_adjacent, list);
7150 return adj->private;
7152 EXPORT_SYMBOL(netdev_adjacent_get_private);
7155 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7157 * @iter: list_head ** of the current position
7159 * Gets the next device from the dev's upper list, starting from iter
7160 * position. The caller must hold RCU read lock.
7162 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7163 struct list_head **iter)
7165 struct netdev_adjacent *upper;
7167 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7169 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7171 if (&upper->list == &dev->adj_list.upper)
7174 *iter = &upper->list;
7178 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7180 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7181 struct list_head **iter,
7184 struct netdev_adjacent *upper;
7186 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7188 if (&upper->list == &dev->adj_list.upper)
7191 *iter = &upper->list;
7192 *ignore = upper->ignore;
7197 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7198 struct list_head **iter)
7200 struct netdev_adjacent *upper;
7202 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7204 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7206 if (&upper->list == &dev->adj_list.upper)
7209 *iter = &upper->list;
7214 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7215 int (*fn)(struct net_device *dev,
7216 struct netdev_nested_priv *priv),
7217 struct netdev_nested_priv *priv)
7219 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7220 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7225 iter = &dev->adj_list.upper;
7229 ret = fn(now, priv);
7236 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7243 niter = &udev->adj_list.upper;
7244 dev_stack[cur] = now;
7245 iter_stack[cur++] = iter;
7252 next = dev_stack[--cur];
7253 niter = iter_stack[cur];
7263 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7264 int (*fn)(struct net_device *dev,
7265 struct netdev_nested_priv *priv),
7266 struct netdev_nested_priv *priv)
7268 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7269 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7273 iter = &dev->adj_list.upper;
7277 ret = fn(now, priv);
7284 udev = netdev_next_upper_dev_rcu(now, &iter);
7289 niter = &udev->adj_list.upper;
7290 dev_stack[cur] = now;
7291 iter_stack[cur++] = iter;
7298 next = dev_stack[--cur];
7299 niter = iter_stack[cur];
7308 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7310 static bool __netdev_has_upper_dev(struct net_device *dev,
7311 struct net_device *upper_dev)
7313 struct netdev_nested_priv priv = {
7315 .data = (void *)upper_dev,
7320 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7325 * netdev_lower_get_next_private - Get the next ->private from the
7326 * lower neighbour list
7328 * @iter: list_head ** of the current position
7330 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7331 * list, starting from iter position. The caller must hold either hold the
7332 * RTNL lock or its own locking that guarantees that the neighbour lower
7333 * list will remain unchanged.
7335 void *netdev_lower_get_next_private(struct net_device *dev,
7336 struct list_head **iter)
7338 struct netdev_adjacent *lower;
7340 lower = list_entry(*iter, struct netdev_adjacent, list);
7342 if (&lower->list == &dev->adj_list.lower)
7345 *iter = lower->list.next;
7347 return lower->private;
7349 EXPORT_SYMBOL(netdev_lower_get_next_private);
7352 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7353 * lower neighbour list, RCU
7356 * @iter: list_head ** of the current position
7358 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7359 * list, starting from iter position. The caller must hold RCU read lock.
7361 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7362 struct list_head **iter)
7364 struct netdev_adjacent *lower;
7366 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7368 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7370 if (&lower->list == &dev->adj_list.lower)
7373 *iter = &lower->list;
7375 return lower->private;
7377 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7380 * netdev_lower_get_next - Get the next device from the lower neighbour
7383 * @iter: list_head ** of the current position
7385 * Gets the next netdev_adjacent from the dev's lower neighbour
7386 * list, starting from iter position. The caller must hold RTNL lock or
7387 * its own locking that guarantees that the neighbour lower
7388 * list will remain unchanged.
7390 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7392 struct netdev_adjacent *lower;
7394 lower = list_entry(*iter, struct netdev_adjacent, list);
7396 if (&lower->list == &dev->adj_list.lower)
7399 *iter = lower->list.next;
7403 EXPORT_SYMBOL(netdev_lower_get_next);
7405 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7406 struct list_head **iter)
7408 struct netdev_adjacent *lower;
7410 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7412 if (&lower->list == &dev->adj_list.lower)
7415 *iter = &lower->list;
7420 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7421 struct list_head **iter,
7424 struct netdev_adjacent *lower;
7426 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7428 if (&lower->list == &dev->adj_list.lower)
7431 *iter = &lower->list;
7432 *ignore = lower->ignore;
7437 int netdev_walk_all_lower_dev(struct net_device *dev,
7438 int (*fn)(struct net_device *dev,
7439 struct netdev_nested_priv *priv),
7440 struct netdev_nested_priv *priv)
7442 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7443 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7447 iter = &dev->adj_list.lower;
7451 ret = fn(now, priv);
7458 ldev = netdev_next_lower_dev(now, &iter);
7463 niter = &ldev->adj_list.lower;
7464 dev_stack[cur] = now;
7465 iter_stack[cur++] = iter;
7472 next = dev_stack[--cur];
7473 niter = iter_stack[cur];
7482 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7484 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7485 int (*fn)(struct net_device *dev,
7486 struct netdev_nested_priv *priv),
7487 struct netdev_nested_priv *priv)
7489 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7490 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7495 iter = &dev->adj_list.lower;
7499 ret = fn(now, priv);
7506 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7513 niter = &ldev->adj_list.lower;
7514 dev_stack[cur] = now;
7515 iter_stack[cur++] = iter;
7522 next = dev_stack[--cur];
7523 niter = iter_stack[cur];
7533 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7534 struct list_head **iter)
7536 struct netdev_adjacent *lower;
7538 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7539 if (&lower->list == &dev->adj_list.lower)
7542 *iter = &lower->list;
7546 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7548 static u8 __netdev_upper_depth(struct net_device *dev)
7550 struct net_device *udev;
7551 struct list_head *iter;
7555 for (iter = &dev->adj_list.upper,
7556 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7558 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7561 if (max_depth < udev->upper_level)
7562 max_depth = udev->upper_level;
7568 static u8 __netdev_lower_depth(struct net_device *dev)
7570 struct net_device *ldev;
7571 struct list_head *iter;
7575 for (iter = &dev->adj_list.lower,
7576 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7578 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7581 if (max_depth < ldev->lower_level)
7582 max_depth = ldev->lower_level;
7588 static int __netdev_update_upper_level(struct net_device *dev,
7589 struct netdev_nested_priv *__unused)
7591 dev->upper_level = __netdev_upper_depth(dev) + 1;
7595 #ifdef CONFIG_LOCKDEP
7596 static LIST_HEAD(net_unlink_list);
7598 static void net_unlink_todo(struct net_device *dev)
7600 if (list_empty(&dev->unlink_list))
7601 list_add_tail(&dev->unlink_list, &net_unlink_list);
7605 static int __netdev_update_lower_level(struct net_device *dev,
7606 struct netdev_nested_priv *priv)
7608 dev->lower_level = __netdev_lower_depth(dev) + 1;
7610 #ifdef CONFIG_LOCKDEP
7614 if (priv->flags & NESTED_SYNC_IMM)
7615 dev->nested_level = dev->lower_level - 1;
7616 if (priv->flags & NESTED_SYNC_TODO)
7617 net_unlink_todo(dev);
7622 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7623 int (*fn)(struct net_device *dev,
7624 struct netdev_nested_priv *priv),
7625 struct netdev_nested_priv *priv)
7627 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7628 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7632 iter = &dev->adj_list.lower;
7636 ret = fn(now, priv);
7643 ldev = netdev_next_lower_dev_rcu(now, &iter);
7648 niter = &ldev->adj_list.lower;
7649 dev_stack[cur] = now;
7650 iter_stack[cur++] = iter;
7657 next = dev_stack[--cur];
7658 niter = iter_stack[cur];
7667 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7670 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7671 * lower neighbour list, RCU
7675 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7676 * list. The caller must hold RCU read lock.
7678 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7680 struct netdev_adjacent *lower;
7682 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7683 struct netdev_adjacent, list);
7685 return lower->private;
7688 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7691 * netdev_master_upper_dev_get_rcu - Get master upper device
7694 * Find a master upper device and return pointer to it or NULL in case
7695 * it's not there. The caller must hold the RCU read lock.
7697 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7699 struct netdev_adjacent *upper;
7701 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7702 struct netdev_adjacent, list);
7703 if (upper && likely(upper->master))
7707 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7709 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7710 struct net_device *adj_dev,
7711 struct list_head *dev_list)
7713 char linkname[IFNAMSIZ+7];
7715 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7716 "upper_%s" : "lower_%s", adj_dev->name);
7717 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7720 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7722 struct list_head *dev_list)
7724 char linkname[IFNAMSIZ+7];
7726 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7727 "upper_%s" : "lower_%s", name);
7728 sysfs_remove_link(&(dev->dev.kobj), linkname);
7731 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7732 struct net_device *adj_dev,
7733 struct list_head *dev_list)
7735 return (dev_list == &dev->adj_list.upper ||
7736 dev_list == &dev->adj_list.lower) &&
7737 net_eq(dev_net(dev), dev_net(adj_dev));
7740 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7741 struct net_device *adj_dev,
7742 struct list_head *dev_list,
7743 void *private, bool master)
7745 struct netdev_adjacent *adj;
7748 adj = __netdev_find_adj(adj_dev, dev_list);
7752 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7753 dev->name, adj_dev->name, adj->ref_nr);
7758 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7763 adj->master = master;
7765 adj->private = private;
7766 adj->ignore = false;
7767 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7769 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7770 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7772 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7773 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7778 /* Ensure that master link is always the first item in list. */
7780 ret = sysfs_create_link(&(dev->dev.kobj),
7781 &(adj_dev->dev.kobj), "master");
7783 goto remove_symlinks;
7785 list_add_rcu(&adj->list, dev_list);
7787 list_add_tail_rcu(&adj->list, dev_list);
7793 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7794 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7796 netdev_put(adj_dev, &adj->dev_tracker);
7802 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7803 struct net_device *adj_dev,
7805 struct list_head *dev_list)
7807 struct netdev_adjacent *adj;
7809 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7810 dev->name, adj_dev->name, ref_nr);
7812 adj = __netdev_find_adj(adj_dev, dev_list);
7815 pr_err("Adjacency does not exist for device %s from %s\n",
7816 dev->name, adj_dev->name);
7821 if (adj->ref_nr > ref_nr) {
7822 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7823 dev->name, adj_dev->name, ref_nr,
7824 adj->ref_nr - ref_nr);
7825 adj->ref_nr -= ref_nr;
7830 sysfs_remove_link(&(dev->dev.kobj), "master");
7832 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7833 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7835 list_del_rcu(&adj->list);
7836 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7837 adj_dev->name, dev->name, adj_dev->name);
7838 netdev_put(adj_dev, &adj->dev_tracker);
7839 kfree_rcu(adj, rcu);
7842 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7843 struct net_device *upper_dev,
7844 struct list_head *up_list,
7845 struct list_head *down_list,
7846 void *private, bool master)
7850 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7855 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7858 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7865 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7866 struct net_device *upper_dev,
7868 struct list_head *up_list,
7869 struct list_head *down_list)
7871 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7872 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7875 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7876 struct net_device *upper_dev,
7877 void *private, bool master)
7879 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7880 &dev->adj_list.upper,
7881 &upper_dev->adj_list.lower,
7885 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7886 struct net_device *upper_dev)
7888 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7889 &dev->adj_list.upper,
7890 &upper_dev->adj_list.lower);
7893 static int __netdev_upper_dev_link(struct net_device *dev,
7894 struct net_device *upper_dev, bool master,
7895 void *upper_priv, void *upper_info,
7896 struct netdev_nested_priv *priv,
7897 struct netlink_ext_ack *extack)
7899 struct netdev_notifier_changeupper_info changeupper_info = {
7904 .upper_dev = upper_dev,
7907 .upper_info = upper_info,
7909 struct net_device *master_dev;
7914 if (dev == upper_dev)
7917 /* To prevent loops, check if dev is not upper device to upper_dev. */
7918 if (__netdev_has_upper_dev(upper_dev, dev))
7921 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7925 if (__netdev_has_upper_dev(dev, upper_dev))
7928 master_dev = __netdev_master_upper_dev_get(dev);
7930 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7933 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7934 &changeupper_info.info);
7935 ret = notifier_to_errno(ret);
7939 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7944 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7945 &changeupper_info.info);
7946 ret = notifier_to_errno(ret);
7950 __netdev_update_upper_level(dev, NULL);
7951 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7953 __netdev_update_lower_level(upper_dev, priv);
7954 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7960 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7966 * netdev_upper_dev_link - Add a link to the upper device
7968 * @upper_dev: new upper device
7969 * @extack: netlink extended ack
7971 * Adds a link to device which is upper to this one. The caller must hold
7972 * the RTNL lock. On a failure a negative errno code is returned.
7973 * On success the reference counts are adjusted and the function
7976 int netdev_upper_dev_link(struct net_device *dev,
7977 struct net_device *upper_dev,
7978 struct netlink_ext_ack *extack)
7980 struct netdev_nested_priv priv = {
7981 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7985 return __netdev_upper_dev_link(dev, upper_dev, false,
7986 NULL, NULL, &priv, extack);
7988 EXPORT_SYMBOL(netdev_upper_dev_link);
7991 * netdev_master_upper_dev_link - Add a master link to the upper device
7993 * @upper_dev: new upper device
7994 * @upper_priv: upper device private
7995 * @upper_info: upper info to be passed down via notifier
7996 * @extack: netlink extended ack
7998 * Adds a link to device which is upper to this one. In this case, only
7999 * one master upper device can be linked, although other non-master devices
8000 * might be linked as well. The caller must hold the RTNL lock.
8001 * On a failure a negative errno code is returned. On success the reference
8002 * counts are adjusted and the function returns zero.
8004 int netdev_master_upper_dev_link(struct net_device *dev,
8005 struct net_device *upper_dev,
8006 void *upper_priv, void *upper_info,
8007 struct netlink_ext_ack *extack)
8009 struct netdev_nested_priv priv = {
8010 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8014 return __netdev_upper_dev_link(dev, upper_dev, true,
8015 upper_priv, upper_info, &priv, extack);
8017 EXPORT_SYMBOL(netdev_master_upper_dev_link);
8019 static void __netdev_upper_dev_unlink(struct net_device *dev,
8020 struct net_device *upper_dev,
8021 struct netdev_nested_priv *priv)
8023 struct netdev_notifier_changeupper_info changeupper_info = {
8027 .upper_dev = upper_dev,
8033 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
8035 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
8036 &changeupper_info.info);
8038 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
8040 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
8041 &changeupper_info.info);
8043 __netdev_update_upper_level(dev, NULL);
8044 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
8046 __netdev_update_lower_level(upper_dev, priv);
8047 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
8052 * netdev_upper_dev_unlink - Removes a link to upper device
8054 * @upper_dev: new upper device
8056 * Removes a link to device which is upper to this one. The caller must hold
8059 void netdev_upper_dev_unlink(struct net_device *dev,
8060 struct net_device *upper_dev)
8062 struct netdev_nested_priv priv = {
8063 .flags = NESTED_SYNC_TODO,
8067 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
8069 EXPORT_SYMBOL(netdev_upper_dev_unlink);
8071 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
8072 struct net_device *lower_dev,
8075 struct netdev_adjacent *adj;
8077 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
8081 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
8086 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
8087 struct net_device *lower_dev)
8089 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
8092 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
8093 struct net_device *lower_dev)
8095 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
8098 int netdev_adjacent_change_prepare(struct net_device *old_dev,
8099 struct net_device *new_dev,
8100 struct net_device *dev,
8101 struct netlink_ext_ack *extack)
8103 struct netdev_nested_priv priv = {
8112 if (old_dev && new_dev != old_dev)
8113 netdev_adjacent_dev_disable(dev, old_dev);
8114 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
8117 if (old_dev && new_dev != old_dev)
8118 netdev_adjacent_dev_enable(dev, old_dev);
8124 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
8126 void netdev_adjacent_change_commit(struct net_device *old_dev,
8127 struct net_device *new_dev,
8128 struct net_device *dev)
8130 struct netdev_nested_priv priv = {
8131 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8135 if (!new_dev || !old_dev)
8138 if (new_dev == old_dev)
8141 netdev_adjacent_dev_enable(dev, old_dev);
8142 __netdev_upper_dev_unlink(old_dev, dev, &priv);
8144 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8146 void netdev_adjacent_change_abort(struct net_device *old_dev,
8147 struct net_device *new_dev,
8148 struct net_device *dev)
8150 struct netdev_nested_priv priv = {
8158 if (old_dev && new_dev != old_dev)
8159 netdev_adjacent_dev_enable(dev, old_dev);
8161 __netdev_upper_dev_unlink(new_dev, dev, &priv);
8163 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8166 * netdev_bonding_info_change - Dispatch event about slave change
8168 * @bonding_info: info to dispatch
8170 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8171 * The caller must hold the RTNL lock.
8173 void netdev_bonding_info_change(struct net_device *dev,
8174 struct netdev_bonding_info *bonding_info)
8176 struct netdev_notifier_bonding_info info = {
8180 memcpy(&info.bonding_info, bonding_info,
8181 sizeof(struct netdev_bonding_info));
8182 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8185 EXPORT_SYMBOL(netdev_bonding_info_change);
8187 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
8188 struct netlink_ext_ack *extack)
8190 struct netdev_notifier_offload_xstats_info info = {
8192 .info.extack = extack,
8193 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8198 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
8200 if (!dev->offload_xstats_l3)
8203 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
8204 NETDEV_OFFLOAD_XSTATS_DISABLE,
8206 err = notifier_to_errno(rc);
8213 kfree(dev->offload_xstats_l3);
8214 dev->offload_xstats_l3 = NULL;
8218 int netdev_offload_xstats_enable(struct net_device *dev,
8219 enum netdev_offload_xstats_type type,
8220 struct netlink_ext_ack *extack)
8224 if (netdev_offload_xstats_enabled(dev, type))
8228 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8229 return netdev_offload_xstats_enable_l3(dev, extack);
8235 EXPORT_SYMBOL(netdev_offload_xstats_enable);
8237 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
8239 struct netdev_notifier_offload_xstats_info info = {
8241 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8244 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8246 kfree(dev->offload_xstats_l3);
8247 dev->offload_xstats_l3 = NULL;
8250 int netdev_offload_xstats_disable(struct net_device *dev,
8251 enum netdev_offload_xstats_type type)
8255 if (!netdev_offload_xstats_enabled(dev, type))
8259 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8260 netdev_offload_xstats_disable_l3(dev);
8267 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8269 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8271 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8274 static struct rtnl_hw_stats64 *
8275 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8276 enum netdev_offload_xstats_type type)
8279 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8280 return dev->offload_xstats_l3;
8287 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8288 enum netdev_offload_xstats_type type)
8292 return netdev_offload_xstats_get_ptr(dev, type);
8294 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8296 struct netdev_notifier_offload_xstats_ru {
8300 struct netdev_notifier_offload_xstats_rd {
8301 struct rtnl_hw_stats64 stats;
8305 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8306 const struct rtnl_hw_stats64 *src)
8308 dest->rx_packets += src->rx_packets;
8309 dest->tx_packets += src->tx_packets;
8310 dest->rx_bytes += src->rx_bytes;
8311 dest->tx_bytes += src->tx_bytes;
8312 dest->rx_errors += src->rx_errors;
8313 dest->tx_errors += src->tx_errors;
8314 dest->rx_dropped += src->rx_dropped;
8315 dest->tx_dropped += src->tx_dropped;
8316 dest->multicast += src->multicast;
8319 static int netdev_offload_xstats_get_used(struct net_device *dev,
8320 enum netdev_offload_xstats_type type,
8322 struct netlink_ext_ack *extack)
8324 struct netdev_notifier_offload_xstats_ru report_used = {};
8325 struct netdev_notifier_offload_xstats_info info = {
8327 .info.extack = extack,
8329 .report_used = &report_used,
8333 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8334 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8336 *p_used = report_used.used;
8337 return notifier_to_errno(rc);
8340 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8341 enum netdev_offload_xstats_type type,
8342 struct rtnl_hw_stats64 *p_stats,
8344 struct netlink_ext_ack *extack)
8346 struct netdev_notifier_offload_xstats_rd report_delta = {};
8347 struct netdev_notifier_offload_xstats_info info = {
8349 .info.extack = extack,
8351 .report_delta = &report_delta,
8353 struct rtnl_hw_stats64 *stats;
8356 stats = netdev_offload_xstats_get_ptr(dev, type);
8357 if (WARN_ON(!stats))
8360 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8363 /* Cache whatever we got, even if there was an error, otherwise the
8364 * successful stats retrievals would get lost.
8366 netdev_hw_stats64_add(stats, &report_delta.stats);
8370 *p_used = report_delta.used;
8372 return notifier_to_errno(rc);
8375 int netdev_offload_xstats_get(struct net_device *dev,
8376 enum netdev_offload_xstats_type type,
8377 struct rtnl_hw_stats64 *p_stats, bool *p_used,
8378 struct netlink_ext_ack *extack)
8383 return netdev_offload_xstats_get_stats(dev, type, p_stats,
8386 return netdev_offload_xstats_get_used(dev, type, p_used,
8389 EXPORT_SYMBOL(netdev_offload_xstats_get);
8392 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8393 const struct rtnl_hw_stats64 *stats)
8395 report_delta->used = true;
8396 netdev_hw_stats64_add(&report_delta->stats, stats);
8398 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8401 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8403 report_used->used = true;
8405 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8407 void netdev_offload_xstats_push_delta(struct net_device *dev,
8408 enum netdev_offload_xstats_type type,
8409 const struct rtnl_hw_stats64 *p_stats)
8411 struct rtnl_hw_stats64 *stats;
8415 stats = netdev_offload_xstats_get_ptr(dev, type);
8416 if (WARN_ON(!stats))
8419 netdev_hw_stats64_add(stats, p_stats);
8421 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8424 * netdev_get_xmit_slave - Get the xmit slave of master device
8427 * @all_slaves: assume all the slaves are active
8429 * The reference counters are not incremented so the caller must be
8430 * careful with locks. The caller must hold RCU lock.
8431 * %NULL is returned if no slave is found.
8434 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8435 struct sk_buff *skb,
8438 const struct net_device_ops *ops = dev->netdev_ops;
8440 if (!ops->ndo_get_xmit_slave)
8442 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8444 EXPORT_SYMBOL(netdev_get_xmit_slave);
8446 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8449 const struct net_device_ops *ops = dev->netdev_ops;
8451 if (!ops->ndo_sk_get_lower_dev)
8453 return ops->ndo_sk_get_lower_dev(dev, sk);
8457 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8461 * %NULL is returned if no lower device is found.
8464 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8467 struct net_device *lower;
8469 lower = netdev_sk_get_lower_dev(dev, sk);
8472 lower = netdev_sk_get_lower_dev(dev, sk);
8477 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8479 static void netdev_adjacent_add_links(struct net_device *dev)
8481 struct netdev_adjacent *iter;
8483 struct net *net = dev_net(dev);
8485 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8486 if (!net_eq(net, dev_net(iter->dev)))
8488 netdev_adjacent_sysfs_add(iter->dev, dev,
8489 &iter->dev->adj_list.lower);
8490 netdev_adjacent_sysfs_add(dev, iter->dev,
8491 &dev->adj_list.upper);
8494 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8495 if (!net_eq(net, dev_net(iter->dev)))
8497 netdev_adjacent_sysfs_add(iter->dev, dev,
8498 &iter->dev->adj_list.upper);
8499 netdev_adjacent_sysfs_add(dev, iter->dev,
8500 &dev->adj_list.lower);
8504 static void netdev_adjacent_del_links(struct net_device *dev)
8506 struct netdev_adjacent *iter;
8508 struct net *net = dev_net(dev);
8510 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8511 if (!net_eq(net, dev_net(iter->dev)))
8513 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8514 &iter->dev->adj_list.lower);
8515 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8516 &dev->adj_list.upper);
8519 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8520 if (!net_eq(net, dev_net(iter->dev)))
8522 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8523 &iter->dev->adj_list.upper);
8524 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8525 &dev->adj_list.lower);
8529 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8531 struct netdev_adjacent *iter;
8533 struct net *net = dev_net(dev);
8535 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8536 if (!net_eq(net, dev_net(iter->dev)))
8538 netdev_adjacent_sysfs_del(iter->dev, oldname,
8539 &iter->dev->adj_list.lower);
8540 netdev_adjacent_sysfs_add(iter->dev, dev,
8541 &iter->dev->adj_list.lower);
8544 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8545 if (!net_eq(net, dev_net(iter->dev)))
8547 netdev_adjacent_sysfs_del(iter->dev, oldname,
8548 &iter->dev->adj_list.upper);
8549 netdev_adjacent_sysfs_add(iter->dev, dev,
8550 &iter->dev->adj_list.upper);
8554 void *netdev_lower_dev_get_private(struct net_device *dev,
8555 struct net_device *lower_dev)
8557 struct netdev_adjacent *lower;
8561 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8565 return lower->private;
8567 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8571 * netdev_lower_state_changed - Dispatch event about lower device state change
8572 * @lower_dev: device
8573 * @lower_state_info: state to dispatch
8575 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8576 * The caller must hold the RTNL lock.
8578 void netdev_lower_state_changed(struct net_device *lower_dev,
8579 void *lower_state_info)
8581 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8582 .info.dev = lower_dev,
8586 changelowerstate_info.lower_state_info = lower_state_info;
8587 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8588 &changelowerstate_info.info);
8590 EXPORT_SYMBOL(netdev_lower_state_changed);
8592 static void dev_change_rx_flags(struct net_device *dev, int flags)
8594 const struct net_device_ops *ops = dev->netdev_ops;
8596 if (ops->ndo_change_rx_flags)
8597 ops->ndo_change_rx_flags(dev, flags);
8600 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8602 unsigned int old_flags = dev->flags;
8603 unsigned int promiscuity, flags;
8609 promiscuity = dev->promiscuity + inc;
8610 if (promiscuity == 0) {
8613 * If inc causes overflow, untouch promisc and return error.
8615 if (unlikely(inc > 0)) {
8616 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8619 flags = old_flags & ~IFF_PROMISC;
8621 flags = old_flags | IFF_PROMISC;
8623 WRITE_ONCE(dev->promiscuity, promiscuity);
8624 if (flags != old_flags) {
8625 WRITE_ONCE(dev->flags, flags);
8626 netdev_info(dev, "%s promiscuous mode\n",
8627 dev->flags & IFF_PROMISC ? "entered" : "left");
8628 if (audit_enabled) {
8629 current_uid_gid(&uid, &gid);
8630 audit_log(audit_context(), GFP_ATOMIC,
8631 AUDIT_ANOM_PROMISCUOUS,
8632 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8633 dev->name, (dev->flags & IFF_PROMISC),
8634 (old_flags & IFF_PROMISC),
8635 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8636 from_kuid(&init_user_ns, uid),
8637 from_kgid(&init_user_ns, gid),
8638 audit_get_sessionid(current));
8641 dev_change_rx_flags(dev, IFF_PROMISC);
8644 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8649 * dev_set_promiscuity - update promiscuity count on a device
8653 * Add or remove promiscuity from a device. While the count in the device
8654 * remains above zero the interface remains promiscuous. Once it hits zero
8655 * the device reverts back to normal filtering operation. A negative inc
8656 * value is used to drop promiscuity on the device.
8657 * Return 0 if successful or a negative errno code on error.
8659 int dev_set_promiscuity(struct net_device *dev, int inc)
8661 unsigned int old_flags = dev->flags;
8664 err = __dev_set_promiscuity(dev, inc, true);
8667 if (dev->flags != old_flags)
8668 dev_set_rx_mode(dev);
8671 EXPORT_SYMBOL(dev_set_promiscuity);
8673 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8675 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8676 unsigned int allmulti, flags;
8680 allmulti = dev->allmulti + inc;
8681 if (allmulti == 0) {
8684 * If inc causes overflow, untouch allmulti and return error.
8686 if (unlikely(inc > 0)) {
8687 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8690 flags = old_flags & ~IFF_ALLMULTI;
8692 flags = old_flags | IFF_ALLMULTI;
8694 WRITE_ONCE(dev->allmulti, allmulti);
8695 if (flags != old_flags) {
8696 WRITE_ONCE(dev->flags, flags);
8697 netdev_info(dev, "%s allmulticast mode\n",
8698 dev->flags & IFF_ALLMULTI ? "entered" : "left");
8699 dev_change_rx_flags(dev, IFF_ALLMULTI);
8700 dev_set_rx_mode(dev);
8702 __dev_notify_flags(dev, old_flags,
8703 dev->gflags ^ old_gflags, 0, NULL);
8709 * dev_set_allmulti - update allmulti count on a device
8713 * Add or remove reception of all multicast frames to a device. While the
8714 * count in the device remains above zero the interface remains listening
8715 * to all interfaces. Once it hits zero the device reverts back to normal
8716 * filtering operation. A negative @inc value is used to drop the counter
8717 * when releasing a resource needing all multicasts.
8718 * Return 0 if successful or a negative errno code on error.
8721 int dev_set_allmulti(struct net_device *dev, int inc)
8723 return __dev_set_allmulti(dev, inc, true);
8725 EXPORT_SYMBOL(dev_set_allmulti);
8728 * Upload unicast and multicast address lists to device and
8729 * configure RX filtering. When the device doesn't support unicast
8730 * filtering it is put in promiscuous mode while unicast addresses
8733 void __dev_set_rx_mode(struct net_device *dev)
8735 const struct net_device_ops *ops = dev->netdev_ops;
8737 /* dev_open will call this function so the list will stay sane. */
8738 if (!(dev->flags&IFF_UP))
8741 if (!netif_device_present(dev))
8744 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8745 /* Unicast addresses changes may only happen under the rtnl,
8746 * therefore calling __dev_set_promiscuity here is safe.
8748 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8749 __dev_set_promiscuity(dev, 1, false);
8750 dev->uc_promisc = true;
8751 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8752 __dev_set_promiscuity(dev, -1, false);
8753 dev->uc_promisc = false;
8757 if (ops->ndo_set_rx_mode)
8758 ops->ndo_set_rx_mode(dev);
8761 void dev_set_rx_mode(struct net_device *dev)
8763 netif_addr_lock_bh(dev);
8764 __dev_set_rx_mode(dev);
8765 netif_addr_unlock_bh(dev);
8769 * dev_get_flags - get flags reported to userspace
8772 * Get the combination of flag bits exported through APIs to userspace.
8774 unsigned int dev_get_flags(const struct net_device *dev)
8778 flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC |
8783 (READ_ONCE(dev->gflags) & (IFF_PROMISC |
8786 if (netif_running(dev)) {
8787 if (netif_oper_up(dev))
8788 flags |= IFF_RUNNING;
8789 if (netif_carrier_ok(dev))
8790 flags |= IFF_LOWER_UP;
8791 if (netif_dormant(dev))
8792 flags |= IFF_DORMANT;
8797 EXPORT_SYMBOL(dev_get_flags);
8799 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8800 struct netlink_ext_ack *extack)
8802 unsigned int old_flags = dev->flags;
8808 * Set the flags on our device.
8811 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8812 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8814 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8818 * Load in the correct multicast list now the flags have changed.
8821 if ((old_flags ^ flags) & IFF_MULTICAST)
8822 dev_change_rx_flags(dev, IFF_MULTICAST);
8824 dev_set_rx_mode(dev);
8827 * Have we downed the interface. We handle IFF_UP ourselves
8828 * according to user attempts to set it, rather than blindly
8833 if ((old_flags ^ flags) & IFF_UP) {
8834 if (old_flags & IFF_UP)
8837 ret = __dev_open(dev, extack);
8840 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8841 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8842 unsigned int old_flags = dev->flags;
8844 dev->gflags ^= IFF_PROMISC;
8846 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8847 if (dev->flags != old_flags)
8848 dev_set_rx_mode(dev);
8851 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8852 * is important. Some (broken) drivers set IFF_PROMISC, when
8853 * IFF_ALLMULTI is requested not asking us and not reporting.
8855 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8856 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8858 dev->gflags ^= IFF_ALLMULTI;
8859 __dev_set_allmulti(dev, inc, false);
8865 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8866 unsigned int gchanges, u32 portid,
8867 const struct nlmsghdr *nlh)
8869 unsigned int changes = dev->flags ^ old_flags;
8872 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8874 if (changes & IFF_UP) {
8875 if (dev->flags & IFF_UP)
8876 call_netdevice_notifiers(NETDEV_UP, dev);
8878 call_netdevice_notifiers(NETDEV_DOWN, dev);
8881 if (dev->flags & IFF_UP &&
8882 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8883 struct netdev_notifier_change_info change_info = {
8887 .flags_changed = changes,
8890 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8895 * dev_change_flags - change device settings
8897 * @flags: device state flags
8898 * @extack: netlink extended ack
8900 * Change settings on device based state flags. The flags are
8901 * in the userspace exported format.
8903 int dev_change_flags(struct net_device *dev, unsigned int flags,
8904 struct netlink_ext_ack *extack)
8907 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8909 ret = __dev_change_flags(dev, flags, extack);
8913 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8914 __dev_notify_flags(dev, old_flags, changes, 0, NULL);
8917 EXPORT_SYMBOL(dev_change_flags);
8919 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8921 const struct net_device_ops *ops = dev->netdev_ops;
8923 if (ops->ndo_change_mtu)
8924 return ops->ndo_change_mtu(dev, new_mtu);
8926 /* Pairs with all the lockless reads of dev->mtu in the stack */
8927 WRITE_ONCE(dev->mtu, new_mtu);
8930 EXPORT_SYMBOL(__dev_set_mtu);
8932 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8933 struct netlink_ext_ack *extack)
8935 /* MTU must be positive, and in range */
8936 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8937 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8941 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8942 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8949 * dev_set_mtu_ext - Change maximum transfer unit
8951 * @new_mtu: new transfer unit
8952 * @extack: netlink extended ack
8954 * Change the maximum transfer size of the network device.
8956 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8957 struct netlink_ext_ack *extack)
8961 if (new_mtu == dev->mtu)
8964 err = dev_validate_mtu(dev, new_mtu, extack);
8968 if (!netif_device_present(dev))
8971 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8972 err = notifier_to_errno(err);
8976 orig_mtu = dev->mtu;
8977 err = __dev_set_mtu(dev, new_mtu);
8980 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8982 err = notifier_to_errno(err);
8984 /* setting mtu back and notifying everyone again,
8985 * so that they have a chance to revert changes.
8987 __dev_set_mtu(dev, orig_mtu);
8988 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8995 int dev_set_mtu(struct net_device *dev, int new_mtu)
8997 struct netlink_ext_ack extack;
9000 memset(&extack, 0, sizeof(extack));
9001 err = dev_set_mtu_ext(dev, new_mtu, &extack);
9002 if (err && extack._msg)
9003 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
9006 EXPORT_SYMBOL(dev_set_mtu);
9009 * dev_change_tx_queue_len - Change TX queue length of a netdevice
9011 * @new_len: new tx queue length
9013 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
9015 unsigned int orig_len = dev->tx_queue_len;
9018 if (new_len != (unsigned int)new_len)
9021 if (new_len != orig_len) {
9022 WRITE_ONCE(dev->tx_queue_len, new_len);
9023 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
9024 res = notifier_to_errno(res);
9027 res = dev_qdisc_change_tx_queue_len(dev);
9035 netdev_err(dev, "refused to change device tx_queue_len\n");
9036 WRITE_ONCE(dev->tx_queue_len, orig_len);
9041 * dev_set_group - Change group this device belongs to
9043 * @new_group: group this device should belong to
9045 void dev_set_group(struct net_device *dev, int new_group)
9047 dev->group = new_group;
9051 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
9053 * @addr: new address
9054 * @extack: netlink extended ack
9056 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
9057 struct netlink_ext_ack *extack)
9059 struct netdev_notifier_pre_changeaddr_info info = {
9061 .info.extack = extack,
9066 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
9067 return notifier_to_errno(rc);
9069 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
9072 * dev_set_mac_address - Change Media Access Control Address
9075 * @extack: netlink extended ack
9077 * Change the hardware (MAC) address of the device
9079 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
9080 struct netlink_ext_ack *extack)
9082 const struct net_device_ops *ops = dev->netdev_ops;
9085 if (!ops->ndo_set_mac_address)
9087 if (sa->sa_family != dev->type)
9089 if (!netif_device_present(dev))
9091 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
9094 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
9095 err = ops->ndo_set_mac_address(dev, sa);
9099 dev->addr_assign_type = NET_ADDR_SET;
9100 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
9101 add_device_randomness(dev->dev_addr, dev->addr_len);
9104 EXPORT_SYMBOL(dev_set_mac_address);
9106 DECLARE_RWSEM(dev_addr_sem);
9108 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
9109 struct netlink_ext_ack *extack)
9113 down_write(&dev_addr_sem);
9114 ret = dev_set_mac_address(dev, sa, extack);
9115 up_write(&dev_addr_sem);
9118 EXPORT_SYMBOL(dev_set_mac_address_user);
9120 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
9122 size_t size = sizeof(sa->sa_data_min);
9123 struct net_device *dev;
9126 down_read(&dev_addr_sem);
9129 dev = dev_get_by_name_rcu(net, dev_name);
9135 memset(sa->sa_data, 0, size);
9137 memcpy(sa->sa_data, dev->dev_addr,
9138 min_t(size_t, size, dev->addr_len));
9139 sa->sa_family = dev->type;
9143 up_read(&dev_addr_sem);
9146 EXPORT_SYMBOL(dev_get_mac_address);
9149 * dev_change_carrier - Change device carrier
9151 * @new_carrier: new value
9153 * Change device carrier
9155 int dev_change_carrier(struct net_device *dev, bool new_carrier)
9157 const struct net_device_ops *ops = dev->netdev_ops;
9159 if (!ops->ndo_change_carrier)
9161 if (!netif_device_present(dev))
9163 return ops->ndo_change_carrier(dev, new_carrier);
9167 * dev_get_phys_port_id - Get device physical port ID
9171 * Get device physical port ID
9173 int dev_get_phys_port_id(struct net_device *dev,
9174 struct netdev_phys_item_id *ppid)
9176 const struct net_device_ops *ops = dev->netdev_ops;
9178 if (!ops->ndo_get_phys_port_id)
9180 return ops->ndo_get_phys_port_id(dev, ppid);
9184 * dev_get_phys_port_name - Get device physical port name
9187 * @len: limit of bytes to copy to name
9189 * Get device physical port name
9191 int dev_get_phys_port_name(struct net_device *dev,
9192 char *name, size_t len)
9194 const struct net_device_ops *ops = dev->netdev_ops;
9197 if (ops->ndo_get_phys_port_name) {
9198 err = ops->ndo_get_phys_port_name(dev, name, len);
9199 if (err != -EOPNOTSUPP)
9202 return devlink_compat_phys_port_name_get(dev, name, len);
9206 * dev_get_port_parent_id - Get the device's port parent identifier
9207 * @dev: network device
9208 * @ppid: pointer to a storage for the port's parent identifier
9209 * @recurse: allow/disallow recursion to lower devices
9211 * Get the devices's port parent identifier
9213 int dev_get_port_parent_id(struct net_device *dev,
9214 struct netdev_phys_item_id *ppid,
9217 const struct net_device_ops *ops = dev->netdev_ops;
9218 struct netdev_phys_item_id first = { };
9219 struct net_device *lower_dev;
9220 struct list_head *iter;
9223 if (ops->ndo_get_port_parent_id) {
9224 err = ops->ndo_get_port_parent_id(dev, ppid);
9225 if (err != -EOPNOTSUPP)
9229 err = devlink_compat_switch_id_get(dev, ppid);
9230 if (!recurse || err != -EOPNOTSUPP)
9233 netdev_for_each_lower_dev(dev, lower_dev, iter) {
9234 err = dev_get_port_parent_id(lower_dev, ppid, true);
9239 else if (memcmp(&first, ppid, sizeof(*ppid)))
9245 EXPORT_SYMBOL(dev_get_port_parent_id);
9248 * netdev_port_same_parent_id - Indicate if two network devices have
9249 * the same port parent identifier
9250 * @a: first network device
9251 * @b: second network device
9253 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9255 struct netdev_phys_item_id a_id = { };
9256 struct netdev_phys_item_id b_id = { };
9258 if (dev_get_port_parent_id(a, &a_id, true) ||
9259 dev_get_port_parent_id(b, &b_id, true))
9262 return netdev_phys_item_id_same(&a_id, &b_id);
9264 EXPORT_SYMBOL(netdev_port_same_parent_id);
9267 * dev_change_proto_down - set carrier according to proto_down.
9270 * @proto_down: new value
9272 int dev_change_proto_down(struct net_device *dev, bool proto_down)
9274 if (!dev->change_proto_down)
9276 if (!netif_device_present(dev))
9279 netif_carrier_off(dev);
9281 netif_carrier_on(dev);
9282 WRITE_ONCE(dev->proto_down, proto_down);
9287 * dev_change_proto_down_reason - proto down reason
9290 * @mask: proto down mask
9291 * @value: proto down value
9293 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
9296 u32 proto_down_reason;
9300 proto_down_reason = value;
9302 proto_down_reason = dev->proto_down_reason;
9303 for_each_set_bit(b, &mask, 32) {
9304 if (value & (1 << b))
9305 proto_down_reason |= BIT(b);
9307 proto_down_reason &= ~BIT(b);
9310 WRITE_ONCE(dev->proto_down_reason, proto_down_reason);
9313 struct bpf_xdp_link {
9314 struct bpf_link link;
9315 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9319 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9321 if (flags & XDP_FLAGS_HW_MODE)
9323 if (flags & XDP_FLAGS_DRV_MODE)
9324 return XDP_MODE_DRV;
9325 if (flags & XDP_FLAGS_SKB_MODE)
9326 return XDP_MODE_SKB;
9327 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9330 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9334 return generic_xdp_install;
9337 return dev->netdev_ops->ndo_bpf;
9343 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9344 enum bpf_xdp_mode mode)
9346 return dev->xdp_state[mode].link;
9349 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9350 enum bpf_xdp_mode mode)
9352 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9355 return link->link.prog;
9356 return dev->xdp_state[mode].prog;
9359 u8 dev_xdp_prog_count(struct net_device *dev)
9364 for (i = 0; i < __MAX_XDP_MODE; i++)
9365 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9369 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9371 int dev_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
9373 if (!dev->netdev_ops->ndo_bpf)
9376 if (dev_get_min_mp_channel_count(dev)) {
9377 NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
9381 return dev->netdev_ops->ndo_bpf(dev, bpf);
9383 EXPORT_SYMBOL_GPL(dev_xdp_propagate);
9385 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9387 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9389 return prog ? prog->aux->id : 0;
9392 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9393 struct bpf_xdp_link *link)
9395 dev->xdp_state[mode].link = link;
9396 dev->xdp_state[mode].prog = NULL;
9399 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9400 struct bpf_prog *prog)
9402 dev->xdp_state[mode].link = NULL;
9403 dev->xdp_state[mode].prog = prog;
9406 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9407 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9408 u32 flags, struct bpf_prog *prog)
9410 struct netdev_bpf xdp;
9413 if (dev_get_min_mp_channel_count(dev)) {
9414 NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
9418 memset(&xdp, 0, sizeof(xdp));
9419 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9420 xdp.extack = extack;
9424 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9425 * "moved" into driver), so they don't increment it on their own, but
9426 * they do decrement refcnt when program is detached or replaced.
9427 * Given net_device also owns link/prog, we need to bump refcnt here
9428 * to prevent drivers from underflowing it.
9432 err = bpf_op(dev, &xdp);
9439 if (mode != XDP_MODE_HW)
9440 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9445 static void dev_xdp_uninstall(struct net_device *dev)
9447 struct bpf_xdp_link *link;
9448 struct bpf_prog *prog;
9449 enum bpf_xdp_mode mode;
9454 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9455 prog = dev_xdp_prog(dev, mode);
9459 bpf_op = dev_xdp_bpf_op(dev, mode);
9463 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9465 /* auto-detach link from net device */
9466 link = dev_xdp_link(dev, mode);
9472 dev_xdp_set_link(dev, mode, NULL);
9476 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9477 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9478 struct bpf_prog *old_prog, u32 flags)
9480 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9481 struct bpf_prog *cur_prog;
9482 struct net_device *upper;
9483 struct list_head *iter;
9484 enum bpf_xdp_mode mode;
9490 /* either link or prog attachment, never both */
9491 if (link && (new_prog || old_prog))
9493 /* link supports only XDP mode flags */
9494 if (link && (flags & ~XDP_FLAGS_MODES)) {
9495 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9498 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9499 if (num_modes > 1) {
9500 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9503 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9504 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9505 NL_SET_ERR_MSG(extack,
9506 "More than one program loaded, unset mode is ambiguous");
9509 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9510 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9511 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9515 mode = dev_xdp_mode(dev, flags);
9516 /* can't replace attached link */
9517 if (dev_xdp_link(dev, mode)) {
9518 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9522 /* don't allow if an upper device already has a program */
9523 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9524 if (dev_xdp_prog_count(upper) > 0) {
9525 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9530 cur_prog = dev_xdp_prog(dev, mode);
9531 /* can't replace attached prog with link */
9532 if (link && cur_prog) {
9533 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9536 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9537 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9541 /* put effective new program into new_prog */
9543 new_prog = link->link.prog;
9546 bool offload = mode == XDP_MODE_HW;
9547 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9548 ? XDP_MODE_DRV : XDP_MODE_SKB;
9550 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9551 NL_SET_ERR_MSG(extack, "XDP program already attached");
9554 if (!offload && dev_xdp_prog(dev, other_mode)) {
9555 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9558 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9559 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9562 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9563 NL_SET_ERR_MSG(extack, "Program bound to different device");
9566 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9567 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9570 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9571 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9576 /* don't call drivers if the effective program didn't change */
9577 if (new_prog != cur_prog) {
9578 bpf_op = dev_xdp_bpf_op(dev, mode);
9580 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9584 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9590 dev_xdp_set_link(dev, mode, link);
9592 dev_xdp_set_prog(dev, mode, new_prog);
9594 bpf_prog_put(cur_prog);
9599 static int dev_xdp_attach_link(struct net_device *dev,
9600 struct netlink_ext_ack *extack,
9601 struct bpf_xdp_link *link)
9603 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9606 static int dev_xdp_detach_link(struct net_device *dev,
9607 struct netlink_ext_ack *extack,
9608 struct bpf_xdp_link *link)
9610 enum bpf_xdp_mode mode;
9615 mode = dev_xdp_mode(dev, link->flags);
9616 if (dev_xdp_link(dev, mode) != link)
9619 bpf_op = dev_xdp_bpf_op(dev, mode);
9620 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9621 dev_xdp_set_link(dev, mode, NULL);
9625 static void bpf_xdp_link_release(struct bpf_link *link)
9627 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9631 /* if racing with net_device's tear down, xdp_link->dev might be
9632 * already NULL, in which case link was already auto-detached
9634 if (xdp_link->dev) {
9635 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9636 xdp_link->dev = NULL;
9642 static int bpf_xdp_link_detach(struct bpf_link *link)
9644 bpf_xdp_link_release(link);
9648 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9650 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9655 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9656 struct seq_file *seq)
9658 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9663 ifindex = xdp_link->dev->ifindex;
9666 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9669 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9670 struct bpf_link_info *info)
9672 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9677 ifindex = xdp_link->dev->ifindex;
9680 info->xdp.ifindex = ifindex;
9684 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9685 struct bpf_prog *old_prog)
9687 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9688 enum bpf_xdp_mode mode;
9694 /* link might have been auto-released already, so fail */
9695 if (!xdp_link->dev) {
9700 if (old_prog && link->prog != old_prog) {
9704 old_prog = link->prog;
9705 if (old_prog->type != new_prog->type ||
9706 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9711 if (old_prog == new_prog) {
9712 /* no-op, don't disturb drivers */
9713 bpf_prog_put(new_prog);
9717 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9718 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9719 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9720 xdp_link->flags, new_prog);
9724 old_prog = xchg(&link->prog, new_prog);
9725 bpf_prog_put(old_prog);
9732 static const struct bpf_link_ops bpf_xdp_link_lops = {
9733 .release = bpf_xdp_link_release,
9734 .dealloc = bpf_xdp_link_dealloc,
9735 .detach = bpf_xdp_link_detach,
9736 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9737 .fill_link_info = bpf_xdp_link_fill_link_info,
9738 .update_prog = bpf_xdp_link_update,
9741 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9743 struct net *net = current->nsproxy->net_ns;
9744 struct bpf_link_primer link_primer;
9745 struct netlink_ext_ack extack = {};
9746 struct bpf_xdp_link *link;
9747 struct net_device *dev;
9751 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9757 link = kzalloc(sizeof(*link), GFP_USER);
9763 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9765 link->flags = attr->link_create.flags;
9767 err = bpf_link_prime(&link->link, &link_primer);
9773 err = dev_xdp_attach_link(dev, &extack, link);
9778 bpf_link_cleanup(&link_primer);
9779 trace_bpf_xdp_link_attach_failed(extack._msg);
9783 fd = bpf_link_settle(&link_primer);
9784 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9797 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9799 * @extack: netlink extended ack
9800 * @fd: new program fd or negative value to clear
9801 * @expected_fd: old program fd that userspace expects to replace or clear
9802 * @flags: xdp-related flags
9804 * Set or clear a bpf program for a device
9806 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9807 int fd, int expected_fd, u32 flags)
9809 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9810 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9816 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9817 mode != XDP_MODE_SKB);
9818 if (IS_ERR(new_prog))
9819 return PTR_ERR(new_prog);
9822 if (expected_fd >= 0) {
9823 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9824 mode != XDP_MODE_SKB);
9825 if (IS_ERR(old_prog)) {
9826 err = PTR_ERR(old_prog);
9832 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9835 if (err && new_prog)
9836 bpf_prog_put(new_prog);
9838 bpf_prog_put(old_prog);
9842 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
9848 for (i = dev->real_num_rx_queues - 1; i >= 0; i--)
9849 if (dev->_rx[i].mp_params.mp_priv)
9850 /* The channel count is the idx plus 1. */
9857 * dev_index_reserve() - allocate an ifindex in a namespace
9858 * @net: the applicable net namespace
9859 * @ifindex: requested ifindex, pass %0 to get one allocated
9861 * Allocate a ifindex for a new device. Caller must either use the ifindex
9862 * to store the device (via list_netdevice()) or call dev_index_release()
9863 * to give the index up.
9865 * Return: a suitable unique value for a new device interface number or -errno.
9867 static int dev_index_reserve(struct net *net, u32 ifindex)
9871 if (ifindex > INT_MAX) {
9872 DEBUG_NET_WARN_ON_ONCE(1);
9877 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
9878 xa_limit_31b, &net->ifindex, GFP_KERNEL);
9880 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
9887 static void dev_index_release(struct net *net, int ifindex)
9889 /* Expect only unused indexes, unlist_netdevice() removes the used */
9890 WARN_ON(xa_erase(&net->dev_by_index, ifindex));
9893 /* Delayed registration/unregisteration */
9894 LIST_HEAD(net_todo_list);
9895 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9896 atomic_t dev_unreg_count = ATOMIC_INIT(0);
9898 static void net_set_todo(struct net_device *dev)
9900 list_add_tail(&dev->todo_list, &net_todo_list);
9903 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9904 struct net_device *upper, netdev_features_t features)
9906 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9907 netdev_features_t feature;
9910 for_each_netdev_feature(upper_disables, feature_bit) {
9911 feature = __NETIF_F_BIT(feature_bit);
9912 if (!(upper->wanted_features & feature)
9913 && (features & feature)) {
9914 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9915 &feature, upper->name);
9916 features &= ~feature;
9923 static void netdev_sync_lower_features(struct net_device *upper,
9924 struct net_device *lower, netdev_features_t features)
9926 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9927 netdev_features_t feature;
9930 for_each_netdev_feature(upper_disables, feature_bit) {
9931 feature = __NETIF_F_BIT(feature_bit);
9932 if (!(features & feature) && (lower->features & feature)) {
9933 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9934 &feature, lower->name);
9935 lower->wanted_features &= ~feature;
9936 __netdev_update_features(lower);
9938 if (unlikely(lower->features & feature))
9939 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9940 &feature, lower->name);
9942 netdev_features_change(lower);
9947 static bool netdev_has_ip_or_hw_csum(netdev_features_t features)
9949 netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
9950 bool ip_csum = (features & ip_csum_mask) == ip_csum_mask;
9951 bool hw_csum = features & NETIF_F_HW_CSUM;
9953 return ip_csum || hw_csum;
9956 static netdev_features_t netdev_fix_features(struct net_device *dev,
9957 netdev_features_t features)
9959 /* Fix illegal checksum combinations */
9960 if ((features & NETIF_F_HW_CSUM) &&
9961 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9962 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9963 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9966 /* TSO requires that SG is present as well. */
9967 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9968 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9969 features &= ~NETIF_F_ALL_TSO;
9972 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9973 !(features & NETIF_F_IP_CSUM)) {
9974 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9975 features &= ~NETIF_F_TSO;
9976 features &= ~NETIF_F_TSO_ECN;
9979 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9980 !(features & NETIF_F_IPV6_CSUM)) {
9981 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9982 features &= ~NETIF_F_TSO6;
9985 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9986 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9987 features &= ~NETIF_F_TSO_MANGLEID;
9989 /* TSO ECN requires that TSO is present as well. */
9990 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9991 features &= ~NETIF_F_TSO_ECN;
9993 /* Software GSO depends on SG. */
9994 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9995 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9996 features &= ~NETIF_F_GSO;
9999 /* GSO partial features require GSO partial be set */
10000 if ((features & dev->gso_partial_features) &&
10001 !(features & NETIF_F_GSO_PARTIAL)) {
10003 "Dropping partially supported GSO features since no GSO partial.\n");
10004 features &= ~dev->gso_partial_features;
10007 if (!(features & NETIF_F_RXCSUM)) {
10008 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
10009 * successfully merged by hardware must also have the
10010 * checksum verified by hardware. If the user does not
10011 * want to enable RXCSUM, logically, we should disable GRO_HW.
10013 if (features & NETIF_F_GRO_HW) {
10014 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
10015 features &= ~NETIF_F_GRO_HW;
10019 /* LRO/HW-GRO features cannot be combined with RX-FCS */
10020 if (features & NETIF_F_RXFCS) {
10021 if (features & NETIF_F_LRO) {
10022 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
10023 features &= ~NETIF_F_LRO;
10026 if (features & NETIF_F_GRO_HW) {
10027 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
10028 features &= ~NETIF_F_GRO_HW;
10032 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
10033 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
10034 features &= ~NETIF_F_LRO;
10037 if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) {
10038 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
10039 features &= ~NETIF_F_HW_TLS_TX;
10042 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
10043 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
10044 features &= ~NETIF_F_HW_TLS_RX;
10047 if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) {
10048 netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n");
10049 features &= ~NETIF_F_GSO_UDP_L4;
10055 int __netdev_update_features(struct net_device *dev)
10057 struct net_device *upper, *lower;
10058 netdev_features_t features;
10059 struct list_head *iter;
10064 features = netdev_get_wanted_features(dev);
10066 if (dev->netdev_ops->ndo_fix_features)
10067 features = dev->netdev_ops->ndo_fix_features(dev, features);
10069 /* driver might be less strict about feature dependencies */
10070 features = netdev_fix_features(dev, features);
10072 /* some features can't be enabled if they're off on an upper device */
10073 netdev_for_each_upper_dev_rcu(dev, upper, iter)
10074 features = netdev_sync_upper_features(dev, upper, features);
10076 if (dev->features == features)
10079 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
10080 &dev->features, &features);
10082 if (dev->netdev_ops->ndo_set_features)
10083 err = dev->netdev_ops->ndo_set_features(dev, features);
10087 if (unlikely(err < 0)) {
10089 "set_features() failed (%d); wanted %pNF, left %pNF\n",
10090 err, &features, &dev->features);
10091 /* return non-0 since some features might have changed and
10092 * it's better to fire a spurious notification than miss it
10098 /* some features must be disabled on lower devices when disabled
10099 * on an upper device (think: bonding master or bridge)
10101 netdev_for_each_lower_dev(dev, lower, iter)
10102 netdev_sync_lower_features(dev, lower, features);
10105 netdev_features_t diff = features ^ dev->features;
10107 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
10108 /* udp_tunnel_{get,drop}_rx_info both need
10109 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
10110 * device, or they won't do anything.
10111 * Thus we need to update dev->features
10112 * *before* calling udp_tunnel_get_rx_info,
10113 * but *after* calling udp_tunnel_drop_rx_info.
10115 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
10116 dev->features = features;
10117 udp_tunnel_get_rx_info(dev);
10119 udp_tunnel_drop_rx_info(dev);
10123 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
10124 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
10125 dev->features = features;
10126 err |= vlan_get_rx_ctag_filter_info(dev);
10128 vlan_drop_rx_ctag_filter_info(dev);
10132 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
10133 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
10134 dev->features = features;
10135 err |= vlan_get_rx_stag_filter_info(dev);
10137 vlan_drop_rx_stag_filter_info(dev);
10141 dev->features = features;
10144 return err < 0 ? 0 : 1;
10148 * netdev_update_features - recalculate device features
10149 * @dev: the device to check
10151 * Recalculate dev->features set and send notifications if it
10152 * has changed. Should be called after driver or hardware dependent
10153 * conditions might have changed that influence the features.
10155 void netdev_update_features(struct net_device *dev)
10157 if (__netdev_update_features(dev))
10158 netdev_features_change(dev);
10160 EXPORT_SYMBOL(netdev_update_features);
10163 * netdev_change_features - recalculate device features
10164 * @dev: the device to check
10166 * Recalculate dev->features set and send notifications even
10167 * if they have not changed. Should be called instead of
10168 * netdev_update_features() if also dev->vlan_features might
10169 * have changed to allow the changes to be propagated to stacked
10172 void netdev_change_features(struct net_device *dev)
10174 __netdev_update_features(dev);
10175 netdev_features_change(dev);
10177 EXPORT_SYMBOL(netdev_change_features);
10180 * netif_stacked_transfer_operstate - transfer operstate
10181 * @rootdev: the root or lower level device to transfer state from
10182 * @dev: the device to transfer operstate to
10184 * Transfer operational state from root to device. This is normally
10185 * called when a stacking relationship exists between the root
10186 * device and the device(a leaf device).
10188 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
10189 struct net_device *dev)
10191 if (rootdev->operstate == IF_OPER_DORMANT)
10192 netif_dormant_on(dev);
10194 netif_dormant_off(dev);
10196 if (rootdev->operstate == IF_OPER_TESTING)
10197 netif_testing_on(dev);
10199 netif_testing_off(dev);
10201 if (netif_carrier_ok(rootdev))
10202 netif_carrier_on(dev);
10204 netif_carrier_off(dev);
10206 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
10208 static int netif_alloc_rx_queues(struct net_device *dev)
10210 unsigned int i, count = dev->num_rx_queues;
10211 struct netdev_rx_queue *rx;
10212 size_t sz = count * sizeof(*rx);
10217 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10223 for (i = 0; i < count; i++) {
10226 /* XDP RX-queue setup */
10227 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
10234 /* Rollback successful reg's and free other resources */
10236 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
10242 static void netif_free_rx_queues(struct net_device *dev)
10244 unsigned int i, count = dev->num_rx_queues;
10246 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
10250 for (i = 0; i < count; i++)
10251 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
10256 static void netdev_init_one_queue(struct net_device *dev,
10257 struct netdev_queue *queue, void *_unused)
10259 /* Initialize queue lock */
10260 spin_lock_init(&queue->_xmit_lock);
10261 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
10262 queue->xmit_lock_owner = -1;
10263 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
10266 dql_init(&queue->dql, HZ);
10270 static void netif_free_tx_queues(struct net_device *dev)
10275 static int netif_alloc_netdev_queues(struct net_device *dev)
10277 unsigned int count = dev->num_tx_queues;
10278 struct netdev_queue *tx;
10279 size_t sz = count * sizeof(*tx);
10281 if (count < 1 || count > 0xffff)
10284 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10290 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
10291 spin_lock_init(&dev->tx_global_lock);
10296 void netif_tx_stop_all_queues(struct net_device *dev)
10300 for (i = 0; i < dev->num_tx_queues; i++) {
10301 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
10303 netif_tx_stop_queue(txq);
10306 EXPORT_SYMBOL(netif_tx_stop_all_queues);
10308 static int netdev_do_alloc_pcpu_stats(struct net_device *dev)
10312 /* Drivers implementing ndo_get_peer_dev must support tstat
10313 * accounting, so that skb_do_redirect() can bump the dev's
10314 * RX stats upon network namespace switch.
10316 if (dev->netdev_ops->ndo_get_peer_dev &&
10317 dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS)
10318 return -EOPNOTSUPP;
10320 switch (dev->pcpu_stat_type) {
10321 case NETDEV_PCPU_STAT_NONE:
10323 case NETDEV_PCPU_STAT_LSTATS:
10324 v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
10326 case NETDEV_PCPU_STAT_TSTATS:
10327 v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
10329 case NETDEV_PCPU_STAT_DSTATS:
10330 v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
10336 return v ? 0 : -ENOMEM;
10339 static void netdev_do_free_pcpu_stats(struct net_device *dev)
10341 switch (dev->pcpu_stat_type) {
10342 case NETDEV_PCPU_STAT_NONE:
10344 case NETDEV_PCPU_STAT_LSTATS:
10345 free_percpu(dev->lstats);
10347 case NETDEV_PCPU_STAT_TSTATS:
10348 free_percpu(dev->tstats);
10350 case NETDEV_PCPU_STAT_DSTATS:
10351 free_percpu(dev->dstats);
10356 static void netdev_free_phy_link_topology(struct net_device *dev)
10358 struct phy_link_topology *topo = dev->link_topo;
10360 if (IS_ENABLED(CONFIG_PHYLIB) && topo) {
10361 xa_destroy(&topo->phys);
10363 dev->link_topo = NULL;
10368 * register_netdevice() - register a network device
10369 * @dev: device to register
10371 * Take a prepared network device structure and make it externally accessible.
10372 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10373 * Callers must hold the rtnl lock - you may want register_netdev()
10376 int register_netdevice(struct net_device *dev)
10379 struct net *net = dev_net(dev);
10381 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10382 NETDEV_FEATURE_COUNT);
10383 BUG_ON(dev_boot_phase);
10388 /* When net_device's are persistent, this will be fatal. */
10389 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10392 ret = ethtool_check_ops(dev->ethtool_ops);
10396 /* rss ctx ID 0 is reserved for the default context, start from 1 */
10397 xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1);
10398 mutex_init(&dev->ethtool->rss_lock);
10400 spin_lock_init(&dev->addr_list_lock);
10401 netdev_set_addr_lockdep_class(dev);
10403 ret = dev_get_valid_name(net, dev, dev->name);
10408 dev->name_node = netdev_name_node_head_alloc(dev);
10409 if (!dev->name_node)
10412 /* Init, if this function is available */
10413 if (dev->netdev_ops->ndo_init) {
10414 ret = dev->netdev_ops->ndo_init(dev);
10418 goto err_free_name;
10422 if (((dev->hw_features | dev->features) &
10423 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10424 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10425 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10426 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10431 ret = netdev_do_alloc_pcpu_stats(dev);
10435 ret = dev_index_reserve(net, dev->ifindex);
10437 goto err_free_pcpu;
10438 dev->ifindex = ret;
10440 /* Transfer changeable features to wanted_features and enable
10441 * software offloads (GSO and GRO).
10443 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10444 dev->features |= NETIF_F_SOFT_FEATURES;
10446 if (dev->udp_tunnel_nic_info) {
10447 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10448 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10451 dev->wanted_features = dev->features & dev->hw_features;
10453 if (!(dev->flags & IFF_LOOPBACK))
10454 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10456 /* If IPv4 TCP segmentation offload is supported we should also
10457 * allow the device to enable segmenting the frame with the option
10458 * of ignoring a static IP ID value. This doesn't enable the
10459 * feature itself but allows the user to enable it later.
10461 if (dev->hw_features & NETIF_F_TSO)
10462 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10463 if (dev->vlan_features & NETIF_F_TSO)
10464 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10465 if (dev->mpls_features & NETIF_F_TSO)
10466 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10467 if (dev->hw_enc_features & NETIF_F_TSO)
10468 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10470 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10472 dev->vlan_features |= NETIF_F_HIGHDMA;
10474 /* Make NETIF_F_SG inheritable to tunnel devices.
10476 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10478 /* Make NETIF_F_SG inheritable to MPLS.
10480 dev->mpls_features |= NETIF_F_SG;
10482 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10483 ret = notifier_to_errno(ret);
10485 goto err_ifindex_release;
10487 ret = netdev_register_kobject(dev);
10489 WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED);
10492 goto err_uninit_notify;
10494 __netdev_update_features(dev);
10497 * Default initial state at registry is that the
10498 * device is present.
10501 set_bit(__LINK_STATE_PRESENT, &dev->state);
10503 linkwatch_init_dev(dev);
10505 dev_init_scheduler(dev);
10507 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10508 list_netdevice(dev);
10510 add_device_randomness(dev->dev_addr, dev->addr_len);
10512 /* If the device has permanent device address, driver should
10513 * set dev_addr and also addr_assign_type should be set to
10514 * NET_ADDR_PERM (default value).
10516 if (dev->addr_assign_type == NET_ADDR_PERM)
10517 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10519 /* Notify protocols, that a new device appeared. */
10520 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10521 ret = notifier_to_errno(ret);
10523 /* Expect explicit free_netdev() on failure */
10524 dev->needs_free_netdev = false;
10525 unregister_netdevice_queue(dev, NULL);
10529 * Prevent userspace races by waiting until the network
10530 * device is fully setup before sending notifications.
10532 if (!dev->rtnl_link_ops ||
10533 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10534 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10540 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10541 err_ifindex_release:
10542 dev_index_release(net, dev->ifindex);
10544 netdev_do_free_pcpu_stats(dev);
10546 if (dev->netdev_ops->ndo_uninit)
10547 dev->netdev_ops->ndo_uninit(dev);
10548 if (dev->priv_destructor)
10549 dev->priv_destructor(dev);
10551 netdev_name_node_free(dev->name_node);
10554 EXPORT_SYMBOL(register_netdevice);
10556 /* Initialize the core of a dummy net device.
10557 * This is useful if you are calling this function after alloc_netdev(),
10558 * since it does not memset the net_device fields.
10560 static void init_dummy_netdev_core(struct net_device *dev)
10562 /* make sure we BUG if trying to hit standard
10563 * register/unregister code path
10565 dev->reg_state = NETREG_DUMMY;
10567 /* NAPI wants this */
10568 INIT_LIST_HEAD(&dev->napi_list);
10570 /* a dummy interface is started by default */
10571 set_bit(__LINK_STATE_PRESENT, &dev->state);
10572 set_bit(__LINK_STATE_START, &dev->state);
10574 /* napi_busy_loop stats accounting wants this */
10575 dev_net_set(dev, &init_net);
10577 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10578 * because users of this 'device' dont need to change
10584 * init_dummy_netdev - init a dummy network device for NAPI
10585 * @dev: device to init
10587 * This takes a network device structure and initializes the minimum
10588 * amount of fields so it can be used to schedule NAPI polls without
10589 * registering a full blown interface. This is to be used by drivers
10590 * that need to tie several hardware interfaces to a single NAPI
10591 * poll scheduler due to HW limitations.
10593 void init_dummy_netdev(struct net_device *dev)
10595 /* Clear everything. Note we don't initialize spinlocks
10596 * as they aren't supposed to be taken by any of the
10597 * NAPI code and this dummy netdev is supposed to be
10598 * only ever used for NAPI polls
10600 memset(dev, 0, sizeof(struct net_device));
10601 init_dummy_netdev_core(dev);
10603 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10606 * register_netdev - register a network device
10607 * @dev: device to register
10609 * Take a completed network device structure and add it to the kernel
10610 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10611 * chain. 0 is returned on success. A negative errno code is returned
10612 * on a failure to set up the device, or if the name is a duplicate.
10614 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10615 * and expands the device name if you passed a format string to
10618 int register_netdev(struct net_device *dev)
10622 if (rtnl_lock_killable())
10624 err = register_netdevice(dev);
10628 EXPORT_SYMBOL(register_netdev);
10630 int netdev_refcnt_read(const struct net_device *dev)
10632 #ifdef CONFIG_PCPU_DEV_REFCNT
10635 for_each_possible_cpu(i)
10636 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10639 return refcount_read(&dev->dev_refcnt);
10642 EXPORT_SYMBOL(netdev_refcnt_read);
10644 int netdev_unregister_timeout_secs __read_mostly = 10;
10646 #define WAIT_REFS_MIN_MSECS 1
10647 #define WAIT_REFS_MAX_MSECS 250
10649 * netdev_wait_allrefs_any - wait until all references are gone.
10650 * @list: list of net_devices to wait on
10652 * This is called when unregistering network devices.
10654 * Any protocol or device that holds a reference should register
10655 * for netdevice notification, and cleanup and put back the
10656 * reference if they receive an UNREGISTER event.
10657 * We can get stuck here if buggy protocols don't correctly
10660 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10662 unsigned long rebroadcast_time, warning_time;
10663 struct net_device *dev;
10666 rebroadcast_time = warning_time = jiffies;
10668 list_for_each_entry(dev, list, todo_list)
10669 if (netdev_refcnt_read(dev) == 1)
10673 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10676 /* Rebroadcast unregister notification */
10677 list_for_each_entry(dev, list, todo_list)
10678 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10684 list_for_each_entry(dev, list, todo_list)
10685 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10687 /* We must not have linkwatch events
10688 * pending on unregister. If this
10689 * happens, we simply run the queue
10690 * unscheduled, resulting in a noop
10693 linkwatch_run_queue();
10699 rebroadcast_time = jiffies;
10705 wait = WAIT_REFS_MIN_MSECS;
10708 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10711 list_for_each_entry(dev, list, todo_list)
10712 if (netdev_refcnt_read(dev) == 1)
10715 if (time_after(jiffies, warning_time +
10716 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10717 list_for_each_entry(dev, list, todo_list) {
10718 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10719 dev->name, netdev_refcnt_read(dev));
10720 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10723 warning_time = jiffies;
10728 /* The sequence is:
10732 * register_netdevice(x1);
10733 * register_netdevice(x2);
10735 * unregister_netdevice(y1);
10736 * unregister_netdevice(y2);
10742 * We are invoked by rtnl_unlock().
10743 * This allows us to deal with problems:
10744 * 1) We can delete sysfs objects which invoke hotplug
10745 * without deadlocking with linkwatch via keventd.
10746 * 2) Since we run with the RTNL semaphore not held, we can sleep
10747 * safely in order to wait for the netdev refcnt to drop to zero.
10749 * We must not return until all unregister events added during
10750 * the interval the lock was held have been completed.
10752 void netdev_run_todo(void)
10754 struct net_device *dev, *tmp;
10755 struct list_head list;
10757 #ifdef CONFIG_LOCKDEP
10758 struct list_head unlink_list;
10760 list_replace_init(&net_unlink_list, &unlink_list);
10762 while (!list_empty(&unlink_list)) {
10763 struct net_device *dev = list_first_entry(&unlink_list,
10766 list_del_init(&dev->unlink_list);
10767 dev->nested_level = dev->lower_level - 1;
10771 /* Snapshot list, allow later requests */
10772 list_replace_init(&net_todo_list, &list);
10776 /* Wait for rcu callbacks to finish before next phase */
10777 if (!list_empty(&list))
10780 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10781 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10782 netdev_WARN(dev, "run_todo but not unregistering\n");
10783 list_del(&dev->todo_list);
10787 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED);
10788 linkwatch_sync_dev(dev);
10792 while (!list_empty(&list)) {
10793 dev = netdev_wait_allrefs_any(&list);
10794 list_del(&dev->todo_list);
10797 BUG_ON(netdev_refcnt_read(dev) != 1);
10798 BUG_ON(!list_empty(&dev->ptype_all));
10799 BUG_ON(!list_empty(&dev->ptype_specific));
10800 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10801 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10803 netdev_do_free_pcpu_stats(dev);
10804 if (dev->priv_destructor)
10805 dev->priv_destructor(dev);
10806 if (dev->needs_free_netdev)
10811 /* Free network device */
10812 kobject_put(&dev->dev.kobj);
10814 if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count))
10815 wake_up(&netdev_unregistering_wq);
10818 /* Collate per-cpu network dstats statistics
10820 * Read per-cpu network statistics from dev->dstats and populate the related
10823 static void dev_fetch_dstats(struct rtnl_link_stats64 *s,
10824 const struct pcpu_dstats __percpu *dstats)
10828 for_each_possible_cpu(cpu) {
10829 u64 rx_packets, rx_bytes, rx_drops;
10830 u64 tx_packets, tx_bytes, tx_drops;
10831 const struct pcpu_dstats *stats;
10832 unsigned int start;
10834 stats = per_cpu_ptr(dstats, cpu);
10836 start = u64_stats_fetch_begin(&stats->syncp);
10837 rx_packets = u64_stats_read(&stats->rx_packets);
10838 rx_bytes = u64_stats_read(&stats->rx_bytes);
10839 rx_drops = u64_stats_read(&stats->rx_drops);
10840 tx_packets = u64_stats_read(&stats->tx_packets);
10841 tx_bytes = u64_stats_read(&stats->tx_bytes);
10842 tx_drops = u64_stats_read(&stats->tx_drops);
10843 } while (u64_stats_fetch_retry(&stats->syncp, start));
10845 s->rx_packets += rx_packets;
10846 s->rx_bytes += rx_bytes;
10847 s->rx_dropped += rx_drops;
10848 s->tx_packets += tx_packets;
10849 s->tx_bytes += tx_bytes;
10850 s->tx_dropped += tx_drops;
10854 /* ndo_get_stats64 implementation for dtstats-based accounting.
10856 * Populate @s from dev->stats and dev->dstats. This is used internally by the
10857 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection.
10859 static void dev_get_dstats64(const struct net_device *dev,
10860 struct rtnl_link_stats64 *s)
10862 netdev_stats_to_stats64(s, &dev->stats);
10863 dev_fetch_dstats(s, dev->dstats);
10866 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10867 * all the same fields in the same order as net_device_stats, with only
10868 * the type differing, but rtnl_link_stats64 may have additional fields
10869 * at the end for newer counters.
10871 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10872 const struct net_device_stats *netdev_stats)
10874 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10875 const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10876 u64 *dst = (u64 *)stats64;
10878 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10879 for (i = 0; i < n; i++)
10880 dst[i] = (unsigned long)atomic_long_read(&src[i]);
10881 /* zero out counters that only exist in rtnl_link_stats64 */
10882 memset((char *)stats64 + n * sizeof(u64), 0,
10883 sizeof(*stats64) - n * sizeof(u64));
10885 EXPORT_SYMBOL(netdev_stats_to_stats64);
10887 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc(
10888 struct net_device *dev)
10890 struct net_device_core_stats __percpu *p;
10892 p = alloc_percpu_gfp(struct net_device_core_stats,
10893 GFP_ATOMIC | __GFP_NOWARN);
10895 if (p && cmpxchg(&dev->core_stats, NULL, p))
10898 /* This READ_ONCE() pairs with the cmpxchg() above */
10899 return READ_ONCE(dev->core_stats);
10902 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset)
10904 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10905 struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats);
10906 unsigned long __percpu *field;
10908 if (unlikely(!p)) {
10909 p = netdev_core_stats_alloc(dev);
10914 field = (unsigned long __percpu *)((void __percpu *)p + offset);
10915 this_cpu_inc(*field);
10917 EXPORT_SYMBOL_GPL(netdev_core_stats_inc);
10920 * dev_get_stats - get network device statistics
10921 * @dev: device to get statistics from
10922 * @storage: place to store stats
10924 * Get network statistics from device. Return @storage.
10925 * The device driver may provide its own method by setting
10926 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10927 * otherwise the internal statistics structure is used.
10929 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10930 struct rtnl_link_stats64 *storage)
10932 const struct net_device_ops *ops = dev->netdev_ops;
10933 const struct net_device_core_stats __percpu *p;
10935 if (ops->ndo_get_stats64) {
10936 memset(storage, 0, sizeof(*storage));
10937 ops->ndo_get_stats64(dev, storage);
10938 } else if (ops->ndo_get_stats) {
10939 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10940 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) {
10941 dev_get_tstats64(dev, storage);
10942 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) {
10943 dev_get_dstats64(dev, storage);
10945 netdev_stats_to_stats64(storage, &dev->stats);
10948 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10949 p = READ_ONCE(dev->core_stats);
10951 const struct net_device_core_stats *core_stats;
10954 for_each_possible_cpu(i) {
10955 core_stats = per_cpu_ptr(p, i);
10956 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10957 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10958 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10959 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10964 EXPORT_SYMBOL(dev_get_stats);
10967 * dev_fetch_sw_netstats - get per-cpu network device statistics
10968 * @s: place to store stats
10969 * @netstats: per-cpu network stats to read from
10971 * Read per-cpu network statistics and populate the related fields in @s.
10973 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10974 const struct pcpu_sw_netstats __percpu *netstats)
10978 for_each_possible_cpu(cpu) {
10979 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10980 const struct pcpu_sw_netstats *stats;
10981 unsigned int start;
10983 stats = per_cpu_ptr(netstats, cpu);
10985 start = u64_stats_fetch_begin(&stats->syncp);
10986 rx_packets = u64_stats_read(&stats->rx_packets);
10987 rx_bytes = u64_stats_read(&stats->rx_bytes);
10988 tx_packets = u64_stats_read(&stats->tx_packets);
10989 tx_bytes = u64_stats_read(&stats->tx_bytes);
10990 } while (u64_stats_fetch_retry(&stats->syncp, start));
10992 s->rx_packets += rx_packets;
10993 s->rx_bytes += rx_bytes;
10994 s->tx_packets += tx_packets;
10995 s->tx_bytes += tx_bytes;
10998 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
11001 * dev_get_tstats64 - ndo_get_stats64 implementation
11002 * @dev: device to get statistics from
11003 * @s: place to store stats
11005 * Populate @s from dev->stats and dev->tstats. Can be used as
11006 * ndo_get_stats64() callback.
11008 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
11010 netdev_stats_to_stats64(s, &dev->stats);
11011 dev_fetch_sw_netstats(s, dev->tstats);
11013 EXPORT_SYMBOL_GPL(dev_get_tstats64);
11015 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
11017 struct netdev_queue *queue = dev_ingress_queue(dev);
11019 #ifdef CONFIG_NET_CLS_ACT
11022 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
11025 netdev_init_one_queue(dev, queue, NULL);
11026 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
11027 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
11028 rcu_assign_pointer(dev->ingress_queue, queue);
11033 static const struct ethtool_ops default_ethtool_ops;
11035 void netdev_set_default_ethtool_ops(struct net_device *dev,
11036 const struct ethtool_ops *ops)
11038 if (dev->ethtool_ops == &default_ethtool_ops)
11039 dev->ethtool_ops = ops;
11041 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
11044 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
11045 * @dev: netdev to enable the IRQ coalescing on
11047 * Sets a conservative default for SW IRQ coalescing. Users can use
11048 * sysfs attributes to override the default values.
11050 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
11052 WARN_ON(dev->reg_state == NETREG_REGISTERED);
11054 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
11055 dev->gro_flush_timeout = 20000;
11056 dev->napi_defer_hard_irqs = 1;
11059 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
11062 * alloc_netdev_mqs - allocate network device
11063 * @sizeof_priv: size of private data to allocate space for
11064 * @name: device name format string
11065 * @name_assign_type: origin of device name
11066 * @setup: callback to initialize device
11067 * @txqs: the number of TX subqueues to allocate
11068 * @rxqs: the number of RX subqueues to allocate
11070 * Allocates a struct net_device with private data area for driver use
11071 * and performs basic initialization. Also allocates subqueue structs
11072 * for each queue on the device.
11074 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
11075 unsigned char name_assign_type,
11076 void (*setup)(struct net_device *),
11077 unsigned int txqs, unsigned int rxqs)
11079 struct net_device *dev;
11081 BUG_ON(strlen(name) >= sizeof(dev->name));
11084 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
11089 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
11093 dev = kvzalloc(struct_size(dev, priv, sizeof_priv),
11094 GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
11098 dev->priv_len = sizeof_priv;
11100 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
11101 #ifdef CONFIG_PCPU_DEV_REFCNT
11102 dev->pcpu_refcnt = alloc_percpu(int);
11103 if (!dev->pcpu_refcnt)
11107 refcount_set(&dev->dev_refcnt, 1);
11110 if (dev_addr_init(dev))
11116 dev_net_set(dev, &init_net);
11118 dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
11119 dev->xdp_zc_max_segs = 1;
11120 dev->gso_max_segs = GSO_MAX_SEGS;
11121 dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
11122 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
11123 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
11124 dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
11125 dev->tso_max_segs = TSO_MAX_SEGS;
11126 dev->upper_level = 1;
11127 dev->lower_level = 1;
11128 #ifdef CONFIG_LOCKDEP
11129 dev->nested_level = 0;
11130 INIT_LIST_HEAD(&dev->unlink_list);
11133 INIT_LIST_HEAD(&dev->napi_list);
11134 INIT_LIST_HEAD(&dev->unreg_list);
11135 INIT_LIST_HEAD(&dev->close_list);
11136 INIT_LIST_HEAD(&dev->link_watch_list);
11137 INIT_LIST_HEAD(&dev->adj_list.upper);
11138 INIT_LIST_HEAD(&dev->adj_list.lower);
11139 INIT_LIST_HEAD(&dev->ptype_all);
11140 INIT_LIST_HEAD(&dev->ptype_specific);
11141 INIT_LIST_HEAD(&dev->net_notifier_list);
11142 #ifdef CONFIG_NET_SCHED
11143 hash_init(dev->qdisc_hash);
11146 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
11149 if (!dev->tx_queue_len) {
11150 dev->priv_flags |= IFF_NO_QUEUE;
11151 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
11154 dev->num_tx_queues = txqs;
11155 dev->real_num_tx_queues = txqs;
11156 if (netif_alloc_netdev_queues(dev))
11159 dev->num_rx_queues = rxqs;
11160 dev->real_num_rx_queues = rxqs;
11161 if (netif_alloc_rx_queues(dev))
11163 dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT);
11167 strscpy(dev->name, name);
11168 dev->name_assign_type = name_assign_type;
11169 dev->group = INIT_NETDEV_GROUP;
11170 if (!dev->ethtool_ops)
11171 dev->ethtool_ops = &default_ethtool_ops;
11173 nf_hook_netdev_init(dev);
11182 #ifdef CONFIG_PCPU_DEV_REFCNT
11183 free_percpu(dev->pcpu_refcnt);
11189 EXPORT_SYMBOL(alloc_netdev_mqs);
11192 * free_netdev - free network device
11195 * This function does the last stage of destroying an allocated device
11196 * interface. The reference to the device object is released. If this
11197 * is the last reference then it will be freed.Must be called in process
11200 void free_netdev(struct net_device *dev)
11202 struct napi_struct *p, *n;
11206 /* When called immediately after register_netdevice() failed the unwind
11207 * handling may still be dismantling the device. Handle that case by
11208 * deferring the free.
11210 if (dev->reg_state == NETREG_UNREGISTERING) {
11212 dev->needs_free_netdev = true;
11216 kfree(dev->ethtool);
11217 netif_free_tx_queues(dev);
11218 netif_free_rx_queues(dev);
11220 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
11222 /* Flush device addresses */
11223 dev_addr_flush(dev);
11225 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
11228 ref_tracker_dir_exit(&dev->refcnt_tracker);
11229 #ifdef CONFIG_PCPU_DEV_REFCNT
11230 free_percpu(dev->pcpu_refcnt);
11231 dev->pcpu_refcnt = NULL;
11233 free_percpu(dev->core_stats);
11234 dev->core_stats = NULL;
11235 free_percpu(dev->xdp_bulkq);
11236 dev->xdp_bulkq = NULL;
11238 netdev_free_phy_link_topology(dev);
11240 /* Compatibility with error handling in drivers */
11241 if (dev->reg_state == NETREG_UNINITIALIZED ||
11242 dev->reg_state == NETREG_DUMMY) {
11247 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
11248 WRITE_ONCE(dev->reg_state, NETREG_RELEASED);
11250 /* will free via device release */
11251 put_device(&dev->dev);
11253 EXPORT_SYMBOL(free_netdev);
11256 * alloc_netdev_dummy - Allocate and initialize a dummy net device.
11257 * @sizeof_priv: size of private data to allocate space for
11259 * Return: the allocated net_device on success, NULL otherwise
11261 struct net_device *alloc_netdev_dummy(int sizeof_priv)
11263 return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN,
11264 init_dummy_netdev_core);
11266 EXPORT_SYMBOL_GPL(alloc_netdev_dummy);
11269 * synchronize_net - Synchronize with packet receive processing
11271 * Wait for packets currently being received to be done.
11272 * Does not block later packets from starting.
11274 void synchronize_net(void)
11277 if (rtnl_is_locked())
11278 synchronize_rcu_expedited();
11282 EXPORT_SYMBOL(synchronize_net);
11284 static void netdev_rss_contexts_free(struct net_device *dev)
11286 struct ethtool_rxfh_context *ctx;
11287 unsigned long context;
11289 mutex_lock(&dev->ethtool->rss_lock);
11290 xa_for_each(&dev->ethtool->rss_ctx, context, ctx) {
11291 struct ethtool_rxfh_param rxfh;
11293 rxfh.indir = ethtool_rxfh_context_indir(ctx);
11294 rxfh.key = ethtool_rxfh_context_key(ctx);
11295 rxfh.hfunc = ctx->hfunc;
11296 rxfh.input_xfrm = ctx->input_xfrm;
11297 rxfh.rss_context = context;
11298 rxfh.rss_delete = true;
11300 xa_erase(&dev->ethtool->rss_ctx, context);
11301 if (dev->ethtool_ops->create_rxfh_context)
11302 dev->ethtool_ops->remove_rxfh_context(dev, ctx,
11305 dev->ethtool_ops->set_rxfh(dev, &rxfh, NULL);
11308 xa_destroy(&dev->ethtool->rss_ctx);
11309 mutex_unlock(&dev->ethtool->rss_lock);
11313 * unregister_netdevice_queue - remove device from the kernel
11317 * This function shuts down a device interface and removes it
11318 * from the kernel tables.
11319 * If head not NULL, device is queued to be unregistered later.
11321 * Callers must hold the rtnl semaphore. You may want
11322 * unregister_netdev() instead of this.
11325 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
11330 list_move_tail(&dev->unreg_list, head);
11334 list_add(&dev->unreg_list, &single);
11335 unregister_netdevice_many(&single);
11338 EXPORT_SYMBOL(unregister_netdevice_queue);
11340 void unregister_netdevice_many_notify(struct list_head *head,
11341 u32 portid, const struct nlmsghdr *nlh)
11343 struct net_device *dev, *tmp;
11344 LIST_HEAD(close_head);
11347 BUG_ON(dev_boot_phase);
11350 if (list_empty(head))
11353 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
11354 /* Some devices call without registering
11355 * for initialization unwind. Remove those
11356 * devices and proceed with the remaining.
11358 if (dev->reg_state == NETREG_UNINITIALIZED) {
11359 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
11363 list_del(&dev->unreg_list);
11366 dev->dismantle = true;
11367 BUG_ON(dev->reg_state != NETREG_REGISTERED);
11370 /* If device is running, close it first. */
11371 list_for_each_entry(dev, head, unreg_list)
11372 list_add_tail(&dev->close_list, &close_head);
11373 dev_close_many(&close_head, true);
11375 list_for_each_entry(dev, head, unreg_list) {
11376 /* And unlink it from device chain. */
11377 unlist_netdevice(dev);
11378 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING);
11380 flush_all_backlogs();
11384 list_for_each_entry(dev, head, unreg_list) {
11385 struct sk_buff *skb = NULL;
11387 /* Shutdown queueing discipline. */
11389 dev_tcx_uninstall(dev);
11390 dev_xdp_uninstall(dev);
11391 bpf_dev_bound_netdev_unregister(dev);
11392 dev_dmabuf_uninstall(dev);
11394 netdev_offload_xstats_disable_all(dev);
11396 /* Notify protocols, that we are about to destroy
11397 * this device. They should clean all the things.
11399 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11401 if (!dev->rtnl_link_ops ||
11402 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
11403 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
11404 GFP_KERNEL, NULL, 0,
11408 * Flush the unicast and multicast chains
11413 netdev_name_node_alt_flush(dev);
11414 netdev_name_node_free(dev->name_node);
11416 netdev_rss_contexts_free(dev);
11418 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
11420 if (dev->netdev_ops->ndo_uninit)
11421 dev->netdev_ops->ndo_uninit(dev);
11423 mutex_destroy(&dev->ethtool->rss_lock);
11426 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
11428 /* Notifier chain MUST detach us all upper devices. */
11429 WARN_ON(netdev_has_any_upper_dev(dev));
11430 WARN_ON(netdev_has_any_lower_dev(dev));
11432 /* Remove entries from kobject tree */
11433 netdev_unregister_kobject(dev);
11435 /* Remove XPS queueing entries */
11436 netif_reset_xps_queues_gt(dev, 0);
11442 list_for_each_entry(dev, head, unreg_list) {
11443 netdev_put(dev, &dev->dev_registered_tracker);
11447 atomic_add(cnt, &dev_unreg_count);
11453 * unregister_netdevice_many - unregister many devices
11454 * @head: list of devices
11456 * Note: As most callers use a stack allocated list_head,
11457 * we force a list_del() to make sure stack won't be corrupted later.
11459 void unregister_netdevice_many(struct list_head *head)
11461 unregister_netdevice_many_notify(head, 0, NULL);
11463 EXPORT_SYMBOL(unregister_netdevice_many);
11466 * unregister_netdev - remove device from the kernel
11469 * This function shuts down a device interface and removes it
11470 * from the kernel tables.
11472 * This is just a wrapper for unregister_netdevice that takes
11473 * the rtnl semaphore. In general you want to use this and not
11474 * unregister_netdevice.
11476 void unregister_netdev(struct net_device *dev)
11479 unregister_netdevice(dev);
11482 EXPORT_SYMBOL(unregister_netdev);
11485 * __dev_change_net_namespace - move device to different nethost namespace
11487 * @net: network namespace
11488 * @pat: If not NULL name pattern to try if the current device name
11489 * is already taken in the destination network namespace.
11490 * @new_ifindex: If not zero, specifies device index in the target
11493 * This function shuts down a device interface and moves it
11494 * to a new network namespace. On success 0 is returned, on
11495 * a failure a netagive errno code is returned.
11497 * Callers must hold the rtnl semaphore.
11500 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
11501 const char *pat, int new_ifindex)
11503 struct netdev_name_node *name_node;
11504 struct net *net_old = dev_net(dev);
11505 char new_name[IFNAMSIZ] = {};
11510 /* Don't allow namespace local devices to be moved. */
11512 if (dev->netns_local)
11515 /* Ensure the device has been registered */
11516 if (dev->reg_state != NETREG_REGISTERED)
11519 /* Get out if there is nothing todo */
11521 if (net_eq(net_old, net))
11524 /* Pick the destination device name, and ensure
11525 * we can use it in the destination network namespace.
11528 if (netdev_name_in_use(net, dev->name)) {
11529 /* We get here if we can't use the current device name */
11532 err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST);
11536 /* Check that none of the altnames conflicts. */
11538 netdev_for_each_altname(dev, name_node)
11539 if (netdev_name_in_use(net, name_node->name))
11542 /* Check that new_ifindex isn't used yet. */
11544 err = dev_index_reserve(net, new_ifindex);
11548 /* If there is an ifindex conflict assign a new one */
11549 err = dev_index_reserve(net, dev->ifindex);
11551 err = dev_index_reserve(net, 0);
11558 * And now a mini version of register_netdevice unregister_netdevice.
11561 /* If device is running close it first. */
11564 /* And unlink it from device chain */
11565 unlist_netdevice(dev);
11569 /* Shutdown queueing discipline. */
11572 /* Notify protocols, that we are about to destroy
11573 * this device. They should clean all the things.
11575 * Note that dev->reg_state stays at NETREG_REGISTERED.
11576 * This is wanted because this way 8021q and macvlan know
11577 * the device is just moving and can keep their slaves up.
11579 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11582 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11584 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11588 * Flush the unicast and multicast chains
11593 /* Send a netdev-removed uevent to the old namespace */
11594 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11595 netdev_adjacent_del_links(dev);
11597 /* Move per-net netdevice notifiers that are following the netdevice */
11598 move_netdevice_notifiers_dev_net(dev, net);
11600 /* Actually switch the network namespace */
11601 dev_net_set(dev, net);
11602 dev->ifindex = new_ifindex;
11605 /* Rename the netdev to prepared name */
11606 write_seqlock_bh(&netdev_rename_lock);
11607 strscpy(dev->name, new_name, IFNAMSIZ);
11608 write_sequnlock_bh(&netdev_rename_lock);
11611 /* Fixup kobjects */
11612 dev_set_uevent_suppress(&dev->dev, 1);
11613 err = device_rename(&dev->dev, dev->name);
11614 dev_set_uevent_suppress(&dev->dev, 0);
11617 /* Send a netdev-add uevent to the new namespace */
11618 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11619 netdev_adjacent_add_links(dev);
11621 /* Adapt owner in case owning user namespace of target network
11622 * namespace is different from the original one.
11624 err = netdev_change_owner(dev, net_old, net);
11627 /* Add the device back in the hashes */
11628 list_netdevice(dev);
11630 /* Notify protocols, that a new device appeared. */
11631 call_netdevice_notifiers(NETDEV_REGISTER, dev);
11634 * Prevent userspace races by waiting until the network
11635 * device is fully setup before sending notifications.
11637 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11644 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11646 static int dev_cpu_dead(unsigned int oldcpu)
11648 struct sk_buff **list_skb;
11649 struct sk_buff *skb;
11651 struct softnet_data *sd, *oldsd, *remsd = NULL;
11653 local_irq_disable();
11654 cpu = smp_processor_id();
11655 sd = &per_cpu(softnet_data, cpu);
11656 oldsd = &per_cpu(softnet_data, oldcpu);
11658 /* Find end of our completion_queue. */
11659 list_skb = &sd->completion_queue;
11661 list_skb = &(*list_skb)->next;
11662 /* Append completion queue from offline CPU. */
11663 *list_skb = oldsd->completion_queue;
11664 oldsd->completion_queue = NULL;
11666 /* Append output queue from offline CPU. */
11667 if (oldsd->output_queue) {
11668 *sd->output_queue_tailp = oldsd->output_queue;
11669 sd->output_queue_tailp = oldsd->output_queue_tailp;
11670 oldsd->output_queue = NULL;
11671 oldsd->output_queue_tailp = &oldsd->output_queue;
11673 /* Append NAPI poll list from offline CPU, with one exception :
11674 * process_backlog() must be called by cpu owning percpu backlog.
11675 * We properly handle process_queue & input_pkt_queue later.
11677 while (!list_empty(&oldsd->poll_list)) {
11678 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11679 struct napi_struct,
11682 list_del_init(&napi->poll_list);
11683 if (napi->poll == process_backlog)
11684 napi->state &= NAPIF_STATE_THREADED;
11686 ____napi_schedule(sd, napi);
11689 raise_softirq_irqoff(NET_TX_SOFTIRQ);
11690 local_irq_enable();
11692 if (!use_backlog_threads()) {
11694 remsd = oldsd->rps_ipi_list;
11695 oldsd->rps_ipi_list = NULL;
11697 /* send out pending IPI's on offline CPU */
11698 net_rps_send_ipi(remsd);
11701 /* Process offline CPU's input_pkt_queue */
11702 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11704 rps_input_queue_head_incr(oldsd);
11706 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11708 rps_input_queue_head_incr(oldsd);
11715 * netdev_increment_features - increment feature set by one
11716 * @all: current feature set
11717 * @one: new feature set
11718 * @mask: mask feature set
11720 * Computes a new feature set after adding a device with feature set
11721 * @one to the master device with current feature set @all. Will not
11722 * enable anything that is off in @mask. Returns the new feature set.
11724 netdev_features_t netdev_increment_features(netdev_features_t all,
11725 netdev_features_t one, netdev_features_t mask)
11727 if (mask & NETIF_F_HW_CSUM)
11728 mask |= NETIF_F_CSUM_MASK;
11729 mask |= NETIF_F_VLAN_CHALLENGED;
11731 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11732 all &= one | ~NETIF_F_ALL_FOR_ALL;
11734 /* If one device supports hw checksumming, set for all. */
11735 if (all & NETIF_F_HW_CSUM)
11736 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11740 EXPORT_SYMBOL(netdev_increment_features);
11742 static struct hlist_head * __net_init netdev_create_hash(void)
11745 struct hlist_head *hash;
11747 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11749 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11750 INIT_HLIST_HEAD(&hash[i]);
11755 /* Initialize per network namespace state */
11756 static int __net_init netdev_init(struct net *net)
11758 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11759 8 * sizeof_field(struct napi_struct, gro_bitmask));
11761 INIT_LIST_HEAD(&net->dev_base_head);
11763 net->dev_name_head = netdev_create_hash();
11764 if (net->dev_name_head == NULL)
11767 net->dev_index_head = netdev_create_hash();
11768 if (net->dev_index_head == NULL)
11771 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
11773 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11778 kfree(net->dev_name_head);
11784 * netdev_drivername - network driver for the device
11785 * @dev: network device
11787 * Determine network driver for device.
11789 const char *netdev_drivername(const struct net_device *dev)
11791 const struct device_driver *driver;
11792 const struct device *parent;
11793 const char *empty = "";
11795 parent = dev->dev.parent;
11799 driver = parent->driver;
11800 if (driver && driver->name)
11801 return driver->name;
11805 static void __netdev_printk(const char *level, const struct net_device *dev,
11806 struct va_format *vaf)
11808 if (dev && dev->dev.parent) {
11809 dev_printk_emit(level[1] - '0',
11812 dev_driver_string(dev->dev.parent),
11813 dev_name(dev->dev.parent),
11814 netdev_name(dev), netdev_reg_state(dev),
11817 printk("%s%s%s: %pV",
11818 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11820 printk("%s(NULL net_device): %pV", level, vaf);
11824 void netdev_printk(const char *level, const struct net_device *dev,
11825 const char *format, ...)
11827 struct va_format vaf;
11830 va_start(args, format);
11835 __netdev_printk(level, dev, &vaf);
11839 EXPORT_SYMBOL(netdev_printk);
11841 #define define_netdev_printk_level(func, level) \
11842 void func(const struct net_device *dev, const char *fmt, ...) \
11844 struct va_format vaf; \
11847 va_start(args, fmt); \
11852 __netdev_printk(level, dev, &vaf); \
11856 EXPORT_SYMBOL(func);
11858 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11859 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11860 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11861 define_netdev_printk_level(netdev_err, KERN_ERR);
11862 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11863 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11864 define_netdev_printk_level(netdev_info, KERN_INFO);
11866 static void __net_exit netdev_exit(struct net *net)
11868 kfree(net->dev_name_head);
11869 kfree(net->dev_index_head);
11870 xa_destroy(&net->dev_by_index);
11871 if (net != &init_net)
11872 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11875 static struct pernet_operations __net_initdata netdev_net_ops = {
11876 .init = netdev_init,
11877 .exit = netdev_exit,
11880 static void __net_exit default_device_exit_net(struct net *net)
11882 struct netdev_name_node *name_node, *tmp;
11883 struct net_device *dev, *aux;
11885 * Push all migratable network devices back to the
11886 * initial network namespace
11889 for_each_netdev_safe(net, dev, aux) {
11891 char fb_name[IFNAMSIZ];
11893 /* Ignore unmoveable devices (i.e. loopback) */
11894 if (dev->netns_local)
11897 /* Leave virtual devices for the generic cleanup */
11898 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11901 /* Push remaining network devices to init_net */
11902 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11903 if (netdev_name_in_use(&init_net, fb_name))
11904 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11906 netdev_for_each_altname_safe(dev, name_node, tmp)
11907 if (netdev_name_in_use(&init_net, name_node->name))
11908 __netdev_name_node_alt_destroy(name_node);
11910 err = dev_change_net_namespace(dev, &init_net, fb_name);
11912 pr_emerg("%s: failed to move %s to init_net: %d\n",
11913 __func__, dev->name, err);
11919 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11921 /* At exit all network devices most be removed from a network
11922 * namespace. Do this in the reverse order of registration.
11923 * Do this across as many network namespaces as possible to
11924 * improve batching efficiency.
11926 struct net_device *dev;
11928 LIST_HEAD(dev_kill_list);
11931 list_for_each_entry(net, net_list, exit_list) {
11932 default_device_exit_net(net);
11936 list_for_each_entry(net, net_list, exit_list) {
11937 for_each_netdev_reverse(net, dev) {
11938 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11939 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11941 unregister_netdevice_queue(dev, &dev_kill_list);
11944 unregister_netdevice_many(&dev_kill_list);
11948 static struct pernet_operations __net_initdata default_device_ops = {
11949 .exit_batch = default_device_exit_batch,
11952 static void __init net_dev_struct_check(void)
11954 /* TX read-mostly hotpath */
11955 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast);
11956 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops);
11957 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops);
11958 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx);
11959 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues);
11960 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size);
11961 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size);
11962 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs);
11963 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features);
11964 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc);
11965 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu);
11966 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom);
11967 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq);
11969 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps);
11971 #ifdef CONFIG_NETFILTER_EGRESS
11972 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress);
11974 #ifdef CONFIG_NET_XGRESS
11975 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress);
11977 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160);
11979 /* TXRX read-mostly hotpath */
11980 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats);
11981 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state);
11982 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags);
11983 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len);
11984 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features);
11985 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr);
11986 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46);
11988 /* RX read-mostly hotpath */
11989 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific);
11990 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex);
11991 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues);
11992 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx);
11993 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_flush_timeout);
11994 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, napi_defer_hard_irqs);
11995 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size);
11996 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size);
11997 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler);
11998 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data);
11999 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net);
12000 #ifdef CONFIG_NETPOLL
12001 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo);
12003 #ifdef CONFIG_NET_XGRESS
12004 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress);
12006 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 104);
12010 * Initialize the DEV module. At boot time this walks the device list and
12011 * unhooks any devices that fail to initialise (normally hardware not
12012 * present) and leaves us with a valid list of present and active devices.
12016 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */
12017 #define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE)
12019 static int net_page_pool_create(int cpuid)
12021 #if IS_ENABLED(CONFIG_PAGE_POOL)
12022 struct page_pool_params page_pool_params = {
12023 .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE,
12024 .flags = PP_FLAG_SYSTEM_POOL,
12025 .nid = cpu_to_mem(cpuid),
12027 struct page_pool *pp_ptr;
12029 pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid);
12030 if (IS_ERR(pp_ptr))
12033 per_cpu(system_page_pool, cpuid) = pp_ptr;
12038 static int backlog_napi_should_run(unsigned int cpu)
12040 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12041 struct napi_struct *napi = &sd->backlog;
12043 return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
12046 static void run_backlog_napi(unsigned int cpu)
12048 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12050 napi_threaded_poll_loop(&sd->backlog);
12053 static void backlog_napi_setup(unsigned int cpu)
12055 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12056 struct napi_struct *napi = &sd->backlog;
12058 napi->thread = this_cpu_read(backlog_napi);
12059 set_bit(NAPI_STATE_THREADED, &napi->state);
12062 static struct smp_hotplug_thread backlog_threads = {
12063 .store = &backlog_napi,
12064 .thread_should_run = backlog_napi_should_run,
12065 .thread_fn = run_backlog_napi,
12066 .thread_comm = "backlog_napi/%u",
12067 .setup = backlog_napi_setup,
12071 * This is called single threaded during boot, so no need
12072 * to take the rtnl semaphore.
12074 static int __init net_dev_init(void)
12076 int i, rc = -ENOMEM;
12078 BUG_ON(!dev_boot_phase);
12080 net_dev_struct_check();
12082 if (dev_proc_init())
12085 if (netdev_kobject_init())
12088 for (i = 0; i < PTYPE_HASH_SIZE; i++)
12089 INIT_LIST_HEAD(&ptype_base[i]);
12091 if (register_pernet_subsys(&netdev_net_ops))
12095 * Initialise the packet receive queues.
12098 for_each_possible_cpu(i) {
12099 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
12100 struct softnet_data *sd = &per_cpu(softnet_data, i);
12102 INIT_WORK(flush, flush_backlog);
12104 skb_queue_head_init(&sd->input_pkt_queue);
12105 skb_queue_head_init(&sd->process_queue);
12106 #ifdef CONFIG_XFRM_OFFLOAD
12107 skb_queue_head_init(&sd->xfrm_backlog);
12109 INIT_LIST_HEAD(&sd->poll_list);
12110 sd->output_queue_tailp = &sd->output_queue;
12112 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
12115 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
12116 spin_lock_init(&sd->defer_lock);
12118 init_gro_hash(&sd->backlog);
12119 sd->backlog.poll = process_backlog;
12120 sd->backlog.weight = weight_p;
12121 INIT_LIST_HEAD(&sd->backlog.poll_list);
12123 if (net_page_pool_create(i))
12126 if (use_backlog_threads())
12127 smpboot_register_percpu_thread(&backlog_threads);
12129 dev_boot_phase = 0;
12131 /* The loopback device is special if any other network devices
12132 * is present in a network namespace the loopback device must
12133 * be present. Since we now dynamically allocate and free the
12134 * loopback device ensure this invariant is maintained by
12135 * keeping the loopback device as the first device on the
12136 * list of network devices. Ensuring the loopback devices
12137 * is the first device that appears and the last network device
12140 if (register_pernet_device(&loopback_net_ops))
12143 if (register_pernet_device(&default_device_ops))
12146 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
12147 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
12149 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
12150 NULL, dev_cpu_dead);
12154 /* avoid static key IPIs to isolated CPUs */
12155 if (housekeeping_enabled(HK_TYPE_MISC))
12156 net_enable_timestamp();
12159 for_each_possible_cpu(i) {
12160 struct page_pool *pp_ptr;
12162 pp_ptr = per_cpu(system_page_pool, i);
12166 page_pool_destroy(pp_ptr);
12167 per_cpu(system_page_pool, i) = NULL;
12174 subsys_initcall(net_dev_init);