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>
164 #include "net-sysfs.h"
166 static DEFINE_SPINLOCK(ptype_lock);
167 struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
169 static int netif_rx_internal(struct sk_buff *skb);
170 static int call_netdevice_notifiers_extack(unsigned long val,
171 struct net_device *dev,
172 struct netlink_ext_ack *extack);
174 static DEFINE_MUTEX(ifalias_mutex);
176 /* protects napi_hash addition/deletion and napi_gen_id */
177 static DEFINE_SPINLOCK(napi_hash_lock);
179 static unsigned int napi_gen_id = NR_CPUS;
180 static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
182 static DECLARE_RWSEM(devnet_rename_sem);
184 static inline void dev_base_seq_inc(struct net *net)
186 unsigned int val = net->dev_base_seq + 1;
188 WRITE_ONCE(net->dev_base_seq, val ?: 1);
191 static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
193 unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
195 return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
198 static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
200 return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
203 #ifndef CONFIG_PREEMPT_RT
205 static DEFINE_STATIC_KEY_FALSE(use_backlog_threads_key);
207 static int __init setup_backlog_napi_threads(char *arg)
209 static_branch_enable(&use_backlog_threads_key);
212 early_param("thread_backlog_napi", setup_backlog_napi_threads);
214 static bool use_backlog_threads(void)
216 return static_branch_unlikely(&use_backlog_threads_key);
221 static bool use_backlog_threads(void)
228 static inline void backlog_lock_irq_save(struct softnet_data *sd,
229 unsigned long *flags)
231 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
232 spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
234 local_irq_save(*flags);
237 static inline void backlog_lock_irq_disable(struct softnet_data *sd)
239 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
240 spin_lock_irq(&sd->input_pkt_queue.lock);
245 static inline void backlog_unlock_irq_restore(struct softnet_data *sd,
246 unsigned long *flags)
248 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
249 spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
251 local_irq_restore(*flags);
254 static inline void backlog_unlock_irq_enable(struct softnet_data *sd)
256 if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
257 spin_unlock_irq(&sd->input_pkt_queue.lock);
262 static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
265 struct netdev_name_node *name_node;
267 name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
270 INIT_HLIST_NODE(&name_node->hlist);
271 name_node->dev = dev;
272 name_node->name = name;
276 static struct netdev_name_node *
277 netdev_name_node_head_alloc(struct net_device *dev)
279 struct netdev_name_node *name_node;
281 name_node = netdev_name_node_alloc(dev, dev->name);
284 INIT_LIST_HEAD(&name_node->list);
288 static void netdev_name_node_free(struct netdev_name_node *name_node)
293 static void netdev_name_node_add(struct net *net,
294 struct netdev_name_node *name_node)
296 hlist_add_head_rcu(&name_node->hlist,
297 dev_name_hash(net, name_node->name));
300 static void netdev_name_node_del(struct netdev_name_node *name_node)
302 hlist_del_rcu(&name_node->hlist);
305 static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
308 struct hlist_head *head = dev_name_hash(net, name);
309 struct netdev_name_node *name_node;
311 hlist_for_each_entry(name_node, head, hlist)
312 if (!strcmp(name_node->name, name))
317 static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
320 struct hlist_head *head = dev_name_hash(net, name);
321 struct netdev_name_node *name_node;
323 hlist_for_each_entry_rcu(name_node, head, hlist)
324 if (!strcmp(name_node->name, name))
329 bool netdev_name_in_use(struct net *net, const char *name)
331 return netdev_name_node_lookup(net, name);
333 EXPORT_SYMBOL(netdev_name_in_use);
335 int netdev_name_node_alt_create(struct net_device *dev, const char *name)
337 struct netdev_name_node *name_node;
338 struct net *net = dev_net(dev);
340 name_node = netdev_name_node_lookup(net, name);
343 name_node = netdev_name_node_alloc(dev, name);
346 netdev_name_node_add(net, name_node);
347 /* The node that holds dev->name acts as a head of per-device list. */
348 list_add_tail_rcu(&name_node->list, &dev->name_node->list);
353 static void netdev_name_node_alt_free(struct rcu_head *head)
355 struct netdev_name_node *name_node =
356 container_of(head, struct netdev_name_node, rcu);
358 kfree(name_node->name);
359 netdev_name_node_free(name_node);
362 static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
364 netdev_name_node_del(name_node);
365 list_del(&name_node->list);
366 call_rcu(&name_node->rcu, netdev_name_node_alt_free);
369 int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
371 struct netdev_name_node *name_node;
372 struct net *net = dev_net(dev);
374 name_node = netdev_name_node_lookup(net, name);
377 /* lookup might have found our primary name or a name belonging
380 if (name_node == dev->name_node || name_node->dev != dev)
383 __netdev_name_node_alt_destroy(name_node);
387 static void netdev_name_node_alt_flush(struct net_device *dev)
389 struct netdev_name_node *name_node, *tmp;
391 list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list) {
392 list_del(&name_node->list);
393 netdev_name_node_alt_free(&name_node->rcu);
397 /* Device list insertion */
398 static void list_netdevice(struct net_device *dev)
400 struct netdev_name_node *name_node;
401 struct net *net = dev_net(dev);
405 list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
406 netdev_name_node_add(net, dev->name_node);
407 hlist_add_head_rcu(&dev->index_hlist,
408 dev_index_hash(net, dev->ifindex));
410 netdev_for_each_altname(dev, name_node)
411 netdev_name_node_add(net, name_node);
413 /* We reserved the ifindex, this can't fail */
414 WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL));
416 dev_base_seq_inc(net);
419 /* Device list removal
420 * caller must respect a RCU grace period before freeing/reusing dev
422 static void unlist_netdevice(struct net_device *dev)
424 struct netdev_name_node *name_node;
425 struct net *net = dev_net(dev);
429 xa_erase(&net->dev_by_index, dev->ifindex);
431 netdev_for_each_altname(dev, name_node)
432 netdev_name_node_del(name_node);
434 /* Unlink dev from the device chain */
435 list_del_rcu(&dev->dev_list);
436 netdev_name_node_del(dev->name_node);
437 hlist_del_rcu(&dev->index_hlist);
439 dev_base_seq_inc(dev_net(dev));
446 static RAW_NOTIFIER_HEAD(netdev_chain);
449 * Device drivers call our routines to queue packets here. We empty the
450 * queue in the local softnet handler.
453 DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data) = {
454 .process_queue_bh_lock = INIT_LOCAL_LOCK(process_queue_bh_lock),
456 EXPORT_PER_CPU_SYMBOL(softnet_data);
458 /* Page_pool has a lockless array/stack to alloc/recycle pages.
459 * PP consumers must pay attention to run APIs in the appropriate context
460 * (e.g. NAPI context).
462 static DEFINE_PER_CPU(struct page_pool *, system_page_pool);
464 #ifdef CONFIG_LOCKDEP
466 * register_netdevice() inits txq->_xmit_lock and sets lockdep class
467 * according to dev->type
469 static const unsigned short netdev_lock_type[] = {
470 ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
471 ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
472 ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
473 ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
474 ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
475 ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
476 ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
477 ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
478 ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
479 ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
480 ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
481 ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
482 ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
483 ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
484 ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
486 static const char *const netdev_lock_name[] = {
487 "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
488 "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
489 "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
490 "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
491 "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
492 "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
493 "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
494 "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
495 "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
496 "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
497 "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
498 "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
499 "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
500 "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
501 "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
503 static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
504 static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
506 static inline unsigned short netdev_lock_pos(unsigned short dev_type)
510 for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
511 if (netdev_lock_type[i] == dev_type)
513 /* the last key is used by default */
514 return ARRAY_SIZE(netdev_lock_type) - 1;
517 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
518 unsigned short dev_type)
522 i = netdev_lock_pos(dev_type);
523 lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
524 netdev_lock_name[i]);
527 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
531 i = netdev_lock_pos(dev->type);
532 lockdep_set_class_and_name(&dev->addr_list_lock,
533 &netdev_addr_lock_key[i],
534 netdev_lock_name[i]);
537 static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
538 unsigned short dev_type)
542 static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
547 /*******************************************************************************
549 * Protocol management and registration routines
551 *******************************************************************************/
555 * Add a protocol ID to the list. Now that the input handler is
556 * smarter we can dispense with all the messy stuff that used to be
559 * BEWARE!!! Protocol handlers, mangling input packets,
560 * MUST BE last in hash buckets and checking protocol handlers
561 * MUST start from promiscuous ptype_all chain in net_bh.
562 * It is true now, do not change it.
563 * Explanation follows: if protocol handler, mangling packet, will
564 * be the first on list, it is not able to sense, that packet
565 * is cloned and should be copied-on-write, so that it will
566 * change it and subsequent readers will get broken packet.
570 static inline struct list_head *ptype_head(const struct packet_type *pt)
572 if (pt->type == htons(ETH_P_ALL))
573 return pt->dev ? &pt->dev->ptype_all : &net_hotdata.ptype_all;
575 return pt->dev ? &pt->dev->ptype_specific :
576 &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
580 * dev_add_pack - add packet handler
581 * @pt: packet type declaration
583 * Add a protocol handler to the networking stack. The passed &packet_type
584 * is linked into kernel lists and may not be freed until it has been
585 * removed from the kernel lists.
587 * This call does not sleep therefore it can not
588 * guarantee all CPU's that are in middle of receiving packets
589 * will see the new packet type (until the next received packet).
592 void dev_add_pack(struct packet_type *pt)
594 struct list_head *head = ptype_head(pt);
596 spin_lock(&ptype_lock);
597 list_add_rcu(&pt->list, head);
598 spin_unlock(&ptype_lock);
600 EXPORT_SYMBOL(dev_add_pack);
603 * __dev_remove_pack - remove packet handler
604 * @pt: packet type declaration
606 * Remove a protocol handler that was previously added to the kernel
607 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
608 * from the kernel lists and can be freed or reused once this function
611 * The packet type might still be in use by receivers
612 * and must not be freed until after all the CPU's have gone
613 * through a quiescent state.
615 void __dev_remove_pack(struct packet_type *pt)
617 struct list_head *head = ptype_head(pt);
618 struct packet_type *pt1;
620 spin_lock(&ptype_lock);
622 list_for_each_entry(pt1, head, list) {
624 list_del_rcu(&pt->list);
629 pr_warn("dev_remove_pack: %p not found\n", pt);
631 spin_unlock(&ptype_lock);
633 EXPORT_SYMBOL(__dev_remove_pack);
636 * dev_remove_pack - remove packet handler
637 * @pt: packet type declaration
639 * Remove a protocol handler that was previously added to the kernel
640 * protocol handlers by dev_add_pack(). The passed &packet_type is removed
641 * from the kernel lists and can be freed or reused once this function
644 * This call sleeps to guarantee that no CPU is looking at the packet
647 void dev_remove_pack(struct packet_type *pt)
649 __dev_remove_pack(pt);
653 EXPORT_SYMBOL(dev_remove_pack);
656 /*******************************************************************************
658 * Device Interface Subroutines
660 *******************************************************************************/
663 * dev_get_iflink - get 'iflink' value of a interface
664 * @dev: targeted interface
666 * Indicates the ifindex the interface is linked to.
667 * Physical interfaces have the same 'ifindex' and 'iflink' values.
670 int dev_get_iflink(const struct net_device *dev)
672 if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
673 return dev->netdev_ops->ndo_get_iflink(dev);
675 return READ_ONCE(dev->ifindex);
677 EXPORT_SYMBOL(dev_get_iflink);
680 * dev_fill_metadata_dst - Retrieve tunnel egress information.
681 * @dev: targeted interface
684 * For better visibility of tunnel traffic OVS needs to retrieve
685 * egress tunnel information for a packet. Following API allows
686 * user to get this info.
688 int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
690 struct ip_tunnel_info *info;
692 if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
695 info = skb_tunnel_info_unclone(skb);
698 if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
701 return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
703 EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
705 static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
707 int k = stack->num_paths++;
709 if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
712 return &stack->path[k];
715 int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
716 struct net_device_path_stack *stack)
718 const struct net_device *last_dev;
719 struct net_device_path_ctx ctx = {
722 struct net_device_path *path;
725 memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
726 stack->num_paths = 0;
727 while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
729 path = dev_fwd_path(stack);
733 memset(path, 0, sizeof(struct net_device_path));
734 ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
738 if (WARN_ON_ONCE(last_dev == ctx.dev))
745 path = dev_fwd_path(stack);
748 path->type = DEV_PATH_ETHERNET;
753 EXPORT_SYMBOL_GPL(dev_fill_forward_path);
756 * __dev_get_by_name - find a device by its name
757 * @net: the applicable net namespace
758 * @name: name to find
760 * Find an interface by name. Must be called under RTNL semaphore.
761 * If the name is found a pointer to the device is returned.
762 * If the name is not found then %NULL is returned. The
763 * reference counters are not incremented so the caller must be
764 * careful with locks.
767 struct net_device *__dev_get_by_name(struct net *net, const char *name)
769 struct netdev_name_node *node_name;
771 node_name = netdev_name_node_lookup(net, name);
772 return node_name ? node_name->dev : NULL;
774 EXPORT_SYMBOL(__dev_get_by_name);
777 * dev_get_by_name_rcu - find a device by its name
778 * @net: the applicable net namespace
779 * @name: name to find
781 * Find an interface by name.
782 * If the name is found a pointer to the device is returned.
783 * If the name is not found then %NULL is returned.
784 * The reference counters are not incremented so the caller must be
785 * careful with locks. The caller must hold RCU lock.
788 struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
790 struct netdev_name_node *node_name;
792 node_name = netdev_name_node_lookup_rcu(net, name);
793 return node_name ? node_name->dev : NULL;
795 EXPORT_SYMBOL(dev_get_by_name_rcu);
797 /* Deprecated for new users, call netdev_get_by_name() instead */
798 struct net_device *dev_get_by_name(struct net *net, const char *name)
800 struct net_device *dev;
803 dev = dev_get_by_name_rcu(net, name);
808 EXPORT_SYMBOL(dev_get_by_name);
811 * netdev_get_by_name() - find a device by its name
812 * @net: the applicable net namespace
813 * @name: name to find
814 * @tracker: tracking object for the acquired reference
815 * @gfp: allocation flags for the tracker
817 * Find an interface by name. This can be called from any
818 * context and does its own locking. The returned handle has
819 * the usage count incremented and the caller must use netdev_put() to
820 * release it when it is no longer needed. %NULL is returned if no
821 * matching device is found.
823 struct net_device *netdev_get_by_name(struct net *net, const char *name,
824 netdevice_tracker *tracker, gfp_t gfp)
826 struct net_device *dev;
828 dev = dev_get_by_name(net, name);
830 netdev_tracker_alloc(dev, tracker, gfp);
833 EXPORT_SYMBOL(netdev_get_by_name);
836 * __dev_get_by_index - find a device by its ifindex
837 * @net: the applicable net namespace
838 * @ifindex: index of device
840 * Search for an interface by index. Returns %NULL if the device
841 * is not found or a pointer to the device. The device has not
842 * had its reference counter increased so the caller must be careful
843 * about locking. The caller must hold the RTNL semaphore.
846 struct net_device *__dev_get_by_index(struct net *net, int ifindex)
848 struct net_device *dev;
849 struct hlist_head *head = dev_index_hash(net, ifindex);
851 hlist_for_each_entry(dev, head, index_hlist)
852 if (dev->ifindex == ifindex)
857 EXPORT_SYMBOL(__dev_get_by_index);
860 * dev_get_by_index_rcu - find a device by its ifindex
861 * @net: the applicable net namespace
862 * @ifindex: index of device
864 * Search for an interface by index. Returns %NULL if the device
865 * is not found or a pointer to the device. The device has not
866 * had its reference counter increased so the caller must be careful
867 * about locking. The caller must hold RCU lock.
870 struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
872 struct net_device *dev;
873 struct hlist_head *head = dev_index_hash(net, ifindex);
875 hlist_for_each_entry_rcu(dev, head, index_hlist)
876 if (dev->ifindex == ifindex)
881 EXPORT_SYMBOL(dev_get_by_index_rcu);
883 /* Deprecated for new users, call netdev_get_by_index() instead */
884 struct net_device *dev_get_by_index(struct net *net, int ifindex)
886 struct net_device *dev;
889 dev = dev_get_by_index_rcu(net, ifindex);
894 EXPORT_SYMBOL(dev_get_by_index);
897 * netdev_get_by_index() - find a device by its ifindex
898 * @net: the applicable net namespace
899 * @ifindex: index of device
900 * @tracker: tracking object for the acquired reference
901 * @gfp: allocation flags for the tracker
903 * Search for an interface by index. Returns NULL if the device
904 * is not found or a pointer to the device. The device returned has
905 * had a reference added and the pointer is safe until the user calls
906 * netdev_put() to indicate they have finished with it.
908 struct net_device *netdev_get_by_index(struct net *net, int ifindex,
909 netdevice_tracker *tracker, gfp_t gfp)
911 struct net_device *dev;
913 dev = dev_get_by_index(net, ifindex);
915 netdev_tracker_alloc(dev, tracker, gfp);
918 EXPORT_SYMBOL(netdev_get_by_index);
921 * dev_get_by_napi_id - find a device by napi_id
922 * @napi_id: ID of the NAPI struct
924 * Search for an interface by NAPI ID. Returns %NULL if the device
925 * is not found or a pointer to the device. The device has not had
926 * its reference counter increased so the caller must be careful
927 * about locking. The caller must hold RCU lock.
930 struct net_device *dev_get_by_napi_id(unsigned int napi_id)
932 struct napi_struct *napi;
934 WARN_ON_ONCE(!rcu_read_lock_held());
936 if (napi_id < MIN_NAPI_ID)
939 napi = napi_by_id(napi_id);
941 return napi ? napi->dev : NULL;
943 EXPORT_SYMBOL(dev_get_by_napi_id);
945 static DEFINE_SEQLOCK(netdev_rename_lock);
947 void netdev_copy_name(struct net_device *dev, char *name)
952 seq = read_seqbegin(&netdev_rename_lock);
953 strscpy(name, dev->name, IFNAMSIZ);
954 } while (read_seqretry(&netdev_rename_lock, seq));
958 * netdev_get_name - get a netdevice name, knowing its ifindex.
959 * @net: network namespace
960 * @name: a pointer to the buffer where the name will be stored.
961 * @ifindex: the ifindex of the interface to get the name from.
963 int netdev_get_name(struct net *net, char *name, int ifindex)
965 struct net_device *dev;
970 dev = dev_get_by_index_rcu(net, ifindex);
976 netdev_copy_name(dev, name);
985 * dev_getbyhwaddr_rcu - find a device by its hardware address
986 * @net: the applicable net namespace
987 * @type: media type of device
988 * @ha: hardware address
990 * Search for an interface by MAC address. Returns NULL if the device
991 * is not found or a pointer to the device.
992 * The caller must hold RCU or RTNL.
993 * The returned device has not had its ref count increased
994 * and the caller must therefore be careful about locking
998 struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
1001 struct net_device *dev;
1003 for_each_netdev_rcu(net, dev)
1004 if (dev->type == type &&
1005 !memcmp(dev->dev_addr, ha, dev->addr_len))
1010 EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
1012 struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
1014 struct net_device *dev, *ret = NULL;
1017 for_each_netdev_rcu(net, dev)
1018 if (dev->type == type) {
1026 EXPORT_SYMBOL(dev_getfirstbyhwtype);
1029 * __dev_get_by_flags - find any device with given flags
1030 * @net: the applicable net namespace
1031 * @if_flags: IFF_* values
1032 * @mask: bitmask of bits in if_flags to check
1034 * Search for any interface with the given flags. Returns NULL if a device
1035 * is not found or a pointer to the device. Must be called inside
1036 * rtnl_lock(), and result refcount is unchanged.
1039 struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
1040 unsigned short mask)
1042 struct net_device *dev, *ret;
1047 for_each_netdev(net, dev) {
1048 if (((dev->flags ^ if_flags) & mask) == 0) {
1055 EXPORT_SYMBOL(__dev_get_by_flags);
1058 * dev_valid_name - check if name is okay for network device
1059 * @name: name string
1061 * Network device names need to be valid file names to
1062 * allow sysfs to work. We also disallow any kind of
1065 bool dev_valid_name(const char *name)
1069 if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
1071 if (!strcmp(name, ".") || !strcmp(name, ".."))
1075 if (*name == '/' || *name == ':' || isspace(*name))
1081 EXPORT_SYMBOL(dev_valid_name);
1084 * __dev_alloc_name - allocate a name for a device
1085 * @net: network namespace to allocate the device name in
1086 * @name: name format string
1087 * @res: result name string
1089 * Passed a format string - eg "lt%d" it will try and find a suitable
1090 * id. It scans list of devices to build up a free map, then chooses
1091 * the first empty slot. The caller must hold the dev_base or rtnl lock
1092 * while allocating the name and adding the device in order to avoid
1094 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1095 * Returns the number of the unit assigned or a negative errno code.
1098 static int __dev_alloc_name(struct net *net, const char *name, char *res)
1102 const int max_netdevices = 8*PAGE_SIZE;
1103 unsigned long *inuse;
1104 struct net_device *d;
1107 /* Verify the string as this thing may have come from the user.
1108 * There must be one "%d" and no other "%" characters.
1110 p = strchr(name, '%');
1111 if (!p || p[1] != 'd' || strchr(p + 2, '%'))
1114 /* Use one page as a bit array of possible slots */
1115 inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
1119 for_each_netdev(net, d) {
1120 struct netdev_name_node *name_node;
1122 netdev_for_each_altname(d, name_node) {
1123 if (!sscanf(name_node->name, name, &i))
1125 if (i < 0 || i >= max_netdevices)
1128 /* avoid cases where sscanf is not exact inverse of printf */
1129 snprintf(buf, IFNAMSIZ, name, i);
1130 if (!strncmp(buf, name_node->name, IFNAMSIZ))
1131 __set_bit(i, inuse);
1133 if (!sscanf(d->name, name, &i))
1135 if (i < 0 || i >= max_netdevices)
1138 /* avoid cases where sscanf is not exact inverse of printf */
1139 snprintf(buf, IFNAMSIZ, name, i);
1140 if (!strncmp(buf, d->name, IFNAMSIZ))
1141 __set_bit(i, inuse);
1144 i = find_first_zero_bit(inuse, max_netdevices);
1146 if (i == max_netdevices)
1149 /* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */
1150 strscpy(buf, name, IFNAMSIZ);
1151 snprintf(res, IFNAMSIZ, buf, i);
1155 /* Returns negative errno or allocated unit id (see __dev_alloc_name()) */
1156 static int dev_prep_valid_name(struct net *net, struct net_device *dev,
1157 const char *want_name, char *out_name,
1160 if (!dev_valid_name(want_name))
1163 if (strchr(want_name, '%'))
1164 return __dev_alloc_name(net, want_name, out_name);
1166 if (netdev_name_in_use(net, want_name))
1168 if (out_name != want_name)
1169 strscpy(out_name, want_name, IFNAMSIZ);
1174 * dev_alloc_name - allocate a name for a device
1176 * @name: name format string
1178 * Passed a format string - eg "lt%d" it will try and find a suitable
1179 * id. It scans list of devices to build up a free map, then chooses
1180 * the first empty slot. The caller must hold the dev_base or rtnl lock
1181 * while allocating the name and adding the device in order to avoid
1183 * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
1184 * Returns the number of the unit assigned or a negative errno code.
1187 int dev_alloc_name(struct net_device *dev, const char *name)
1189 return dev_prep_valid_name(dev_net(dev), dev, name, dev->name, ENFILE);
1191 EXPORT_SYMBOL(dev_alloc_name);
1193 static int dev_get_valid_name(struct net *net, struct net_device *dev,
1198 ret = dev_prep_valid_name(net, dev, name, dev->name, EEXIST);
1199 return ret < 0 ? ret : 0;
1203 * dev_change_name - change name of a device
1205 * @newname: name (or format string) must be at least IFNAMSIZ
1207 * Change name of a device, can pass format strings "eth%d".
1210 int dev_change_name(struct net_device *dev, const char *newname)
1212 unsigned char old_assign_type;
1213 char oldname[IFNAMSIZ];
1219 BUG_ON(!dev_net(dev));
1223 down_write(&devnet_rename_sem);
1225 if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
1226 up_write(&devnet_rename_sem);
1230 memcpy(oldname, dev->name, IFNAMSIZ);
1232 write_seqlock_bh(&netdev_rename_lock);
1233 err = dev_get_valid_name(net, dev, newname);
1234 write_sequnlock_bh(&netdev_rename_lock);
1237 up_write(&devnet_rename_sem);
1241 if (oldname[0] && !strchr(oldname, '%'))
1242 netdev_info(dev, "renamed from %s%s\n", oldname,
1243 dev->flags & IFF_UP ? " (while UP)" : "");
1245 old_assign_type = dev->name_assign_type;
1246 WRITE_ONCE(dev->name_assign_type, NET_NAME_RENAMED);
1249 ret = device_rename(&dev->dev, dev->name);
1251 memcpy(dev->name, oldname, IFNAMSIZ);
1252 WRITE_ONCE(dev->name_assign_type, old_assign_type);
1253 up_write(&devnet_rename_sem);
1257 up_write(&devnet_rename_sem);
1259 netdev_adjacent_rename_links(dev, oldname);
1261 netdev_name_node_del(dev->name_node);
1265 netdev_name_node_add(net, dev->name_node);
1267 ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
1268 ret = notifier_to_errno(ret);
1271 /* err >= 0 after dev_alloc_name() or stores the first errno */
1274 down_write(&devnet_rename_sem);
1275 write_seqlock_bh(&netdev_rename_lock);
1276 memcpy(dev->name, oldname, IFNAMSIZ);
1277 write_sequnlock_bh(&netdev_rename_lock);
1278 memcpy(oldname, newname, IFNAMSIZ);
1279 WRITE_ONCE(dev->name_assign_type, old_assign_type);
1280 old_assign_type = NET_NAME_RENAMED;
1283 netdev_err(dev, "name change rollback failed: %d\n",
1292 * dev_set_alias - change ifalias of a device
1294 * @alias: name up to IFALIASZ
1295 * @len: limit of bytes to copy from info
1297 * Set ifalias for a device,
1299 int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
1301 struct dev_ifalias *new_alias = NULL;
1303 if (len >= IFALIASZ)
1307 new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
1311 memcpy(new_alias->ifalias, alias, len);
1312 new_alias->ifalias[len] = 0;
1315 mutex_lock(&ifalias_mutex);
1316 new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
1317 mutex_is_locked(&ifalias_mutex));
1318 mutex_unlock(&ifalias_mutex);
1321 kfree_rcu(new_alias, rcuhead);
1325 EXPORT_SYMBOL(dev_set_alias);
1328 * dev_get_alias - get ifalias of a device
1330 * @name: buffer to store name of ifalias
1331 * @len: size of buffer
1333 * get ifalias for a device. Caller must make sure dev cannot go
1334 * away, e.g. rcu read lock or own a reference count to device.
1336 int dev_get_alias(const struct net_device *dev, char *name, size_t len)
1338 const struct dev_ifalias *alias;
1342 alias = rcu_dereference(dev->ifalias);
1344 ret = snprintf(name, len, "%s", alias->ifalias);
1351 * netdev_features_change - device changes features
1352 * @dev: device to cause notification
1354 * Called to indicate a device has changed features.
1356 void netdev_features_change(struct net_device *dev)
1358 call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
1360 EXPORT_SYMBOL(netdev_features_change);
1363 * netdev_state_change - device changes state
1364 * @dev: device to cause notification
1366 * Called to indicate a device has changed state. This function calls
1367 * the notifier chains for netdev_chain and sends a NEWLINK message
1368 * to the routing socket.
1370 void netdev_state_change(struct net_device *dev)
1372 if (dev->flags & IFF_UP) {
1373 struct netdev_notifier_change_info change_info = {
1377 call_netdevice_notifiers_info(NETDEV_CHANGE,
1379 rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
1382 EXPORT_SYMBOL(netdev_state_change);
1385 * __netdev_notify_peers - notify network peers about existence of @dev,
1386 * to be called when rtnl lock is already held.
1387 * @dev: network device
1389 * Generate traffic such that interested network peers are aware of
1390 * @dev, such as by generating a gratuitous ARP. This may be used when
1391 * a device wants to inform the rest of the network about some sort of
1392 * reconfiguration such as a failover event or virtual machine
1395 void __netdev_notify_peers(struct net_device *dev)
1398 call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
1399 call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
1401 EXPORT_SYMBOL(__netdev_notify_peers);
1404 * netdev_notify_peers - notify network peers about existence of @dev
1405 * @dev: network device
1407 * Generate traffic such that interested network peers are aware of
1408 * @dev, such as by generating a gratuitous ARP. This may be used when
1409 * a device wants to inform the rest of the network about some sort of
1410 * reconfiguration such as a failover event or virtual machine
1413 void netdev_notify_peers(struct net_device *dev)
1416 __netdev_notify_peers(dev);
1419 EXPORT_SYMBOL(netdev_notify_peers);
1421 static int napi_threaded_poll(void *data);
1423 static int napi_kthread_create(struct napi_struct *n)
1427 /* Create and wake up the kthread once to put it in
1428 * TASK_INTERRUPTIBLE mode to avoid the blocked task
1429 * warning and work with loadavg.
1431 n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
1432 n->dev->name, n->napi_id);
1433 if (IS_ERR(n->thread)) {
1434 err = PTR_ERR(n->thread);
1435 pr_err("kthread_run failed with err %d\n", err);
1442 static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1444 const struct net_device_ops *ops = dev->netdev_ops;
1448 dev_addr_check(dev);
1450 if (!netif_device_present(dev)) {
1451 /* may be detached because parent is runtime-suspended */
1452 if (dev->dev.parent)
1453 pm_runtime_resume(dev->dev.parent);
1454 if (!netif_device_present(dev))
1458 /* Block netpoll from trying to do any rx path servicing.
1459 * If we don't do this there is a chance ndo_poll_controller
1460 * or ndo_poll may be running while we open the device
1462 netpoll_poll_disable(dev);
1464 ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
1465 ret = notifier_to_errno(ret);
1469 set_bit(__LINK_STATE_START, &dev->state);
1471 if (ops->ndo_validate_addr)
1472 ret = ops->ndo_validate_addr(dev);
1474 if (!ret && ops->ndo_open)
1475 ret = ops->ndo_open(dev);
1477 netpoll_poll_enable(dev);
1480 clear_bit(__LINK_STATE_START, &dev->state);
1482 dev->flags |= IFF_UP;
1483 dev_set_rx_mode(dev);
1485 add_device_randomness(dev->dev_addr, dev->addr_len);
1492 * dev_open - prepare an interface for use.
1493 * @dev: device to open
1494 * @extack: netlink extended ack
1496 * Takes a device from down to up state. The device's private open
1497 * function is invoked and then the multicast lists are loaded. Finally
1498 * the device is moved into the up state and a %NETDEV_UP message is
1499 * sent to the netdev notifier chain.
1501 * Calling this function on an active interface is a nop. On a failure
1502 * a negative errno code is returned.
1504 int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
1508 if (dev->flags & IFF_UP)
1511 ret = __dev_open(dev, extack);
1515 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1516 call_netdevice_notifiers(NETDEV_UP, dev);
1520 EXPORT_SYMBOL(dev_open);
1522 static void __dev_close_many(struct list_head *head)
1524 struct net_device *dev;
1529 list_for_each_entry(dev, head, close_list) {
1530 /* Temporarily disable netpoll until the interface is down */
1531 netpoll_poll_disable(dev);
1533 call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
1535 clear_bit(__LINK_STATE_START, &dev->state);
1537 /* Synchronize to scheduled poll. We cannot touch poll list, it
1538 * can be even on different cpu. So just clear netif_running().
1540 * dev->stop() will invoke napi_disable() on all of it's
1541 * napi_struct instances on this device.
1543 smp_mb__after_atomic(); /* Commit netif_running(). */
1546 dev_deactivate_many(head);
1548 list_for_each_entry(dev, head, close_list) {
1549 const struct net_device_ops *ops = dev->netdev_ops;
1552 * Call the device specific close. This cannot fail.
1553 * Only if device is UP
1555 * We allow it to be called even after a DETACH hot-plug
1561 dev->flags &= ~IFF_UP;
1562 netpoll_poll_enable(dev);
1566 static void __dev_close(struct net_device *dev)
1570 list_add(&dev->close_list, &single);
1571 __dev_close_many(&single);
1575 void dev_close_many(struct list_head *head, bool unlink)
1577 struct net_device *dev, *tmp;
1579 /* Remove the devices that don't need to be closed */
1580 list_for_each_entry_safe(dev, tmp, head, close_list)
1581 if (!(dev->flags & IFF_UP))
1582 list_del_init(&dev->close_list);
1584 __dev_close_many(head);
1586 list_for_each_entry_safe(dev, tmp, head, close_list) {
1587 rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
1588 call_netdevice_notifiers(NETDEV_DOWN, dev);
1590 list_del_init(&dev->close_list);
1593 EXPORT_SYMBOL(dev_close_many);
1596 * dev_close - shutdown an interface.
1597 * @dev: device to shutdown
1599 * This function moves an active device into down state. A
1600 * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
1601 * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
1604 void dev_close(struct net_device *dev)
1606 if (dev->flags & IFF_UP) {
1609 list_add(&dev->close_list, &single);
1610 dev_close_many(&single, true);
1614 EXPORT_SYMBOL(dev_close);
1618 * dev_disable_lro - disable Large Receive Offload on a device
1621 * Disable Large Receive Offload (LRO) on a net device. Must be
1622 * called under RTNL. This is needed if received packets may be
1623 * forwarded to another interface.
1625 void dev_disable_lro(struct net_device *dev)
1627 struct net_device *lower_dev;
1628 struct list_head *iter;
1630 dev->wanted_features &= ~NETIF_F_LRO;
1631 netdev_update_features(dev);
1633 if (unlikely(dev->features & NETIF_F_LRO))
1634 netdev_WARN(dev, "failed to disable LRO!\n");
1636 netdev_for_each_lower_dev(dev, lower_dev, iter)
1637 dev_disable_lro(lower_dev);
1639 EXPORT_SYMBOL(dev_disable_lro);
1642 * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
1645 * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
1646 * called under RTNL. This is needed if Generic XDP is installed on
1649 static void dev_disable_gro_hw(struct net_device *dev)
1651 dev->wanted_features &= ~NETIF_F_GRO_HW;
1652 netdev_update_features(dev);
1654 if (unlikely(dev->features & NETIF_F_GRO_HW))
1655 netdev_WARN(dev, "failed to disable GRO_HW!\n");
1658 const char *netdev_cmd_to_name(enum netdev_cmd cmd)
1661 case NETDEV_##val: \
1662 return "NETDEV_" __stringify(val);
1664 N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
1665 N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
1666 N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
1667 N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
1668 N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
1669 N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
1670 N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
1671 N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
1672 N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
1673 N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
1674 N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
1678 return "UNKNOWN_NETDEV_EVENT";
1680 EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
1682 static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
1683 struct net_device *dev)
1685 struct netdev_notifier_info info = {
1689 return nb->notifier_call(nb, val, &info);
1692 static int call_netdevice_register_notifiers(struct notifier_block *nb,
1693 struct net_device *dev)
1697 err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
1698 err = notifier_to_errno(err);
1702 if (!(dev->flags & IFF_UP))
1705 call_netdevice_notifier(nb, NETDEV_UP, dev);
1709 static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
1710 struct net_device *dev)
1712 if (dev->flags & IFF_UP) {
1713 call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
1715 call_netdevice_notifier(nb, NETDEV_DOWN, dev);
1717 call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
1720 static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
1723 struct net_device *dev;
1726 for_each_netdev(net, dev) {
1727 err = call_netdevice_register_notifiers(nb, dev);
1734 for_each_netdev_continue_reverse(net, dev)
1735 call_netdevice_unregister_notifiers(nb, dev);
1739 static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
1742 struct net_device *dev;
1744 for_each_netdev(net, dev)
1745 call_netdevice_unregister_notifiers(nb, dev);
1748 static int dev_boot_phase = 1;
1751 * register_netdevice_notifier - register a network notifier block
1754 * Register a notifier to be called when network device events occur.
1755 * The notifier passed is linked into the kernel structures and must
1756 * not be reused until it has been unregistered. A negative errno code
1757 * is returned on a failure.
1759 * When registered all registration and up events are replayed
1760 * to the new notifier to allow device to have a race free
1761 * view of the network device list.
1764 int register_netdevice_notifier(struct notifier_block *nb)
1769 /* Close race with setup_net() and cleanup_net() */
1770 down_write(&pernet_ops_rwsem);
1772 err = raw_notifier_chain_register(&netdev_chain, nb);
1778 err = call_netdevice_register_net_notifiers(nb, net);
1785 up_write(&pernet_ops_rwsem);
1789 for_each_net_continue_reverse(net)
1790 call_netdevice_unregister_net_notifiers(nb, net);
1792 raw_notifier_chain_unregister(&netdev_chain, nb);
1795 EXPORT_SYMBOL(register_netdevice_notifier);
1798 * unregister_netdevice_notifier - unregister a network notifier block
1801 * Unregister a notifier previously registered by
1802 * register_netdevice_notifier(). The notifier is unlinked into the
1803 * kernel structures and may then be reused. A negative errno code
1804 * is returned on a failure.
1806 * After unregistering unregister and down device events are synthesized
1807 * for all devices on the device list to the removed notifier to remove
1808 * the need for special case cleanup code.
1811 int unregister_netdevice_notifier(struct notifier_block *nb)
1816 /* Close race with setup_net() and cleanup_net() */
1817 down_write(&pernet_ops_rwsem);
1819 err = raw_notifier_chain_unregister(&netdev_chain, nb);
1824 call_netdevice_unregister_net_notifiers(nb, net);
1828 up_write(&pernet_ops_rwsem);
1831 EXPORT_SYMBOL(unregister_netdevice_notifier);
1833 static int __register_netdevice_notifier_net(struct net *net,
1834 struct notifier_block *nb,
1835 bool ignore_call_fail)
1839 err = raw_notifier_chain_register(&net->netdev_chain, nb);
1845 err = call_netdevice_register_net_notifiers(nb, net);
1846 if (err && !ignore_call_fail)
1847 goto chain_unregister;
1852 raw_notifier_chain_unregister(&net->netdev_chain, nb);
1856 static int __unregister_netdevice_notifier_net(struct net *net,
1857 struct notifier_block *nb)
1861 err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
1865 call_netdevice_unregister_net_notifiers(nb, net);
1870 * register_netdevice_notifier_net - register a per-netns network notifier block
1871 * @net: network namespace
1874 * Register a notifier to be called when network device events occur.
1875 * The notifier passed is linked into the kernel structures and must
1876 * not be reused until it has been unregistered. A negative errno code
1877 * is returned on a failure.
1879 * When registered all registration and up events are replayed
1880 * to the new notifier to allow device to have a race free
1881 * view of the network device list.
1884 int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
1889 err = __register_netdevice_notifier_net(net, nb, false);
1893 EXPORT_SYMBOL(register_netdevice_notifier_net);
1896 * unregister_netdevice_notifier_net - unregister a per-netns
1897 * network notifier block
1898 * @net: network namespace
1901 * Unregister a notifier previously registered by
1902 * register_netdevice_notifier_net(). The notifier is unlinked from the
1903 * kernel structures and may then be reused. A negative errno code
1904 * is returned on a failure.
1906 * After unregistering unregister and down device events are synthesized
1907 * for all devices on the device list to the removed notifier to remove
1908 * the need for special case cleanup code.
1911 int unregister_netdevice_notifier_net(struct net *net,
1912 struct notifier_block *nb)
1917 err = __unregister_netdevice_notifier_net(net, nb);
1921 EXPORT_SYMBOL(unregister_netdevice_notifier_net);
1923 static void __move_netdevice_notifier_net(struct net *src_net,
1924 struct net *dst_net,
1925 struct notifier_block *nb)
1927 __unregister_netdevice_notifier_net(src_net, nb);
1928 __register_netdevice_notifier_net(dst_net, nb, true);
1931 int register_netdevice_notifier_dev_net(struct net_device *dev,
1932 struct notifier_block *nb,
1933 struct netdev_net_notifier *nn)
1938 err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
1941 list_add(&nn->list, &dev->net_notifier_list);
1946 EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
1948 int unregister_netdevice_notifier_dev_net(struct net_device *dev,
1949 struct notifier_block *nb,
1950 struct netdev_net_notifier *nn)
1955 list_del(&nn->list);
1956 err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
1960 EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
1962 static void move_netdevice_notifiers_dev_net(struct net_device *dev,
1965 struct netdev_net_notifier *nn;
1967 list_for_each_entry(nn, &dev->net_notifier_list, list)
1968 __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
1972 * call_netdevice_notifiers_info - call all network notifier blocks
1973 * @val: value passed unmodified to notifier function
1974 * @info: notifier information data
1976 * Call all network notifier blocks. Parameters and return value
1977 * are as for raw_notifier_call_chain().
1980 int call_netdevice_notifiers_info(unsigned long val,
1981 struct netdev_notifier_info *info)
1983 struct net *net = dev_net(info->dev);
1988 /* Run per-netns notifier block chain first, then run the global one.
1989 * Hopefully, one day, the global one is going to be removed after
1990 * all notifier block registrators get converted to be per-netns.
1992 ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
1993 if (ret & NOTIFY_STOP_MASK)
1995 return raw_notifier_call_chain(&netdev_chain, val, info);
1999 * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
2000 * for and rollback on error
2001 * @val_up: value passed unmodified to notifier function
2002 * @val_down: value passed unmodified to the notifier function when
2003 * recovering from an error on @val_up
2004 * @info: notifier information data
2006 * Call all per-netns network notifier blocks, but not notifier blocks on
2007 * the global notifier chain. Parameters and return value are as for
2008 * raw_notifier_call_chain_robust().
2012 call_netdevice_notifiers_info_robust(unsigned long val_up,
2013 unsigned long val_down,
2014 struct netdev_notifier_info *info)
2016 struct net *net = dev_net(info->dev);
2020 return raw_notifier_call_chain_robust(&net->netdev_chain,
2021 val_up, val_down, info);
2024 static int call_netdevice_notifiers_extack(unsigned long val,
2025 struct net_device *dev,
2026 struct netlink_ext_ack *extack)
2028 struct netdev_notifier_info info = {
2033 return call_netdevice_notifiers_info(val, &info);
2037 * call_netdevice_notifiers - call all network notifier blocks
2038 * @val: value passed unmodified to notifier function
2039 * @dev: net_device pointer passed unmodified to notifier function
2041 * Call all network notifier blocks. Parameters and return value
2042 * are as for raw_notifier_call_chain().
2045 int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
2047 return call_netdevice_notifiers_extack(val, dev, NULL);
2049 EXPORT_SYMBOL(call_netdevice_notifiers);
2052 * call_netdevice_notifiers_mtu - call all network notifier blocks
2053 * @val: value passed unmodified to notifier function
2054 * @dev: net_device pointer passed unmodified to notifier function
2055 * @arg: additional u32 argument passed to the notifier function
2057 * Call all network notifier blocks. Parameters and return value
2058 * are as for raw_notifier_call_chain().
2060 static int call_netdevice_notifiers_mtu(unsigned long val,
2061 struct net_device *dev, u32 arg)
2063 struct netdev_notifier_info_ext info = {
2068 BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
2070 return call_netdevice_notifiers_info(val, &info.info);
2073 #ifdef CONFIG_NET_INGRESS
2074 static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
2076 void net_inc_ingress_queue(void)
2078 static_branch_inc(&ingress_needed_key);
2080 EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
2082 void net_dec_ingress_queue(void)
2084 static_branch_dec(&ingress_needed_key);
2086 EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
2089 #ifdef CONFIG_NET_EGRESS
2090 static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
2092 void net_inc_egress_queue(void)
2094 static_branch_inc(&egress_needed_key);
2096 EXPORT_SYMBOL_GPL(net_inc_egress_queue);
2098 void net_dec_egress_queue(void)
2100 static_branch_dec(&egress_needed_key);
2102 EXPORT_SYMBOL_GPL(net_dec_egress_queue);
2105 #ifdef CONFIG_NET_CLS_ACT
2106 DEFINE_STATIC_KEY_FALSE(tcf_bypass_check_needed_key);
2107 EXPORT_SYMBOL(tcf_bypass_check_needed_key);
2110 DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
2111 EXPORT_SYMBOL(netstamp_needed_key);
2112 #ifdef CONFIG_JUMP_LABEL
2113 static atomic_t netstamp_needed_deferred;
2114 static atomic_t netstamp_wanted;
2115 static void netstamp_clear(struct work_struct *work)
2117 int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
2120 wanted = atomic_add_return(deferred, &netstamp_wanted);
2122 static_branch_enable(&netstamp_needed_key);
2124 static_branch_disable(&netstamp_needed_key);
2126 static DECLARE_WORK(netstamp_work, netstamp_clear);
2129 void net_enable_timestamp(void)
2131 #ifdef CONFIG_JUMP_LABEL
2132 int wanted = atomic_read(&netstamp_wanted);
2134 while (wanted > 0) {
2135 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
2138 atomic_inc(&netstamp_needed_deferred);
2139 schedule_work(&netstamp_work);
2141 static_branch_inc(&netstamp_needed_key);
2144 EXPORT_SYMBOL(net_enable_timestamp);
2146 void net_disable_timestamp(void)
2148 #ifdef CONFIG_JUMP_LABEL
2149 int wanted = atomic_read(&netstamp_wanted);
2151 while (wanted > 1) {
2152 if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
2155 atomic_dec(&netstamp_needed_deferred);
2156 schedule_work(&netstamp_work);
2158 static_branch_dec(&netstamp_needed_key);
2161 EXPORT_SYMBOL(net_disable_timestamp);
2163 static inline void net_timestamp_set(struct sk_buff *skb)
2166 skb->tstamp_type = SKB_CLOCK_REALTIME;
2167 if (static_branch_unlikely(&netstamp_needed_key))
2168 skb->tstamp = ktime_get_real();
2171 #define net_timestamp_check(COND, SKB) \
2172 if (static_branch_unlikely(&netstamp_needed_key)) { \
2173 if ((COND) && !(SKB)->tstamp) \
2174 (SKB)->tstamp = ktime_get_real(); \
2177 bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
2179 return __is_skb_forwardable(dev, skb, true);
2181 EXPORT_SYMBOL_GPL(is_skb_forwardable);
2183 static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
2186 int ret = ____dev_forward_skb(dev, skb, check_mtu);
2189 skb->protocol = eth_type_trans(skb, dev);
2190 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
2196 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2198 return __dev_forward_skb2(dev, skb, true);
2200 EXPORT_SYMBOL_GPL(__dev_forward_skb);
2203 * dev_forward_skb - loopback an skb to another netif
2205 * @dev: destination network device
2206 * @skb: buffer to forward
2209 * NET_RX_SUCCESS (no congestion)
2210 * NET_RX_DROP (packet was dropped, but freed)
2212 * dev_forward_skb can be used for injecting an skb from the
2213 * start_xmit function of one device into the receive queue
2214 * of another device.
2216 * The receiving device may be in another namespace, so
2217 * we have to clear all information in the skb that could
2218 * impact namespace isolation.
2220 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
2222 return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
2224 EXPORT_SYMBOL_GPL(dev_forward_skb);
2226 int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
2228 return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
2231 static inline int deliver_skb(struct sk_buff *skb,
2232 struct packet_type *pt_prev,
2233 struct net_device *orig_dev)
2235 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
2237 refcount_inc(&skb->users);
2238 return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
2241 static inline void deliver_ptype_list_skb(struct sk_buff *skb,
2242 struct packet_type **pt,
2243 struct net_device *orig_dev,
2245 struct list_head *ptype_list)
2247 struct packet_type *ptype, *pt_prev = *pt;
2249 list_for_each_entry_rcu(ptype, ptype_list, list) {
2250 if (ptype->type != type)
2253 deliver_skb(skb, pt_prev, orig_dev);
2259 static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
2261 if (!ptype->af_packet_priv || !skb->sk)
2264 if (ptype->id_match)
2265 return ptype->id_match(ptype, skb->sk);
2266 else if ((struct sock *)ptype->af_packet_priv == skb->sk)
2273 * dev_nit_active - return true if any network interface taps are in use
2275 * @dev: network device to check for the presence of taps
2277 bool dev_nit_active(struct net_device *dev)
2279 return !list_empty(&net_hotdata.ptype_all) ||
2280 !list_empty(&dev->ptype_all);
2282 EXPORT_SYMBOL_GPL(dev_nit_active);
2285 * Support routine. Sends outgoing frames to any network
2286 * taps currently in use.
2289 void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
2291 struct list_head *ptype_list = &net_hotdata.ptype_all;
2292 struct packet_type *ptype, *pt_prev = NULL;
2293 struct sk_buff *skb2 = NULL;
2297 list_for_each_entry_rcu(ptype, ptype_list, list) {
2298 if (READ_ONCE(ptype->ignore_outgoing))
2301 /* Never send packets back to the socket
2304 if (skb_loop_sk(ptype, skb))
2308 deliver_skb(skb2, pt_prev, skb->dev);
2313 /* need to clone skb, done only once */
2314 skb2 = skb_clone(skb, GFP_ATOMIC);
2318 net_timestamp_set(skb2);
2320 /* skb->nh should be correctly
2321 * set by sender, so that the second statement is
2322 * just protection against buggy protocols.
2324 skb_reset_mac_header(skb2);
2326 if (skb_network_header(skb2) < skb2->data ||
2327 skb_network_header(skb2) > skb_tail_pointer(skb2)) {
2328 net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
2329 ntohs(skb2->protocol),
2331 skb_reset_network_header(skb2);
2334 skb2->transport_header = skb2->network_header;
2335 skb2->pkt_type = PACKET_OUTGOING;
2339 if (ptype_list == &net_hotdata.ptype_all) {
2340 ptype_list = &dev->ptype_all;
2345 if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
2346 pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
2352 EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
2355 * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
2356 * @dev: Network device
2357 * @txq: number of queues available
2359 * If real_num_tx_queues is changed the tc mappings may no longer be
2360 * valid. To resolve this verify the tc mapping remains valid and if
2361 * not NULL the mapping. With no priorities mapping to this
2362 * offset/count pair it will no longer be used. In the worst case TC0
2363 * is invalid nothing can be done so disable priority mappings. If is
2364 * expected that drivers will fix this mapping if they can before
2365 * calling netif_set_real_num_tx_queues.
2367 static void netif_setup_tc(struct net_device *dev, unsigned int txq)
2370 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2372 /* If TC0 is invalidated disable TC mapping */
2373 if (tc->offset + tc->count > txq) {
2374 netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
2379 /* Invalidated prio to tc mappings set to TC0 */
2380 for (i = 1; i < TC_BITMASK + 1; i++) {
2381 int q = netdev_get_prio_tc_map(dev, i);
2383 tc = &dev->tc_to_txq[q];
2384 if (tc->offset + tc->count > txq) {
2385 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",
2387 netdev_set_prio_tc_map(dev, i, 0);
2392 int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
2395 struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
2398 /* walk through the TCs and see if it falls into any of them */
2399 for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
2400 if ((txq - tc->offset) < tc->count)
2404 /* didn't find it, just return -1 to indicate no match */
2410 EXPORT_SYMBOL(netdev_txq_to_tc);
2413 static struct static_key xps_needed __read_mostly;
2414 static struct static_key xps_rxqs_needed __read_mostly;
2415 static DEFINE_MUTEX(xps_map_mutex);
2416 #define xmap_dereference(P) \
2417 rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
2419 static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
2420 struct xps_dev_maps *old_maps, int tci, u16 index)
2422 struct xps_map *map = NULL;
2425 map = xmap_dereference(dev_maps->attr_map[tci]);
2429 for (pos = map->len; pos--;) {
2430 if (map->queues[pos] != index)
2434 map->queues[pos] = map->queues[--map->len];
2439 RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
2440 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2441 kfree_rcu(map, rcu);
2448 static bool remove_xps_queue_cpu(struct net_device *dev,
2449 struct xps_dev_maps *dev_maps,
2450 int cpu, u16 offset, u16 count)
2452 int num_tc = dev_maps->num_tc;
2453 bool active = false;
2456 for (tci = cpu * num_tc; num_tc--; tci++) {
2459 for (i = count, j = offset; i--; j++) {
2460 if (!remove_xps_queue(dev_maps, NULL, tci, j))
2470 static void reset_xps_maps(struct net_device *dev,
2471 struct xps_dev_maps *dev_maps,
2472 enum xps_map_type type)
2474 static_key_slow_dec_cpuslocked(&xps_needed);
2475 if (type == XPS_RXQS)
2476 static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
2478 RCU_INIT_POINTER(dev->xps_maps[type], NULL);
2480 kfree_rcu(dev_maps, rcu);
2483 static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
2484 u16 offset, u16 count)
2486 struct xps_dev_maps *dev_maps;
2487 bool active = false;
2490 dev_maps = xmap_dereference(dev->xps_maps[type]);
2494 for (j = 0; j < dev_maps->nr_ids; j++)
2495 active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
2497 reset_xps_maps(dev, dev_maps, type);
2499 if (type == XPS_CPUS) {
2500 for (i = offset + (count - 1); count--; i--)
2501 netdev_queue_numa_node_write(
2502 netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
2506 static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
2509 if (!static_key_false(&xps_needed))
2513 mutex_lock(&xps_map_mutex);
2515 if (static_key_false(&xps_rxqs_needed))
2516 clean_xps_maps(dev, XPS_RXQS, offset, count);
2518 clean_xps_maps(dev, XPS_CPUS, offset, count);
2520 mutex_unlock(&xps_map_mutex);
2524 static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
2526 netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
2529 static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
2530 u16 index, bool is_rxqs_map)
2532 struct xps_map *new_map;
2533 int alloc_len = XPS_MIN_MAP_ALLOC;
2536 for (pos = 0; map && pos < map->len; pos++) {
2537 if (map->queues[pos] != index)
2542 /* Need to add tx-queue to this CPU's/rx-queue's existing map */
2544 if (pos < map->alloc_len)
2547 alloc_len = map->alloc_len * 2;
2550 /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
2554 new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
2556 new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
2557 cpu_to_node(attr_index));
2561 for (i = 0; i < pos; i++)
2562 new_map->queues[i] = map->queues[i];
2563 new_map->alloc_len = alloc_len;
2569 /* Copy xps maps at a given index */
2570 static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
2571 struct xps_dev_maps *new_dev_maps, int index,
2572 int tc, bool skip_tc)
2574 int i, tci = index * dev_maps->num_tc;
2575 struct xps_map *map;
2577 /* copy maps belonging to foreign traffic classes */
2578 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2579 if (i == tc && skip_tc)
2582 /* fill in the new device map from the old device map */
2583 map = xmap_dereference(dev_maps->attr_map[tci]);
2584 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2588 /* Must be called under cpus_read_lock */
2589 int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
2590 u16 index, enum xps_map_type type)
2592 struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
2593 const unsigned long *online_mask = NULL;
2594 bool active = false, copy = false;
2595 int i, j, tci, numa_node_id = -2;
2596 int maps_sz, num_tc = 1, tc = 0;
2597 struct xps_map *map, *new_map;
2598 unsigned int nr_ids;
2600 WARN_ON_ONCE(index >= dev->num_tx_queues);
2603 /* Do not allow XPS on subordinate device directly */
2604 num_tc = dev->num_tc;
2608 /* If queue belongs to subordinate dev use its map */
2609 dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
2611 tc = netdev_txq_to_tc(dev, index);
2616 mutex_lock(&xps_map_mutex);
2618 dev_maps = xmap_dereference(dev->xps_maps[type]);
2619 if (type == XPS_RXQS) {
2620 maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
2621 nr_ids = dev->num_rx_queues;
2623 maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
2624 if (num_possible_cpus() > 1)
2625 online_mask = cpumask_bits(cpu_online_mask);
2626 nr_ids = nr_cpu_ids;
2629 if (maps_sz < L1_CACHE_BYTES)
2630 maps_sz = L1_CACHE_BYTES;
2632 /* The old dev_maps could be larger or smaller than the one we're
2633 * setting up now, as dev->num_tc or nr_ids could have been updated in
2634 * between. We could try to be smart, but let's be safe instead and only
2635 * copy foreign traffic classes if the two map sizes match.
2638 dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
2641 /* allocate memory for queue storage */
2642 for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
2644 if (!new_dev_maps) {
2645 new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
2646 if (!new_dev_maps) {
2647 mutex_unlock(&xps_map_mutex);
2651 new_dev_maps->nr_ids = nr_ids;
2652 new_dev_maps->num_tc = num_tc;
2655 tci = j * num_tc + tc;
2656 map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
2658 map = expand_xps_map(map, j, index, type == XPS_RXQS);
2662 RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
2666 goto out_no_new_maps;
2669 /* Increment static keys at most once per type */
2670 static_key_slow_inc_cpuslocked(&xps_needed);
2671 if (type == XPS_RXQS)
2672 static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
2675 for (j = 0; j < nr_ids; j++) {
2676 bool skip_tc = false;
2678 tci = j * num_tc + tc;
2679 if (netif_attr_test_mask(j, mask, nr_ids) &&
2680 netif_attr_test_online(j, online_mask, nr_ids)) {
2681 /* add tx-queue to CPU/rx-queue maps */
2686 map = xmap_dereference(new_dev_maps->attr_map[tci]);
2687 while ((pos < map->len) && (map->queues[pos] != index))
2690 if (pos == map->len)
2691 map->queues[map->len++] = index;
2693 if (type == XPS_CPUS) {
2694 if (numa_node_id == -2)
2695 numa_node_id = cpu_to_node(j);
2696 else if (numa_node_id != cpu_to_node(j))
2703 xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
2707 rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
2709 /* Cleanup old maps */
2711 goto out_no_old_maps;
2713 for (j = 0; j < dev_maps->nr_ids; j++) {
2714 for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
2715 map = xmap_dereference(dev_maps->attr_map[tci]);
2720 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2725 RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
2726 kfree_rcu(map, rcu);
2730 old_dev_maps = dev_maps;
2733 dev_maps = new_dev_maps;
2737 if (type == XPS_CPUS)
2738 /* update Tx queue numa node */
2739 netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
2740 (numa_node_id >= 0) ?
2741 numa_node_id : NUMA_NO_NODE);
2746 /* removes tx-queue from unused CPUs/rx-queues */
2747 for (j = 0; j < dev_maps->nr_ids; j++) {
2748 tci = j * dev_maps->num_tc;
2750 for (i = 0; i < dev_maps->num_tc; i++, tci++) {
2752 netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
2753 netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
2756 active |= remove_xps_queue(dev_maps,
2757 copy ? old_dev_maps : NULL,
2763 kfree_rcu(old_dev_maps, rcu);
2765 /* free map if not active */
2767 reset_xps_maps(dev, dev_maps, type);
2770 mutex_unlock(&xps_map_mutex);
2774 /* remove any maps that we added */
2775 for (j = 0; j < nr_ids; j++) {
2776 for (i = num_tc, tci = j * num_tc; i--; tci++) {
2777 new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
2779 xmap_dereference(dev_maps->attr_map[tci]) :
2781 if (new_map && new_map != map)
2786 mutex_unlock(&xps_map_mutex);
2788 kfree(new_dev_maps);
2791 EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
2793 int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
2799 ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
2804 EXPORT_SYMBOL(netif_set_xps_queue);
2807 static void netdev_unbind_all_sb_channels(struct net_device *dev)
2809 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2811 /* Unbind any subordinate channels */
2812 while (txq-- != &dev->_tx[0]) {
2814 netdev_unbind_sb_channel(dev, txq->sb_dev);
2818 void netdev_reset_tc(struct net_device *dev)
2821 netif_reset_xps_queues_gt(dev, 0);
2823 netdev_unbind_all_sb_channels(dev);
2825 /* Reset TC configuration of device */
2827 memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
2828 memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
2830 EXPORT_SYMBOL(netdev_reset_tc);
2832 int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
2834 if (tc >= dev->num_tc)
2838 netif_reset_xps_queues(dev, offset, count);
2840 dev->tc_to_txq[tc].count = count;
2841 dev->tc_to_txq[tc].offset = offset;
2844 EXPORT_SYMBOL(netdev_set_tc_queue);
2846 int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
2848 if (num_tc > TC_MAX_QUEUE)
2852 netif_reset_xps_queues_gt(dev, 0);
2854 netdev_unbind_all_sb_channels(dev);
2856 dev->num_tc = num_tc;
2859 EXPORT_SYMBOL(netdev_set_num_tc);
2861 void netdev_unbind_sb_channel(struct net_device *dev,
2862 struct net_device *sb_dev)
2864 struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
2867 netif_reset_xps_queues_gt(sb_dev, 0);
2869 memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
2870 memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
2872 while (txq-- != &dev->_tx[0]) {
2873 if (txq->sb_dev == sb_dev)
2877 EXPORT_SYMBOL(netdev_unbind_sb_channel);
2879 int netdev_bind_sb_channel_queue(struct net_device *dev,
2880 struct net_device *sb_dev,
2881 u8 tc, u16 count, u16 offset)
2883 /* Make certain the sb_dev and dev are already configured */
2884 if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
2887 /* We cannot hand out queues we don't have */
2888 if ((offset + count) > dev->real_num_tx_queues)
2891 /* Record the mapping */
2892 sb_dev->tc_to_txq[tc].count = count;
2893 sb_dev->tc_to_txq[tc].offset = offset;
2895 /* Provide a way for Tx queue to find the tc_to_txq map or
2896 * XPS map for itself.
2899 netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
2903 EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
2905 int netdev_set_sb_channel(struct net_device *dev, u16 channel)
2907 /* Do not use a multiqueue device to represent a subordinate channel */
2908 if (netif_is_multiqueue(dev))
2911 /* We allow channels 1 - 32767 to be used for subordinate channels.
2912 * Channel 0 is meant to be "native" mode and used only to represent
2913 * the main root device. We allow writing 0 to reset the device back
2914 * to normal mode after being used as a subordinate channel.
2916 if (channel > S16_MAX)
2919 dev->num_tc = -channel;
2923 EXPORT_SYMBOL(netdev_set_sb_channel);
2926 * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
2927 * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
2929 int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
2934 disabling = txq < dev->real_num_tx_queues;
2936 if (txq < 1 || txq > dev->num_tx_queues)
2939 if (dev->reg_state == NETREG_REGISTERED ||
2940 dev->reg_state == NETREG_UNREGISTERING) {
2943 rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
2949 netif_setup_tc(dev, txq);
2951 dev_qdisc_change_real_num_tx(dev, txq);
2953 dev->real_num_tx_queues = txq;
2957 qdisc_reset_all_tx_gt(dev, txq);
2959 netif_reset_xps_queues_gt(dev, txq);
2963 dev->real_num_tx_queues = txq;
2968 EXPORT_SYMBOL(netif_set_real_num_tx_queues);
2972 * netif_set_real_num_rx_queues - set actual number of RX queues used
2973 * @dev: Network device
2974 * @rxq: Actual number of RX queues
2976 * This must be called either with the rtnl_lock held or before
2977 * registration of the net device. Returns 0 on success, or a
2978 * negative error code. If called before registration, it always
2981 int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
2985 if (rxq < 1 || rxq > dev->num_rx_queues)
2988 if (dev->reg_state == NETREG_REGISTERED) {
2991 rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
2997 dev->real_num_rx_queues = rxq;
3000 EXPORT_SYMBOL(netif_set_real_num_rx_queues);
3004 * netif_set_real_num_queues - set actual number of RX and TX queues used
3005 * @dev: Network device
3006 * @txq: Actual number of TX queues
3007 * @rxq: Actual number of RX queues
3009 * Set the real number of both TX and RX queues.
3010 * Does nothing if the number of queues is already correct.
3012 int netif_set_real_num_queues(struct net_device *dev,
3013 unsigned int txq, unsigned int rxq)
3015 unsigned int old_rxq = dev->real_num_rx_queues;
3018 if (txq < 1 || txq > dev->num_tx_queues ||
3019 rxq < 1 || rxq > dev->num_rx_queues)
3022 /* Start from increases, so the error path only does decreases -
3023 * decreases can't fail.
3025 if (rxq > dev->real_num_rx_queues) {
3026 err = netif_set_real_num_rx_queues(dev, rxq);
3030 if (txq > dev->real_num_tx_queues) {
3031 err = netif_set_real_num_tx_queues(dev, txq);
3035 if (rxq < dev->real_num_rx_queues)
3036 WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
3037 if (txq < dev->real_num_tx_queues)
3038 WARN_ON(netif_set_real_num_tx_queues(dev, txq));
3042 WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
3045 EXPORT_SYMBOL(netif_set_real_num_queues);
3048 * netif_set_tso_max_size() - set the max size of TSO frames supported
3049 * @dev: netdev to update
3050 * @size: max skb->len of a TSO frame
3052 * Set the limit on the size of TSO super-frames the device can handle.
3053 * Unless explicitly set the stack will assume the value of
3054 * %GSO_LEGACY_MAX_SIZE.
3056 void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
3058 dev->tso_max_size = min(GSO_MAX_SIZE, size);
3059 if (size < READ_ONCE(dev->gso_max_size))
3060 netif_set_gso_max_size(dev, size);
3061 if (size < READ_ONCE(dev->gso_ipv4_max_size))
3062 netif_set_gso_ipv4_max_size(dev, size);
3064 EXPORT_SYMBOL(netif_set_tso_max_size);
3067 * netif_set_tso_max_segs() - set the max number of segs supported for TSO
3068 * @dev: netdev to update
3069 * @segs: max number of TCP segments
3071 * Set the limit on the number of TCP segments the device can generate from
3072 * a single TSO super-frame.
3073 * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
3075 void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
3077 dev->tso_max_segs = segs;
3078 if (segs < READ_ONCE(dev->gso_max_segs))
3079 netif_set_gso_max_segs(dev, segs);
3081 EXPORT_SYMBOL(netif_set_tso_max_segs);
3084 * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
3085 * @to: netdev to update
3086 * @from: netdev from which to copy the limits
3088 void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
3090 netif_set_tso_max_size(to, from->tso_max_size);
3091 netif_set_tso_max_segs(to, from->tso_max_segs);
3093 EXPORT_SYMBOL(netif_inherit_tso_max);
3096 * netif_get_num_default_rss_queues - default number of RSS queues
3098 * Default value is the number of physical cores if there are only 1 or 2, or
3099 * divided by 2 if there are more.
3101 int netif_get_num_default_rss_queues(void)
3106 if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
3109 cpumask_copy(cpus, cpu_online_mask);
3110 for_each_cpu(cpu, cpus) {
3112 cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
3114 free_cpumask_var(cpus);
3116 return count > 2 ? DIV_ROUND_UP(count, 2) : count;
3118 EXPORT_SYMBOL(netif_get_num_default_rss_queues);
3120 static void __netif_reschedule(struct Qdisc *q)
3122 struct softnet_data *sd;
3123 unsigned long flags;
3125 local_irq_save(flags);
3126 sd = this_cpu_ptr(&softnet_data);
3127 q->next_sched = NULL;
3128 *sd->output_queue_tailp = q;
3129 sd->output_queue_tailp = &q->next_sched;
3130 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3131 local_irq_restore(flags);
3134 void __netif_schedule(struct Qdisc *q)
3136 if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
3137 __netif_reschedule(q);
3139 EXPORT_SYMBOL(__netif_schedule);
3141 struct dev_kfree_skb_cb {
3142 enum skb_drop_reason reason;
3145 static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
3147 return (struct dev_kfree_skb_cb *)skb->cb;
3150 void netif_schedule_queue(struct netdev_queue *txq)
3153 if (!netif_xmit_stopped(txq)) {
3154 struct Qdisc *q = rcu_dereference(txq->qdisc);
3156 __netif_schedule(q);
3160 EXPORT_SYMBOL(netif_schedule_queue);
3162 void netif_tx_wake_queue(struct netdev_queue *dev_queue)
3164 if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
3168 q = rcu_dereference(dev_queue->qdisc);
3169 __netif_schedule(q);
3173 EXPORT_SYMBOL(netif_tx_wake_queue);
3175 void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3177 unsigned long flags;
3182 if (likely(refcount_read(&skb->users) == 1)) {
3184 refcount_set(&skb->users, 0);
3185 } else if (likely(!refcount_dec_and_test(&skb->users))) {
3188 get_kfree_skb_cb(skb)->reason = reason;
3189 local_irq_save(flags);
3190 skb->next = __this_cpu_read(softnet_data.completion_queue);
3191 __this_cpu_write(softnet_data.completion_queue, skb);
3192 raise_softirq_irqoff(NET_TX_SOFTIRQ);
3193 local_irq_restore(flags);
3195 EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
3197 void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
3199 if (in_hardirq() || irqs_disabled())
3200 dev_kfree_skb_irq_reason(skb, reason);
3202 kfree_skb_reason(skb, reason);
3204 EXPORT_SYMBOL(dev_kfree_skb_any_reason);
3208 * netif_device_detach - mark device as removed
3209 * @dev: network device
3211 * Mark device as removed from system and therefore no longer available.
3213 void netif_device_detach(struct net_device *dev)
3215 if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
3216 netif_running(dev)) {
3217 netif_tx_stop_all_queues(dev);
3220 EXPORT_SYMBOL(netif_device_detach);
3223 * netif_device_attach - mark device as attached
3224 * @dev: network device
3226 * Mark device as attached from system and restart if needed.
3228 void netif_device_attach(struct net_device *dev)
3230 if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
3231 netif_running(dev)) {
3232 netif_tx_wake_all_queues(dev);
3233 __netdev_watchdog_up(dev);
3236 EXPORT_SYMBOL(netif_device_attach);
3239 * Returns a Tx hash based on the given packet descriptor a Tx queues' number
3240 * to be used as a distribution range.
3242 static u16 skb_tx_hash(const struct net_device *dev,
3243 const struct net_device *sb_dev,
3244 struct sk_buff *skb)
3248 u16 qcount = dev->real_num_tx_queues;
3251 u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
3253 qoffset = sb_dev->tc_to_txq[tc].offset;
3254 qcount = sb_dev->tc_to_txq[tc].count;
3255 if (unlikely(!qcount)) {
3256 net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
3257 sb_dev->name, qoffset, tc);
3259 qcount = dev->real_num_tx_queues;
3263 if (skb_rx_queue_recorded(skb)) {
3264 DEBUG_NET_WARN_ON_ONCE(qcount == 0);
3265 hash = skb_get_rx_queue(skb);
3266 if (hash >= qoffset)
3268 while (unlikely(hash >= qcount))
3270 return hash + qoffset;
3273 return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
3276 void skb_warn_bad_offload(const struct sk_buff *skb)
3278 static const netdev_features_t null_features;
3279 struct net_device *dev = skb->dev;
3280 const char *name = "";
3282 if (!net_ratelimit())
3286 if (dev->dev.parent)
3287 name = dev_driver_string(dev->dev.parent);
3289 name = netdev_name(dev);
3291 skb_dump(KERN_WARNING, skb, false);
3292 WARN(1, "%s: caps=(%pNF, %pNF)\n",
3293 name, dev ? &dev->features : &null_features,
3294 skb->sk ? &skb->sk->sk_route_caps : &null_features);
3298 * Invalidate hardware checksum when packet is to be mangled, and
3299 * complete checksum manually on outgoing path.
3301 int skb_checksum_help(struct sk_buff *skb)
3304 int ret = 0, offset;
3306 if (skb->ip_summed == CHECKSUM_COMPLETE)
3307 goto out_set_summed;
3309 if (unlikely(skb_is_gso(skb))) {
3310 skb_warn_bad_offload(skb);
3314 /* Before computing a checksum, we should make sure no frag could
3315 * be modified by an external entity : checksum could be wrong.
3317 if (skb_has_shared_frag(skb)) {
3318 ret = __skb_linearize(skb);
3323 offset = skb_checksum_start_offset(skb);
3325 if (unlikely(offset >= skb_headlen(skb))) {
3326 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3327 WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
3328 offset, skb_headlen(skb));
3331 csum = skb_checksum(skb, offset, skb->len - offset, 0);
3333 offset += skb->csum_offset;
3334 if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
3335 DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
3336 WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
3337 offset + sizeof(__sum16), skb_headlen(skb));
3340 ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
3344 *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
3346 skb->ip_summed = CHECKSUM_NONE;
3350 EXPORT_SYMBOL(skb_checksum_help);
3352 int skb_crc32c_csum_help(struct sk_buff *skb)
3355 int ret = 0, offset, start;
3357 if (skb->ip_summed != CHECKSUM_PARTIAL)
3360 if (unlikely(skb_is_gso(skb)))
3363 /* Before computing a checksum, we should make sure no frag could
3364 * be modified by an external entity : checksum could be wrong.
3366 if (unlikely(skb_has_shared_frag(skb))) {
3367 ret = __skb_linearize(skb);
3371 start = skb_checksum_start_offset(skb);
3372 offset = start + offsetof(struct sctphdr, checksum);
3373 if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
3378 ret = skb_ensure_writable(skb, offset + sizeof(__le32));
3382 crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
3383 skb->len - start, ~(__u32)0,
3385 *(__le32 *)(skb->data + offset) = crc32c_csum;
3386 skb_reset_csum_not_inet(skb);
3390 EXPORT_SYMBOL(skb_crc32c_csum_help);
3392 __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
3394 __be16 type = skb->protocol;
3396 /* Tunnel gso handlers can set protocol to ethernet. */
3397 if (type == htons(ETH_P_TEB)) {
3400 if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
3403 eth = (struct ethhdr *)skb->data;
3404 type = eth->h_proto;
3407 return vlan_get_protocol_and_depth(skb, type, depth);
3411 /* Take action when hardware reception checksum errors are detected. */
3413 static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3415 netdev_err(dev, "hw csum failure\n");
3416 skb_dump(KERN_ERR, skb, true);
3420 void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
3422 DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
3424 EXPORT_SYMBOL(netdev_rx_csum_fault);
3427 /* XXX: check that highmem exists at all on the given machine. */
3428 static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
3430 #ifdef CONFIG_HIGHMEM
3433 if (!(dev->features & NETIF_F_HIGHDMA)) {
3434 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3435 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3437 if (PageHighMem(skb_frag_page(frag)))
3445 /* If MPLS offload request, verify we are testing hardware MPLS features
3446 * instead of standard features for the netdev.
3448 #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
3449 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3450 netdev_features_t features,
3453 if (eth_p_mpls(type))
3454 features &= skb->dev->mpls_features;
3459 static netdev_features_t net_mpls_features(struct sk_buff *skb,
3460 netdev_features_t features,
3467 static netdev_features_t harmonize_features(struct sk_buff *skb,
3468 netdev_features_t features)
3472 type = skb_network_protocol(skb, NULL);
3473 features = net_mpls_features(skb, features, type);
3475 if (skb->ip_summed != CHECKSUM_NONE &&
3476 !can_checksum_protocol(features, type)) {
3477 features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
3479 if (illegal_highdma(skb->dev, skb))
3480 features &= ~NETIF_F_SG;
3485 netdev_features_t passthru_features_check(struct sk_buff *skb,
3486 struct net_device *dev,
3487 netdev_features_t features)
3491 EXPORT_SYMBOL(passthru_features_check);
3493 static netdev_features_t dflt_features_check(struct sk_buff *skb,
3494 struct net_device *dev,
3495 netdev_features_t features)
3497 return vlan_features_check(skb, features);
3500 static netdev_features_t gso_features_check(const struct sk_buff *skb,
3501 struct net_device *dev,
3502 netdev_features_t features)
3504 u16 gso_segs = skb_shinfo(skb)->gso_segs;
3506 if (gso_segs > READ_ONCE(dev->gso_max_segs))
3507 return features & ~NETIF_F_GSO_MASK;
3509 if (unlikely(skb->len >= READ_ONCE(dev->gso_max_size)))
3510 return features & ~NETIF_F_GSO_MASK;
3512 if (!skb_shinfo(skb)->gso_type) {
3513 skb_warn_bad_offload(skb);
3514 return features & ~NETIF_F_GSO_MASK;
3517 /* Support for GSO partial features requires software
3518 * intervention before we can actually process the packets
3519 * so we need to strip support for any partial features now
3520 * and we can pull them back in after we have partially
3521 * segmented the frame.
3523 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
3524 features &= ~dev->gso_partial_features;
3526 /* Make sure to clear the IPv4 ID mangling feature if the
3527 * IPv4 header has the potential to be fragmented.
3529 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
3530 struct iphdr *iph = skb->encapsulation ?
3531 inner_ip_hdr(skb) : ip_hdr(skb);
3533 if (!(iph->frag_off & htons(IP_DF)))
3534 features &= ~NETIF_F_TSO_MANGLEID;
3540 netdev_features_t netif_skb_features(struct sk_buff *skb)
3542 struct net_device *dev = skb->dev;
3543 netdev_features_t features = dev->features;
3545 if (skb_is_gso(skb))
3546 features = gso_features_check(skb, dev, features);
3548 /* If encapsulation offload request, verify we are testing
3549 * hardware encapsulation features instead of standard
3550 * features for the netdev
3552 if (skb->encapsulation)
3553 features &= dev->hw_enc_features;
3555 if (skb_vlan_tagged(skb))
3556 features = netdev_intersect_features(features,
3557 dev->vlan_features |
3558 NETIF_F_HW_VLAN_CTAG_TX |
3559 NETIF_F_HW_VLAN_STAG_TX);
3561 if (dev->netdev_ops->ndo_features_check)
3562 features &= dev->netdev_ops->ndo_features_check(skb, dev,
3565 features &= dflt_features_check(skb, dev, features);
3567 return harmonize_features(skb, features);
3569 EXPORT_SYMBOL(netif_skb_features);
3571 static int xmit_one(struct sk_buff *skb, struct net_device *dev,
3572 struct netdev_queue *txq, bool more)
3577 if (dev_nit_active(dev))
3578 dev_queue_xmit_nit(skb, dev);
3581 trace_net_dev_start_xmit(skb, dev);
3582 rc = netdev_start_xmit(skb, dev, txq, more);
3583 trace_net_dev_xmit(skb, rc, dev, len);
3588 struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
3589 struct netdev_queue *txq, int *ret)
3591 struct sk_buff *skb = first;
3592 int rc = NETDEV_TX_OK;
3595 struct sk_buff *next = skb->next;
3597 skb_mark_not_on_list(skb);
3598 rc = xmit_one(skb, dev, txq, next != NULL);
3599 if (unlikely(!dev_xmit_complete(rc))) {
3605 if (netif_tx_queue_stopped(txq) && skb) {
3606 rc = NETDEV_TX_BUSY;
3616 static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
3617 netdev_features_t features)
3619 if (skb_vlan_tag_present(skb) &&
3620 !vlan_hw_offload_capable(features, skb->vlan_proto))
3621 skb = __vlan_hwaccel_push_inside(skb);
3625 int skb_csum_hwoffload_help(struct sk_buff *skb,
3626 const netdev_features_t features)
3628 if (unlikely(skb_csum_is_sctp(skb)))
3629 return !!(features & NETIF_F_SCTP_CRC) ? 0 :
3630 skb_crc32c_csum_help(skb);
3632 if (features & NETIF_F_HW_CSUM)
3635 if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
3636 switch (skb->csum_offset) {
3637 case offsetof(struct tcphdr, check):
3638 case offsetof(struct udphdr, check):
3643 return skb_checksum_help(skb);
3645 EXPORT_SYMBOL(skb_csum_hwoffload_help);
3647 static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
3649 netdev_features_t features;
3651 features = netif_skb_features(skb);
3652 skb = validate_xmit_vlan(skb, features);
3656 skb = sk_validate_xmit_skb(skb, dev);
3660 if (netif_needs_gso(skb, features)) {
3661 struct sk_buff *segs;
3663 segs = skb_gso_segment(skb, features);
3671 if (skb_needs_linearize(skb, features) &&
3672 __skb_linearize(skb))
3675 /* If packet is not checksummed and device does not
3676 * support checksumming for this protocol, complete
3677 * checksumming here.
3679 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3680 if (skb->encapsulation)
3681 skb_set_inner_transport_header(skb,
3682 skb_checksum_start_offset(skb));
3684 skb_set_transport_header(skb,
3685 skb_checksum_start_offset(skb));
3686 if (skb_csum_hwoffload_help(skb, features))
3691 skb = validate_xmit_xfrm(skb, features, again);
3698 dev_core_stats_tx_dropped_inc(dev);
3702 struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
3704 struct sk_buff *next, *head = NULL, *tail;
3706 for (; skb != NULL; skb = next) {
3708 skb_mark_not_on_list(skb);
3710 /* in case skb won't be segmented, point to itself */
3713 skb = validate_xmit_skb(skb, dev, again);
3721 /* If skb was segmented, skb->prev points to
3722 * the last segment. If not, it still contains skb.
3728 EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
3730 static void qdisc_pkt_len_init(struct sk_buff *skb)
3732 const struct skb_shared_info *shinfo = skb_shinfo(skb);
3734 qdisc_skb_cb(skb)->pkt_len = skb->len;
3736 /* To get more precise estimation of bytes sent on wire,
3737 * we add to pkt_len the headers size of all segments
3739 if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
3740 u16 gso_segs = shinfo->gso_segs;
3741 unsigned int hdr_len;
3743 /* mac layer + network layer */
3744 hdr_len = skb_transport_offset(skb);
3746 /* + transport layer */
3747 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
3748 const struct tcphdr *th;
3749 struct tcphdr _tcphdr;
3751 th = skb_header_pointer(skb, hdr_len,
3752 sizeof(_tcphdr), &_tcphdr);
3754 hdr_len += __tcp_hdrlen(th);
3756 struct udphdr _udphdr;
3758 if (skb_header_pointer(skb, hdr_len,
3759 sizeof(_udphdr), &_udphdr))
3760 hdr_len += sizeof(struct udphdr);
3763 if (shinfo->gso_type & SKB_GSO_DODGY)
3764 gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
3767 qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
3771 static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
3772 struct sk_buff **to_free,
3773 struct netdev_queue *txq)
3777 rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
3778 if (rc == NET_XMIT_SUCCESS)
3779 trace_qdisc_enqueue(q, txq, skb);
3783 static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
3784 struct net_device *dev,
3785 struct netdev_queue *txq)
3787 spinlock_t *root_lock = qdisc_lock(q);
3788 struct sk_buff *to_free = NULL;
3792 qdisc_calculate_pkt_len(skb, q);
3794 tcf_set_drop_reason(skb, SKB_DROP_REASON_QDISC_DROP);
3796 if (q->flags & TCQ_F_NOLOCK) {
3797 if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
3798 qdisc_run_begin(q)) {
3799 /* Retest nolock_qdisc_is_empty() within the protection
3800 * of q->seqlock to protect from racing with requeuing.
3802 if (unlikely(!nolock_qdisc_is_empty(q))) {
3803 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3810 qdisc_bstats_cpu_update(q, skb);
3811 if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
3812 !nolock_qdisc_is_empty(q))
3816 return NET_XMIT_SUCCESS;
3819 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3823 if (unlikely(to_free))
3824 kfree_skb_list_reason(to_free,
3825 tcf_get_drop_reason(to_free));
3829 if (unlikely(READ_ONCE(q->owner) == smp_processor_id())) {
3830 kfree_skb_reason(skb, SKB_DROP_REASON_TC_RECLASSIFY_LOOP);
3831 return NET_XMIT_DROP;
3834 * Heuristic to force contended enqueues to serialize on a
3835 * separate lock before trying to get qdisc main lock.
3836 * This permits qdisc->running owner to get the lock more
3837 * often and dequeue packets faster.
3838 * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
3839 * and then other tasks will only enqueue packets. The packets will be
3840 * sent after the qdisc owner is scheduled again. To prevent this
3841 * scenario the task always serialize on the lock.
3843 contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
3844 if (unlikely(contended))
3845 spin_lock(&q->busylock);
3847 spin_lock(root_lock);
3848 if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
3849 __qdisc_drop(skb, &to_free);
3851 } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
3852 qdisc_run_begin(q)) {
3854 * This is a work-conserving queue; there are no old skbs
3855 * waiting to be sent out; and the qdisc is not running -
3856 * xmit the skb directly.
3859 qdisc_bstats_update(q, skb);
3861 if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
3862 if (unlikely(contended)) {
3863 spin_unlock(&q->busylock);
3870 rc = NET_XMIT_SUCCESS;
3872 WRITE_ONCE(q->owner, smp_processor_id());
3873 rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
3874 WRITE_ONCE(q->owner, -1);
3875 if (qdisc_run_begin(q)) {
3876 if (unlikely(contended)) {
3877 spin_unlock(&q->busylock);
3884 spin_unlock(root_lock);
3885 if (unlikely(to_free))
3886 kfree_skb_list_reason(to_free,
3887 tcf_get_drop_reason(to_free));
3888 if (unlikely(contended))
3889 spin_unlock(&q->busylock);
3893 #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
3894 static void skb_update_prio(struct sk_buff *skb)
3896 const struct netprio_map *map;
3897 const struct sock *sk;
3898 unsigned int prioidx;
3902 map = rcu_dereference_bh(skb->dev->priomap);
3905 sk = skb_to_full_sk(skb);
3909 prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
3911 if (prioidx < map->priomap_len)
3912 skb->priority = map->priomap[prioidx];
3915 #define skb_update_prio(skb)
3919 * dev_loopback_xmit - loop back @skb
3920 * @net: network namespace this loopback is happening in
3921 * @sk: sk needed to be a netfilter okfn
3922 * @skb: buffer to transmit
3924 int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
3926 skb_reset_mac_header(skb);
3927 __skb_pull(skb, skb_network_offset(skb));
3928 skb->pkt_type = PACKET_LOOPBACK;
3929 if (skb->ip_summed == CHECKSUM_NONE)
3930 skb->ip_summed = CHECKSUM_UNNECESSARY;
3931 DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
3936 EXPORT_SYMBOL(dev_loopback_xmit);
3938 #ifdef CONFIG_NET_EGRESS
3939 static struct netdev_queue *
3940 netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
3942 int qm = skb_get_queue_mapping(skb);
3944 return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
3947 #ifndef CONFIG_PREEMPT_RT
3948 static bool netdev_xmit_txqueue_skipped(void)
3950 return __this_cpu_read(softnet_data.xmit.skip_txqueue);
3953 void netdev_xmit_skip_txqueue(bool skip)
3955 __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
3957 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3960 static bool netdev_xmit_txqueue_skipped(void)
3962 return current->net_xmit.skip_txqueue;
3965 void netdev_xmit_skip_txqueue(bool skip)
3967 current->net_xmit.skip_txqueue = skip;
3969 EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
3971 #endif /* CONFIG_NET_EGRESS */
3973 #ifdef CONFIG_NET_XGRESS
3974 static int tc_run(struct tcx_entry *entry, struct sk_buff *skb,
3975 enum skb_drop_reason *drop_reason)
3977 int ret = TC_ACT_UNSPEC;
3978 #ifdef CONFIG_NET_CLS_ACT
3979 struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
3980 struct tcf_result res;
3985 if (static_branch_unlikely(&tcf_bypass_check_needed_key)) {
3986 if (tcf_block_bypass_sw(miniq->block))
3990 tc_skb_cb(skb)->mru = 0;
3991 tc_skb_cb(skb)->post_ct = false;
3992 tcf_set_drop_reason(skb, *drop_reason);
3994 mini_qdisc_bstats_cpu_update(miniq, skb);
3995 ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
3996 /* Only tcf related quirks below. */
3999 *drop_reason = tcf_get_drop_reason(skb);
4000 mini_qdisc_qstats_cpu_drop(miniq);
4003 case TC_ACT_RECLASSIFY:
4004 skb->tc_index = TC_H_MIN(res.classid);
4007 #endif /* CONFIG_NET_CLS_ACT */
4011 static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
4015 static_branch_inc(&tcx_needed_key);
4020 static_branch_dec(&tcx_needed_key);
4023 static __always_inline enum tcx_action_base
4024 tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
4025 const bool needs_mac)
4027 const struct bpf_mprog_fp *fp;
4028 const struct bpf_prog *prog;
4032 __skb_push(skb, skb->mac_len);
4033 bpf_mprog_foreach_prog(entry, fp, prog) {
4034 bpf_compute_data_pointers(skb);
4035 ret = bpf_prog_run(prog, skb);
4036 if (ret != TCX_NEXT)
4040 __skb_pull(skb, skb->mac_len);
4041 return tcx_action_code(skb, ret);
4044 static __always_inline struct sk_buff *
4045 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4046 struct net_device *orig_dev, bool *another)
4048 struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
4049 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_INGRESS;
4050 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
4056 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
4058 *ret = deliver_skb(skb, *pt_prev, orig_dev);
4062 qdisc_skb_cb(skb)->pkt_len = skb->len;
4063 tcx_set_ingress(skb, true);
4065 if (static_branch_unlikely(&tcx_needed_key)) {
4066 sch_ret = tcx_run(entry, skb, true);
4067 if (sch_ret != TC_ACT_UNSPEC)
4068 goto ingress_verdict;
4070 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
4073 case TC_ACT_REDIRECT:
4074 /* skb_mac_header check was done by BPF, so we can safely
4075 * push the L2 header back before redirecting to another
4078 __skb_push(skb, skb->mac_len);
4079 if (skb_do_redirect(skb) == -EAGAIN) {
4080 __skb_pull(skb, skb->mac_len);
4084 *ret = NET_RX_SUCCESS;
4085 bpf_net_ctx_clear(bpf_net_ctx);
4088 kfree_skb_reason(skb, drop_reason);
4090 bpf_net_ctx_clear(bpf_net_ctx);
4092 /* used by tc_run */
4098 case TC_ACT_CONSUMED:
4099 *ret = NET_RX_SUCCESS;
4100 bpf_net_ctx_clear(bpf_net_ctx);
4103 bpf_net_ctx_clear(bpf_net_ctx);
4108 static __always_inline struct sk_buff *
4109 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4111 struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
4112 enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_EGRESS;
4113 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
4119 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
4121 /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
4122 * already set by the caller.
4124 if (static_branch_unlikely(&tcx_needed_key)) {
4125 sch_ret = tcx_run(entry, skb, false);
4126 if (sch_ret != TC_ACT_UNSPEC)
4127 goto egress_verdict;
4129 sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
4132 case TC_ACT_REDIRECT:
4133 /* No need to push/pop skb's mac_header here on egress! */
4134 skb_do_redirect(skb);
4135 *ret = NET_XMIT_SUCCESS;
4136 bpf_net_ctx_clear(bpf_net_ctx);
4139 kfree_skb_reason(skb, drop_reason);
4140 *ret = NET_XMIT_DROP;
4141 bpf_net_ctx_clear(bpf_net_ctx);
4143 /* used by tc_run */
4149 case TC_ACT_CONSUMED:
4150 *ret = NET_XMIT_SUCCESS;
4151 bpf_net_ctx_clear(bpf_net_ctx);
4154 bpf_net_ctx_clear(bpf_net_ctx);
4159 static __always_inline struct sk_buff *
4160 sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
4161 struct net_device *orig_dev, bool *another)
4166 static __always_inline struct sk_buff *
4167 sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
4171 #endif /* CONFIG_NET_XGRESS */
4174 static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
4175 struct xps_dev_maps *dev_maps, unsigned int tci)
4177 int tc = netdev_get_prio_tc_map(dev, skb->priority);
4178 struct xps_map *map;
4179 int queue_index = -1;
4181 if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
4184 tci *= dev_maps->num_tc;
4187 map = rcu_dereference(dev_maps->attr_map[tci]);
4190 queue_index = map->queues[0];
4192 queue_index = map->queues[reciprocal_scale(
4193 skb_get_hash(skb), map->len)];
4194 if (unlikely(queue_index >= dev->real_num_tx_queues))
4201 static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
4202 struct sk_buff *skb)
4205 struct xps_dev_maps *dev_maps;
4206 struct sock *sk = skb->sk;
4207 int queue_index = -1;
4209 if (!static_key_false(&xps_needed))
4213 if (!static_key_false(&xps_rxqs_needed))
4216 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
4218 int tci = sk_rx_queue_get(sk);
4221 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4226 if (queue_index < 0) {
4227 dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
4229 unsigned int tci = skb->sender_cpu - 1;
4231 queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
4243 u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
4244 struct net_device *sb_dev)
4248 EXPORT_SYMBOL(dev_pick_tx_zero);
4250 u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
4251 struct net_device *sb_dev)
4253 return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
4255 EXPORT_SYMBOL(dev_pick_tx_cpu_id);
4257 u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
4258 struct net_device *sb_dev)
4260 struct sock *sk = skb->sk;
4261 int queue_index = sk_tx_queue_get(sk);
4263 sb_dev = sb_dev ? : dev;
4265 if (queue_index < 0 || skb->ooo_okay ||
4266 queue_index >= dev->real_num_tx_queues) {
4267 int new_index = get_xps_queue(dev, sb_dev, skb);
4270 new_index = skb_tx_hash(dev, sb_dev, skb);
4272 if (queue_index != new_index && sk &&
4274 rcu_access_pointer(sk->sk_dst_cache))
4275 sk_tx_queue_set(sk, new_index);
4277 queue_index = new_index;
4282 EXPORT_SYMBOL(netdev_pick_tx);
4284 struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
4285 struct sk_buff *skb,
4286 struct net_device *sb_dev)
4288 int queue_index = 0;
4291 u32 sender_cpu = skb->sender_cpu - 1;
4293 if (sender_cpu >= (u32)NR_CPUS)
4294 skb->sender_cpu = raw_smp_processor_id() + 1;
4297 if (dev->real_num_tx_queues != 1) {
4298 const struct net_device_ops *ops = dev->netdev_ops;
4300 if (ops->ndo_select_queue)
4301 queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
4303 queue_index = netdev_pick_tx(dev, skb, sb_dev);
4305 queue_index = netdev_cap_txqueue(dev, queue_index);
4308 skb_set_queue_mapping(skb, queue_index);
4309 return netdev_get_tx_queue(dev, queue_index);
4313 * __dev_queue_xmit() - transmit a buffer
4314 * @skb: buffer to transmit
4315 * @sb_dev: suboordinate device used for L2 forwarding offload
4317 * Queue a buffer for transmission to a network device. The caller must
4318 * have set the device and priority and built the buffer before calling
4319 * this function. The function can be called from an interrupt.
4321 * When calling this method, interrupts MUST be enabled. This is because
4322 * the BH enable code must have IRQs enabled so that it will not deadlock.
4324 * Regardless of the return value, the skb is consumed, so it is currently
4325 * difficult to retry a send to this method. (You can bump the ref count
4326 * before sending to hold a reference for retry if you are careful.)
4329 * * 0 - buffer successfully transmitted
4330 * * positive qdisc return code - NET_XMIT_DROP etc.
4331 * * negative errno - other errors
4333 int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
4335 struct net_device *dev = skb->dev;
4336 struct netdev_queue *txq = NULL;
4341 skb_reset_mac_header(skb);
4342 skb_assert_len(skb);
4344 if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
4345 __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
4347 /* Disable soft irqs for various locks below. Also
4348 * stops preemption for RCU.
4352 skb_update_prio(skb);
4354 qdisc_pkt_len_init(skb);
4355 tcx_set_ingress(skb, false);
4356 #ifdef CONFIG_NET_EGRESS
4357 if (static_branch_unlikely(&egress_needed_key)) {
4358 if (nf_hook_egress_active()) {
4359 skb = nf_hook_egress(skb, &rc, dev);
4364 netdev_xmit_skip_txqueue(false);
4366 nf_skip_egress(skb, true);
4367 skb = sch_handle_egress(skb, &rc, dev);
4370 nf_skip_egress(skb, false);
4372 if (netdev_xmit_txqueue_skipped())
4373 txq = netdev_tx_queue_mapping(dev, skb);
4376 /* If device/qdisc don't need skb->dst, release it right now while
4377 * its hot in this cpu cache.
4379 if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
4385 txq = netdev_core_pick_tx(dev, skb, sb_dev);
4387 q = rcu_dereference_bh(txq->qdisc);
4389 trace_net_dev_queue(skb);
4391 rc = __dev_xmit_skb(skb, q, dev, txq);
4395 /* The device has no queue. Common case for software devices:
4396 * loopback, all the sorts of tunnels...
4398 * Really, it is unlikely that netif_tx_lock protection is necessary
4399 * here. (f.e. loopback and IP tunnels are clean ignoring statistics
4401 * However, it is possible, that they rely on protection
4404 * Check this and shot the lock. It is not prone from deadlocks.
4405 *Either shot noqueue qdisc, it is even simpler 8)
4407 if (dev->flags & IFF_UP) {
4408 int cpu = smp_processor_id(); /* ok because BHs are off */
4410 /* Other cpus might concurrently change txq->xmit_lock_owner
4411 * to -1 or to their cpu id, but not to our id.
4413 if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
4414 if (dev_xmit_recursion())
4415 goto recursion_alert;
4417 skb = validate_xmit_skb(skb, dev, &again);
4421 HARD_TX_LOCK(dev, txq, cpu);
4423 if (!netif_xmit_stopped(txq)) {
4424 dev_xmit_recursion_inc();
4425 skb = dev_hard_start_xmit(skb, dev, txq, &rc);
4426 dev_xmit_recursion_dec();
4427 if (dev_xmit_complete(rc)) {
4428 HARD_TX_UNLOCK(dev, txq);
4432 HARD_TX_UNLOCK(dev, txq);
4433 net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
4436 /* Recursion is detected! It is possible,
4440 net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
4446 rcu_read_unlock_bh();
4448 dev_core_stats_tx_dropped_inc(dev);
4449 kfree_skb_list(skb);
4452 rcu_read_unlock_bh();
4455 EXPORT_SYMBOL(__dev_queue_xmit);
4457 int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
4459 struct net_device *dev = skb->dev;
4460 struct sk_buff *orig_skb = skb;
4461 struct netdev_queue *txq;
4462 int ret = NETDEV_TX_BUSY;
4465 if (unlikely(!netif_running(dev) ||
4466 !netif_carrier_ok(dev)))
4469 skb = validate_xmit_skb_list(skb, dev, &again);
4470 if (skb != orig_skb)
4473 skb_set_queue_mapping(skb, queue_id);
4474 txq = skb_get_tx_queue(dev, skb);
4478 dev_xmit_recursion_inc();
4479 HARD_TX_LOCK(dev, txq, smp_processor_id());
4480 if (!netif_xmit_frozen_or_drv_stopped(txq))
4481 ret = netdev_start_xmit(skb, dev, txq, false);
4482 HARD_TX_UNLOCK(dev, txq);
4483 dev_xmit_recursion_dec();
4488 dev_core_stats_tx_dropped_inc(dev);
4489 kfree_skb_list(skb);
4490 return NET_XMIT_DROP;
4492 EXPORT_SYMBOL(__dev_direct_xmit);
4494 /*************************************************************************
4496 *************************************************************************/
4497 static DEFINE_PER_CPU(struct task_struct *, backlog_napi);
4499 int weight_p __read_mostly = 64; /* old backlog weight */
4500 int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
4501 int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
4503 /* Called with irq disabled */
4504 static inline void ____napi_schedule(struct softnet_data *sd,
4505 struct napi_struct *napi)
4507 struct task_struct *thread;
4509 lockdep_assert_irqs_disabled();
4511 if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
4512 /* Paired with smp_mb__before_atomic() in
4513 * napi_enable()/dev_set_threaded().
4514 * Use READ_ONCE() to guarantee a complete
4515 * read on napi->thread. Only call
4516 * wake_up_process() when it's not NULL.
4518 thread = READ_ONCE(napi->thread);
4520 if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi))
4521 goto use_local_napi;
4523 set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
4524 wake_up_process(thread);
4530 list_add_tail(&napi->poll_list, &sd->poll_list);
4531 WRITE_ONCE(napi->list_owner, smp_processor_id());
4532 /* If not called from net_rx_action()
4533 * we have to raise NET_RX_SOFTIRQ.
4535 if (!sd->in_net_rx_action)
4536 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4541 struct static_key_false rps_needed __read_mostly;
4542 EXPORT_SYMBOL(rps_needed);
4543 struct static_key_false rfs_needed __read_mostly;
4544 EXPORT_SYMBOL(rfs_needed);
4546 static struct rps_dev_flow *
4547 set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4548 struct rps_dev_flow *rflow, u16 next_cpu)
4550 if (next_cpu < nr_cpu_ids) {
4552 #ifdef CONFIG_RFS_ACCEL
4553 struct netdev_rx_queue *rxqueue;
4554 struct rps_dev_flow_table *flow_table;
4555 struct rps_dev_flow *old_rflow;
4560 /* Should we steer this flow to a different hardware queue? */
4561 if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
4562 !(dev->features & NETIF_F_NTUPLE))
4564 rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
4565 if (rxq_index == skb_get_rx_queue(skb))
4568 rxqueue = dev->_rx + rxq_index;
4569 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4572 flow_id = skb_get_hash(skb) & flow_table->mask;
4573 rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
4574 rxq_index, flow_id);
4578 rflow = &flow_table->flows[flow_id];
4579 WRITE_ONCE(rflow->filter, rc);
4580 if (old_rflow->filter == rc)
4581 WRITE_ONCE(old_rflow->filter, RPS_NO_FILTER);
4584 head = READ_ONCE(per_cpu(softnet_data, next_cpu).input_queue_head);
4585 rps_input_queue_tail_save(&rflow->last_qtail, head);
4588 WRITE_ONCE(rflow->cpu, next_cpu);
4593 * get_rps_cpu is called from netif_receive_skb and returns the target
4594 * CPU from the RPS map of the receiving queue for a given skb.
4595 * rcu_read_lock must be held on entry.
4597 static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
4598 struct rps_dev_flow **rflowp)
4600 const struct rps_sock_flow_table *sock_flow_table;
4601 struct netdev_rx_queue *rxqueue = dev->_rx;
4602 struct rps_dev_flow_table *flow_table;
4603 struct rps_map *map;
4608 if (skb_rx_queue_recorded(skb)) {
4609 u16 index = skb_get_rx_queue(skb);
4611 if (unlikely(index >= dev->real_num_rx_queues)) {
4612 WARN_ONCE(dev->real_num_rx_queues > 1,
4613 "%s received packet on queue %u, but number "
4614 "of RX queues is %u\n",
4615 dev->name, index, dev->real_num_rx_queues);
4621 /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
4623 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4624 map = rcu_dereference(rxqueue->rps_map);
4625 if (!flow_table && !map)
4628 skb_reset_network_header(skb);
4629 hash = skb_get_hash(skb);
4633 sock_flow_table = rcu_dereference(net_hotdata.rps_sock_flow_table);
4634 if (flow_table && sock_flow_table) {
4635 struct rps_dev_flow *rflow;
4639 /* First check into global flow table if there is a match.
4640 * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
4642 ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
4643 if ((ident ^ hash) & ~net_hotdata.rps_cpu_mask)
4646 next_cpu = ident & net_hotdata.rps_cpu_mask;
4648 /* OK, now we know there is a match,
4649 * we can look at the local (per receive queue) flow table
4651 rflow = &flow_table->flows[hash & flow_table->mask];
4655 * If the desired CPU (where last recvmsg was done) is
4656 * different from current CPU (one in the rx-queue flow
4657 * table entry), switch if one of the following holds:
4658 * - Current CPU is unset (>= nr_cpu_ids).
4659 * - Current CPU is offline.
4660 * - The current CPU's queue tail has advanced beyond the
4661 * last packet that was enqueued using this table entry.
4662 * This guarantees that all previous packets for the flow
4663 * have been dequeued, thus preserving in order delivery.
4665 if (unlikely(tcpu != next_cpu) &&
4666 (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
4667 ((int)(READ_ONCE(per_cpu(softnet_data, tcpu).input_queue_head) -
4668 rflow->last_qtail)) >= 0)) {
4670 rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
4673 if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
4683 tcpu = map->cpus[reciprocal_scale(hash, map->len)];
4684 if (cpu_online(tcpu)) {
4694 #ifdef CONFIG_RFS_ACCEL
4697 * rps_may_expire_flow - check whether an RFS hardware filter may be removed
4698 * @dev: Device on which the filter was set
4699 * @rxq_index: RX queue index
4700 * @flow_id: Flow ID passed to ndo_rx_flow_steer()
4701 * @filter_id: Filter ID returned by ndo_rx_flow_steer()
4703 * Drivers that implement ndo_rx_flow_steer() should periodically call
4704 * this function for each installed filter and remove the filters for
4705 * which it returns %true.
4707 bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
4708 u32 flow_id, u16 filter_id)
4710 struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
4711 struct rps_dev_flow_table *flow_table;
4712 struct rps_dev_flow *rflow;
4717 flow_table = rcu_dereference(rxqueue->rps_flow_table);
4718 if (flow_table && flow_id <= flow_table->mask) {
4719 rflow = &flow_table->flows[flow_id];
4720 cpu = READ_ONCE(rflow->cpu);
4721 if (READ_ONCE(rflow->filter) == filter_id && cpu < nr_cpu_ids &&
4722 ((int)(READ_ONCE(per_cpu(softnet_data, cpu).input_queue_head) -
4723 READ_ONCE(rflow->last_qtail)) <
4724 (int)(10 * flow_table->mask)))
4730 EXPORT_SYMBOL(rps_may_expire_flow);
4732 #endif /* CONFIG_RFS_ACCEL */
4734 /* Called from hardirq (IPI) context */
4735 static void rps_trigger_softirq(void *data)
4737 struct softnet_data *sd = data;
4739 ____napi_schedule(sd, &sd->backlog);
4743 #endif /* CONFIG_RPS */
4745 /* Called from hardirq (IPI) context */
4746 static void trigger_rx_softirq(void *data)
4748 struct softnet_data *sd = data;
4750 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4751 smp_store_release(&sd->defer_ipi_scheduled, 0);
4755 * After we queued a packet into sd->input_pkt_queue,
4756 * we need to make sure this queue is serviced soon.
4758 * - If this is another cpu queue, link it to our rps_ipi_list,
4759 * and make sure we will process rps_ipi_list from net_rx_action().
4761 * - If this is our own queue, NAPI schedule our backlog.
4762 * Note that this also raises NET_RX_SOFTIRQ.
4764 static void napi_schedule_rps(struct softnet_data *sd)
4766 struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
4770 if (use_backlog_threads()) {
4771 __napi_schedule_irqoff(&sd->backlog);
4775 sd->rps_ipi_next = mysd->rps_ipi_list;
4776 mysd->rps_ipi_list = sd;
4778 /* If not called from net_rx_action() or napi_threaded_poll()
4779 * we have to raise NET_RX_SOFTIRQ.
4781 if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
4782 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
4785 #endif /* CONFIG_RPS */
4786 __napi_schedule_irqoff(&mysd->backlog);
4789 void kick_defer_list_purge(struct softnet_data *sd, unsigned int cpu)
4791 unsigned long flags;
4793 if (use_backlog_threads()) {
4794 backlog_lock_irq_save(sd, &flags);
4796 if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
4797 __napi_schedule_irqoff(&sd->backlog);
4799 backlog_unlock_irq_restore(sd, &flags);
4801 } else if (!cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) {
4802 smp_call_function_single_async(cpu, &sd->defer_csd);
4806 #ifdef CONFIG_NET_FLOW_LIMIT
4807 int netdev_flow_limit_table_len __read_mostly = (1 << 12);
4810 static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
4812 #ifdef CONFIG_NET_FLOW_LIMIT
4813 struct sd_flow_limit *fl;
4814 struct softnet_data *sd;
4815 unsigned int old_flow, new_flow;
4817 if (qlen < (READ_ONCE(net_hotdata.max_backlog) >> 1))
4820 sd = this_cpu_ptr(&softnet_data);
4823 fl = rcu_dereference(sd->flow_limit);
4825 new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
4826 old_flow = fl->history[fl->history_head];
4827 fl->history[fl->history_head] = new_flow;
4830 fl->history_head &= FLOW_LIMIT_HISTORY - 1;
4832 if (likely(fl->buckets[old_flow]))
4833 fl->buckets[old_flow]--;
4835 if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
4847 * enqueue_to_backlog is called to queue an skb to a per CPU backlog
4848 * queue (may be a remote CPU queue).
4850 static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
4851 unsigned int *qtail)
4853 enum skb_drop_reason reason;
4854 struct softnet_data *sd;
4855 unsigned long flags;
4860 reason = SKB_DROP_REASON_DEV_READY;
4861 if (!netif_running(skb->dev))
4864 reason = SKB_DROP_REASON_CPU_BACKLOG;
4865 sd = &per_cpu(softnet_data, cpu);
4867 qlen = skb_queue_len_lockless(&sd->input_pkt_queue);
4868 max_backlog = READ_ONCE(net_hotdata.max_backlog);
4869 if (unlikely(qlen > max_backlog))
4870 goto cpu_backlog_drop;
4871 backlog_lock_irq_save(sd, &flags);
4872 qlen = skb_queue_len(&sd->input_pkt_queue);
4873 if (qlen <= max_backlog && !skb_flow_limit(skb, qlen)) {
4875 /* Schedule NAPI for backlog device. We can use
4876 * non atomic operation as we own the queue lock.
4878 if (!__test_and_set_bit(NAPI_STATE_SCHED,
4879 &sd->backlog.state))
4880 napi_schedule_rps(sd);
4882 __skb_queue_tail(&sd->input_pkt_queue, skb);
4883 tail = rps_input_queue_tail_incr(sd);
4884 backlog_unlock_irq_restore(sd, &flags);
4886 /* save the tail outside of the critical section */
4887 rps_input_queue_tail_save(qtail, tail);
4888 return NET_RX_SUCCESS;
4891 backlog_unlock_irq_restore(sd, &flags);
4894 atomic_inc(&sd->dropped);
4896 dev_core_stats_rx_dropped_inc(skb->dev);
4897 kfree_skb_reason(skb, reason);
4901 static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
4903 struct net_device *dev = skb->dev;
4904 struct netdev_rx_queue *rxqueue;
4908 if (skb_rx_queue_recorded(skb)) {
4909 u16 index = skb_get_rx_queue(skb);
4911 if (unlikely(index >= dev->real_num_rx_queues)) {
4912 WARN_ONCE(dev->real_num_rx_queues > 1,
4913 "%s received packet on queue %u, but number "
4914 "of RX queues is %u\n",
4915 dev->name, index, dev->real_num_rx_queues);
4917 return rxqueue; /* Return first rxqueue */
4924 u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
4925 struct bpf_prog *xdp_prog)
4927 void *orig_data, *orig_data_end, *hard_start;
4928 struct netdev_rx_queue *rxqueue;
4929 bool orig_bcast, orig_host;
4930 u32 mac_len, frame_sz;
4931 __be16 orig_eth_type;
4936 /* The XDP program wants to see the packet starting at the MAC
4939 mac_len = skb->data - skb_mac_header(skb);
4940 hard_start = skb->data - skb_headroom(skb);
4942 /* SKB "head" area always have tailroom for skb_shared_info */
4943 frame_sz = (void *)skb_end_pointer(skb) - hard_start;
4944 frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4946 rxqueue = netif_get_rxqueue(skb);
4947 xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
4948 xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
4949 skb_headlen(skb) + mac_len, true);
4950 if (skb_is_nonlinear(skb)) {
4951 skb_shinfo(skb)->xdp_frags_size = skb->data_len;
4952 xdp_buff_set_frags_flag(xdp);
4954 xdp_buff_clear_frags_flag(xdp);
4957 orig_data_end = xdp->data_end;
4958 orig_data = xdp->data;
4959 eth = (struct ethhdr *)xdp->data;
4960 orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
4961 orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
4962 orig_eth_type = eth->h_proto;
4964 act = bpf_prog_run_xdp(xdp_prog, xdp);
4966 /* check if bpf_xdp_adjust_head was used */
4967 off = xdp->data - orig_data;
4970 __skb_pull(skb, off);
4972 __skb_push(skb, -off);
4974 skb->mac_header += off;
4975 skb_reset_network_header(skb);
4978 /* check if bpf_xdp_adjust_tail was used */
4979 off = xdp->data_end - orig_data_end;
4981 skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
4982 skb->len += off; /* positive on grow, negative on shrink */
4985 /* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers
4986 * (e.g. bpf_xdp_adjust_tail), we need to update data_len here.
4988 if (xdp_buff_has_frags(xdp))
4989 skb->data_len = skb_shinfo(skb)->xdp_frags_size;
4993 /* check if XDP changed eth hdr such SKB needs update */
4994 eth = (struct ethhdr *)xdp->data;
4995 if ((orig_eth_type != eth->h_proto) ||
4996 (orig_host != ether_addr_equal_64bits(eth->h_dest,
4997 skb->dev->dev_addr)) ||
4998 (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
4999 __skb_push(skb, ETH_HLEN);
5000 skb->pkt_type = PACKET_HOST;
5001 skb->protocol = eth_type_trans(skb, skb->dev);
5004 /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
5005 * before calling us again on redirect path. We do not call do_redirect
5006 * as we leave that up to the caller.
5008 * Caller is responsible for managing lifetime of skb (i.e. calling
5009 * kfree_skb in response to actions it cannot handle/XDP_DROP).
5014 __skb_push(skb, mac_len);
5017 metalen = xdp->data - xdp->data_meta;
5019 skb_metadata_set(skb, metalen);
5027 netif_skb_check_for_xdp(struct sk_buff **pskb, struct bpf_prog *prog)
5029 struct sk_buff *skb = *pskb;
5030 int err, hroom, troom;
5032 if (!skb_cow_data_for_xdp(this_cpu_read(system_page_pool), pskb, prog))
5035 /* In case we have to go down the path and also linearize,
5036 * then lets do the pskb_expand_head() work just once here.
5038 hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
5039 troom = skb->tail + skb->data_len - skb->end;
5040 err = pskb_expand_head(skb,
5041 hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
5042 troom > 0 ? troom + 128 : 0, GFP_ATOMIC);
5046 return skb_linearize(skb);
5049 static u32 netif_receive_generic_xdp(struct sk_buff **pskb,
5050 struct xdp_buff *xdp,
5051 struct bpf_prog *xdp_prog)
5053 struct sk_buff *skb = *pskb;
5054 u32 mac_len, act = XDP_DROP;
5056 /* Reinjected packets coming from act_mirred or similar should
5057 * not get XDP generic processing.
5059 if (skb_is_redirected(skb))
5062 /* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM
5063 * bytes. This is the guarantee that also native XDP provides,
5064 * thus we need to do it here as well.
5066 mac_len = skb->data - skb_mac_header(skb);
5067 __skb_push(skb, mac_len);
5069 if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
5070 skb_headroom(skb) < XDP_PACKET_HEADROOM) {
5071 if (netif_skb_check_for_xdp(pskb, xdp_prog))
5075 __skb_pull(*pskb, mac_len);
5077 act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog);
5084 bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act);
5087 trace_xdp_exception((*pskb)->dev, xdp_prog, act);
5098 /* When doing generic XDP we have to bypass the qdisc layer and the
5099 * network taps in order to match in-driver-XDP behavior. This also means
5100 * that XDP packets are able to starve other packets going through a qdisc,
5101 * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
5102 * queues, so they do not have this starvation issue.
5104 void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
5106 struct net_device *dev = skb->dev;
5107 struct netdev_queue *txq;
5108 bool free_skb = true;
5111 txq = netdev_core_pick_tx(dev, skb, NULL);
5112 cpu = smp_processor_id();
5113 HARD_TX_LOCK(dev, txq, cpu);
5114 if (!netif_xmit_frozen_or_drv_stopped(txq)) {
5115 rc = netdev_start_xmit(skb, dev, txq, 0);
5116 if (dev_xmit_complete(rc))
5119 HARD_TX_UNLOCK(dev, txq);
5121 trace_xdp_exception(dev, xdp_prog, XDP_TX);
5122 dev_core_stats_tx_dropped_inc(dev);
5127 static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
5129 int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff **pskb)
5131 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
5134 struct xdp_buff xdp;
5138 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
5139 act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog);
5140 if (act != XDP_PASS) {
5143 err = xdp_do_generic_redirect((*pskb)->dev, *pskb,
5149 generic_xdp_tx(*pskb, xdp_prog);
5152 bpf_net_ctx_clear(bpf_net_ctx);
5155 bpf_net_ctx_clear(bpf_net_ctx);
5159 bpf_net_ctx_clear(bpf_net_ctx);
5160 kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP);
5163 EXPORT_SYMBOL_GPL(do_xdp_generic);
5165 static int netif_rx_internal(struct sk_buff *skb)
5169 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5171 trace_netif_rx(skb);
5174 if (static_branch_unlikely(&rps_needed)) {
5175 struct rps_dev_flow voidflow, *rflow = &voidflow;
5180 cpu = get_rps_cpu(skb->dev, skb, &rflow);
5182 cpu = smp_processor_id();
5184 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5192 ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
5198 * __netif_rx - Slightly optimized version of netif_rx
5199 * @skb: buffer to post
5201 * This behaves as netif_rx except that it does not disable bottom halves.
5202 * As a result this function may only be invoked from the interrupt context
5203 * (either hard or soft interrupt).
5205 int __netif_rx(struct sk_buff *skb)
5209 lockdep_assert_once(hardirq_count() | softirq_count());
5211 trace_netif_rx_entry(skb);
5212 ret = netif_rx_internal(skb);
5213 trace_netif_rx_exit(ret);
5216 EXPORT_SYMBOL(__netif_rx);
5219 * netif_rx - post buffer to the network code
5220 * @skb: buffer to post
5222 * This function receives a packet from a device driver and queues it for
5223 * the upper (protocol) levels to process via the backlog NAPI device. It
5224 * always succeeds. The buffer may be dropped during processing for
5225 * congestion control or by the protocol layers.
5226 * The network buffer is passed via the backlog NAPI device. Modern NIC
5227 * driver should use NAPI and GRO.
5228 * This function can used from interrupt and from process context. The
5229 * caller from process context must not disable interrupts before invoking
5233 * NET_RX_SUCCESS (no congestion)
5234 * NET_RX_DROP (packet was dropped)
5237 int netif_rx(struct sk_buff *skb)
5239 bool need_bh_off = !(hardirq_count() | softirq_count());
5244 trace_netif_rx_entry(skb);
5245 ret = netif_rx_internal(skb);
5246 trace_netif_rx_exit(ret);
5251 EXPORT_SYMBOL(netif_rx);
5253 static __latent_entropy void net_tx_action(struct softirq_action *h)
5255 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
5257 if (sd->completion_queue) {
5258 struct sk_buff *clist;
5260 local_irq_disable();
5261 clist = sd->completion_queue;
5262 sd->completion_queue = NULL;
5266 struct sk_buff *skb = clist;
5268 clist = clist->next;
5270 WARN_ON(refcount_read(&skb->users));
5271 if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
5272 trace_consume_skb(skb, net_tx_action);
5274 trace_kfree_skb(skb, net_tx_action,
5275 get_kfree_skb_cb(skb)->reason, NULL);
5277 if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
5280 __napi_kfree_skb(skb,
5281 get_kfree_skb_cb(skb)->reason);
5285 if (sd->output_queue) {
5288 local_irq_disable();
5289 head = sd->output_queue;
5290 sd->output_queue = NULL;
5291 sd->output_queue_tailp = &sd->output_queue;
5297 struct Qdisc *q = head;
5298 spinlock_t *root_lock = NULL;
5300 head = head->next_sched;
5302 /* We need to make sure head->next_sched is read
5303 * before clearing __QDISC_STATE_SCHED
5305 smp_mb__before_atomic();
5307 if (!(q->flags & TCQ_F_NOLOCK)) {
5308 root_lock = qdisc_lock(q);
5309 spin_lock(root_lock);
5310 } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
5312 /* There is a synchronize_net() between
5313 * STATE_DEACTIVATED flag being set and
5314 * qdisc_reset()/some_qdisc_is_busy() in
5315 * dev_deactivate(), so we can safely bail out
5316 * early here to avoid data race between
5317 * qdisc_deactivate() and some_qdisc_is_busy()
5318 * for lockless qdisc.
5320 clear_bit(__QDISC_STATE_SCHED, &q->state);
5324 clear_bit(__QDISC_STATE_SCHED, &q->state);
5327 spin_unlock(root_lock);
5333 xfrm_dev_backlog(sd);
5336 #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
5337 /* This hook is defined here for ATM LANE */
5338 int (*br_fdb_test_addr_hook)(struct net_device *dev,
5339 unsigned char *addr) __read_mostly;
5340 EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
5344 * netdev_is_rx_handler_busy - check if receive handler is registered
5345 * @dev: device to check
5347 * Check if a receive handler is already registered for a given device.
5348 * Return true if there one.
5350 * The caller must hold the rtnl_mutex.
5352 bool netdev_is_rx_handler_busy(struct net_device *dev)
5355 return dev && rtnl_dereference(dev->rx_handler);
5357 EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
5360 * netdev_rx_handler_register - register receive handler
5361 * @dev: device to register a handler for
5362 * @rx_handler: receive handler to register
5363 * @rx_handler_data: data pointer that is used by rx handler
5365 * Register a receive handler for a device. This handler will then be
5366 * called from __netif_receive_skb. A negative errno code is returned
5369 * The caller must hold the rtnl_mutex.
5371 * For a general description of rx_handler, see enum rx_handler_result.
5373 int netdev_rx_handler_register(struct net_device *dev,
5374 rx_handler_func_t *rx_handler,
5375 void *rx_handler_data)
5377 if (netdev_is_rx_handler_busy(dev))
5380 if (dev->priv_flags & IFF_NO_RX_HANDLER)
5383 /* Note: rx_handler_data must be set before rx_handler */
5384 rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
5385 rcu_assign_pointer(dev->rx_handler, rx_handler);
5389 EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
5392 * netdev_rx_handler_unregister - unregister receive handler
5393 * @dev: device to unregister a handler from
5395 * Unregister a receive handler from a device.
5397 * The caller must hold the rtnl_mutex.
5399 void netdev_rx_handler_unregister(struct net_device *dev)
5403 RCU_INIT_POINTER(dev->rx_handler, NULL);
5404 /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
5405 * section has a guarantee to see a non NULL rx_handler_data
5409 RCU_INIT_POINTER(dev->rx_handler_data, NULL);
5411 EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
5414 * Limit the use of PFMEMALLOC reserves to those protocols that implement
5415 * the special handling of PFMEMALLOC skbs.
5417 static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
5419 switch (skb->protocol) {
5420 case htons(ETH_P_ARP):
5421 case htons(ETH_P_IP):
5422 case htons(ETH_P_IPV6):
5423 case htons(ETH_P_8021Q):
5424 case htons(ETH_P_8021AD):
5431 static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
5432 int *ret, struct net_device *orig_dev)
5434 if (nf_hook_ingress_active(skb)) {
5438 *ret = deliver_skb(skb, *pt_prev, orig_dev);
5443 ingress_retval = nf_hook_ingress(skb);
5445 return ingress_retval;
5450 static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
5451 struct packet_type **ppt_prev)
5453 struct packet_type *ptype, *pt_prev;
5454 rx_handler_func_t *rx_handler;
5455 struct sk_buff *skb = *pskb;
5456 struct net_device *orig_dev;
5457 bool deliver_exact = false;
5458 int ret = NET_RX_DROP;
5461 net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5463 trace_netif_receive_skb(skb);
5465 orig_dev = skb->dev;
5467 skb_reset_network_header(skb);
5468 if (!skb_transport_header_was_set(skb))
5469 skb_reset_transport_header(skb);
5470 skb_reset_mac_len(skb);
5475 skb->skb_iif = skb->dev->ifindex;
5477 __this_cpu_inc(softnet_data.processed);
5479 if (static_branch_unlikely(&generic_xdp_needed_key)) {
5483 ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog),
5487 if (ret2 != XDP_PASS) {
5493 if (eth_type_vlan(skb->protocol)) {
5494 skb = skb_vlan_untag(skb);
5499 if (skb_skip_tc_classify(skb))
5505 list_for_each_entry_rcu(ptype, &net_hotdata.ptype_all, list) {
5507 ret = deliver_skb(skb, pt_prev, orig_dev);
5511 list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
5513 ret = deliver_skb(skb, pt_prev, orig_dev);
5518 #ifdef CONFIG_NET_INGRESS
5519 if (static_branch_unlikely(&ingress_needed_key)) {
5520 bool another = false;
5522 nf_skip_egress(skb, true);
5523 skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
5530 nf_skip_egress(skb, false);
5531 if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
5535 skb_reset_redirect(skb);
5537 if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
5540 if (skb_vlan_tag_present(skb)) {
5542 ret = deliver_skb(skb, pt_prev, orig_dev);
5545 if (vlan_do_receive(&skb))
5547 else if (unlikely(!skb))
5551 rx_handler = rcu_dereference(skb->dev->rx_handler);
5554 ret = deliver_skb(skb, pt_prev, orig_dev);
5557 switch (rx_handler(&skb)) {
5558 case RX_HANDLER_CONSUMED:
5559 ret = NET_RX_SUCCESS;
5561 case RX_HANDLER_ANOTHER:
5563 case RX_HANDLER_EXACT:
5564 deliver_exact = true;
5566 case RX_HANDLER_PASS:
5573 if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
5575 if (skb_vlan_tag_get_id(skb)) {
5576 /* Vlan id is non 0 and vlan_do_receive() above couldn't
5579 skb->pkt_type = PACKET_OTHERHOST;
5580 } else if (eth_type_vlan(skb->protocol)) {
5581 /* Outer header is 802.1P with vlan 0, inner header is
5582 * 802.1Q or 802.1AD and vlan_do_receive() above could
5583 * not find vlan dev for vlan id 0.
5585 __vlan_hwaccel_clear_tag(skb);
5586 skb = skb_vlan_untag(skb);
5589 if (vlan_do_receive(&skb))
5590 /* After stripping off 802.1P header with vlan 0
5591 * vlan dev is found for inner header.
5594 else if (unlikely(!skb))
5597 /* We have stripped outer 802.1P vlan 0 header.
5598 * But could not find vlan dev.
5599 * check again for vlan id to set OTHERHOST.
5603 /* Note: we might in the future use prio bits
5604 * and set skb->priority like in vlan_do_receive()
5605 * For the time being, just ignore Priority Code Point
5607 __vlan_hwaccel_clear_tag(skb);
5610 type = skb->protocol;
5612 /* deliver only exact match when indicated */
5613 if (likely(!deliver_exact)) {
5614 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5615 &ptype_base[ntohs(type) &
5619 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5620 &orig_dev->ptype_specific);
5622 if (unlikely(skb->dev != orig_dev)) {
5623 deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
5624 &skb->dev->ptype_specific);
5628 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
5630 *ppt_prev = pt_prev;
5634 dev_core_stats_rx_dropped_inc(skb->dev);
5636 dev_core_stats_rx_nohandler_inc(skb->dev);
5637 kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
5638 /* Jamal, now you will not able to escape explaining
5639 * me how you were going to use this. :-)
5645 /* The invariant here is that if *ppt_prev is not NULL
5646 * then skb should also be non-NULL.
5648 * Apparently *ppt_prev assignment above holds this invariant due to
5649 * skb dereferencing near it.
5655 static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
5657 struct net_device *orig_dev = skb->dev;
5658 struct packet_type *pt_prev = NULL;
5661 ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5663 ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
5664 skb->dev, pt_prev, orig_dev);
5669 * netif_receive_skb_core - special purpose version of netif_receive_skb
5670 * @skb: buffer to process
5672 * More direct receive version of netif_receive_skb(). It should
5673 * only be used by callers that have a need to skip RPS and Generic XDP.
5674 * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
5676 * This function may only be called from softirq context and interrupts
5677 * should be enabled.
5679 * Return values (usually ignored):
5680 * NET_RX_SUCCESS: no congestion
5681 * NET_RX_DROP: packet was dropped
5683 int netif_receive_skb_core(struct sk_buff *skb)
5688 ret = __netif_receive_skb_one_core(skb, false);
5693 EXPORT_SYMBOL(netif_receive_skb_core);
5695 static inline void __netif_receive_skb_list_ptype(struct list_head *head,
5696 struct packet_type *pt_prev,
5697 struct net_device *orig_dev)
5699 struct sk_buff *skb, *next;
5703 if (list_empty(head))
5705 if (pt_prev->list_func != NULL)
5706 INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
5707 ip_list_rcv, head, pt_prev, orig_dev);
5709 list_for_each_entry_safe(skb, next, head, list) {
5710 skb_list_del_init(skb);
5711 pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
5715 static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
5717 /* Fast-path assumptions:
5718 * - There is no RX handler.
5719 * - Only one packet_type matches.
5720 * If either of these fails, we will end up doing some per-packet
5721 * processing in-line, then handling the 'last ptype' for the whole
5722 * sublist. This can't cause out-of-order delivery to any single ptype,
5723 * because the 'last ptype' must be constant across the sublist, and all
5724 * other ptypes are handled per-packet.
5726 /* Current (common) ptype of sublist */
5727 struct packet_type *pt_curr = NULL;
5728 /* Current (common) orig_dev of sublist */
5729 struct net_device *od_curr = NULL;
5730 struct list_head sublist;
5731 struct sk_buff *skb, *next;
5733 INIT_LIST_HEAD(&sublist);
5734 list_for_each_entry_safe(skb, next, head, list) {
5735 struct net_device *orig_dev = skb->dev;
5736 struct packet_type *pt_prev = NULL;
5738 skb_list_del_init(skb);
5739 __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
5742 if (pt_curr != pt_prev || od_curr != orig_dev) {
5743 /* dispatch old sublist */
5744 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5745 /* start new sublist */
5746 INIT_LIST_HEAD(&sublist);
5750 list_add_tail(&skb->list, &sublist);
5753 /* dispatch final sublist */
5754 __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
5757 static int __netif_receive_skb(struct sk_buff *skb)
5761 if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
5762 unsigned int noreclaim_flag;
5765 * PFMEMALLOC skbs are special, they should
5766 * - be delivered to SOCK_MEMALLOC sockets only
5767 * - stay away from userspace
5768 * - have bounded memory usage
5770 * Use PF_MEMALLOC as this saves us from propagating the allocation
5771 * context down to all allocation sites.
5773 noreclaim_flag = memalloc_noreclaim_save();
5774 ret = __netif_receive_skb_one_core(skb, true);
5775 memalloc_noreclaim_restore(noreclaim_flag);
5777 ret = __netif_receive_skb_one_core(skb, false);
5782 static void __netif_receive_skb_list(struct list_head *head)
5784 unsigned long noreclaim_flag = 0;
5785 struct sk_buff *skb, *next;
5786 bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
5788 list_for_each_entry_safe(skb, next, head, list) {
5789 if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
5790 struct list_head sublist;
5792 /* Handle the previous sublist */
5793 list_cut_before(&sublist, head, &skb->list);
5794 if (!list_empty(&sublist))
5795 __netif_receive_skb_list_core(&sublist, pfmemalloc);
5796 pfmemalloc = !pfmemalloc;
5797 /* See comments in __netif_receive_skb */
5799 noreclaim_flag = memalloc_noreclaim_save();
5801 memalloc_noreclaim_restore(noreclaim_flag);
5804 /* Handle the remaining sublist */
5805 if (!list_empty(head))
5806 __netif_receive_skb_list_core(head, pfmemalloc);
5807 /* Restore pflags */
5809 memalloc_noreclaim_restore(noreclaim_flag);
5812 static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
5814 struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
5815 struct bpf_prog *new = xdp->prog;
5818 switch (xdp->command) {
5819 case XDP_SETUP_PROG:
5820 rcu_assign_pointer(dev->xdp_prog, new);
5825 static_branch_dec(&generic_xdp_needed_key);
5826 } else if (new && !old) {
5827 static_branch_inc(&generic_xdp_needed_key);
5828 dev_disable_lro(dev);
5829 dev_disable_gro_hw(dev);
5841 static int netif_receive_skb_internal(struct sk_buff *skb)
5845 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
5847 if (skb_defer_rx_timestamp(skb))
5848 return NET_RX_SUCCESS;
5852 if (static_branch_unlikely(&rps_needed)) {
5853 struct rps_dev_flow voidflow, *rflow = &voidflow;
5854 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5857 ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5863 ret = __netif_receive_skb(skb);
5868 void netif_receive_skb_list_internal(struct list_head *head)
5870 struct sk_buff *skb, *next;
5871 struct list_head sublist;
5873 INIT_LIST_HEAD(&sublist);
5874 list_for_each_entry_safe(skb, next, head, list) {
5875 net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue),
5877 skb_list_del_init(skb);
5878 if (!skb_defer_rx_timestamp(skb))
5879 list_add_tail(&skb->list, &sublist);
5881 list_splice_init(&sublist, head);
5885 if (static_branch_unlikely(&rps_needed)) {
5886 list_for_each_entry_safe(skb, next, head, list) {
5887 struct rps_dev_flow voidflow, *rflow = &voidflow;
5888 int cpu = get_rps_cpu(skb->dev, skb, &rflow);
5891 /* Will be handled, remove from list */
5892 skb_list_del_init(skb);
5893 enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
5898 __netif_receive_skb_list(head);
5903 * netif_receive_skb - process receive buffer from network
5904 * @skb: buffer to process
5906 * netif_receive_skb() is the main receive data processing function.
5907 * It always succeeds. The buffer may be dropped during processing
5908 * for congestion control or by the protocol layers.
5910 * This function may only be called from softirq context and interrupts
5911 * should be enabled.
5913 * Return values (usually ignored):
5914 * NET_RX_SUCCESS: no congestion
5915 * NET_RX_DROP: packet was dropped
5917 int netif_receive_skb(struct sk_buff *skb)
5921 trace_netif_receive_skb_entry(skb);
5923 ret = netif_receive_skb_internal(skb);
5924 trace_netif_receive_skb_exit(ret);
5928 EXPORT_SYMBOL(netif_receive_skb);
5931 * netif_receive_skb_list - process many receive buffers from network
5932 * @head: list of skbs to process.
5934 * Since return value of netif_receive_skb() is normally ignored, and
5935 * wouldn't be meaningful for a list, this function returns void.
5937 * This function may only be called from softirq context and interrupts
5938 * should be enabled.
5940 void netif_receive_skb_list(struct list_head *head)
5942 struct sk_buff *skb;
5944 if (list_empty(head))
5946 if (trace_netif_receive_skb_list_entry_enabled()) {
5947 list_for_each_entry(skb, head, list)
5948 trace_netif_receive_skb_list_entry(skb);
5950 netif_receive_skb_list_internal(head);
5951 trace_netif_receive_skb_list_exit(0);
5953 EXPORT_SYMBOL(netif_receive_skb_list);
5955 static DEFINE_PER_CPU(struct work_struct, flush_works);
5957 /* Network device is going away, flush any packets still pending */
5958 static void flush_backlog(struct work_struct *work)
5960 struct sk_buff *skb, *tmp;
5961 struct softnet_data *sd;
5964 sd = this_cpu_ptr(&softnet_data);
5966 backlog_lock_irq_disable(sd);
5967 skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
5968 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5969 __skb_unlink(skb, &sd->input_pkt_queue);
5970 dev_kfree_skb_irq(skb);
5971 rps_input_queue_head_incr(sd);
5974 backlog_unlock_irq_enable(sd);
5976 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
5977 skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
5978 if (skb->dev->reg_state == NETREG_UNREGISTERING) {
5979 __skb_unlink(skb, &sd->process_queue);
5981 rps_input_queue_head_incr(sd);
5984 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
5988 static bool flush_required(int cpu)
5990 #if IS_ENABLED(CONFIG_RPS)
5991 struct softnet_data *sd = &per_cpu(softnet_data, cpu);
5994 backlog_lock_irq_disable(sd);
5996 /* as insertion into process_queue happens with the rps lock held,
5997 * process_queue access may race only with dequeue
5999 do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
6000 !skb_queue_empty_lockless(&sd->process_queue);
6001 backlog_unlock_irq_enable(sd);
6005 /* without RPS we can't safely check input_pkt_queue: during a
6006 * concurrent remote skb_queue_splice() we can detect as empty both
6007 * input_pkt_queue and process_queue even if the latter could end-up
6008 * containing a lot of packets.
6013 static void flush_all_backlogs(void)
6015 static cpumask_t flush_cpus;
6018 /* since we are under rtnl lock protection we can use static data
6019 * for the cpumask and avoid allocating on stack the possibly
6026 cpumask_clear(&flush_cpus);
6027 for_each_online_cpu(cpu) {
6028 if (flush_required(cpu)) {
6029 queue_work_on(cpu, system_highpri_wq,
6030 per_cpu_ptr(&flush_works, cpu));
6031 cpumask_set_cpu(cpu, &flush_cpus);
6035 /* we can have in flight packet[s] on the cpus we are not flushing,
6036 * synchronize_net() in unregister_netdevice_many() will take care of
6039 for_each_cpu(cpu, &flush_cpus)
6040 flush_work(per_cpu_ptr(&flush_works, cpu));
6045 static void net_rps_send_ipi(struct softnet_data *remsd)
6049 struct softnet_data *next = remsd->rps_ipi_next;
6051 if (cpu_online(remsd->cpu))
6052 smp_call_function_single_async(remsd->cpu, &remsd->csd);
6059 * net_rps_action_and_irq_enable sends any pending IPI's for rps.
6060 * Note: called with local irq disabled, but exits with local irq enabled.
6062 static void net_rps_action_and_irq_enable(struct softnet_data *sd)
6065 struct softnet_data *remsd = sd->rps_ipi_list;
6067 if (!use_backlog_threads() && remsd) {
6068 sd->rps_ipi_list = NULL;
6072 /* Send pending IPI's to kick RPS processing on remote cpus. */
6073 net_rps_send_ipi(remsd);
6079 static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
6082 return !use_backlog_threads() && sd->rps_ipi_list;
6088 static int process_backlog(struct napi_struct *napi, int quota)
6090 struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
6094 /* Check if we have pending ipi, its better to send them now,
6095 * not waiting net_rx_action() end.
6097 if (sd_has_rps_ipi_waiting(sd)) {
6098 local_irq_disable();
6099 net_rps_action_and_irq_enable(sd);
6102 napi->weight = READ_ONCE(net_hotdata.dev_rx_weight);
6104 struct sk_buff *skb;
6106 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6107 while ((skb = __skb_dequeue(&sd->process_queue))) {
6108 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6110 __netif_receive_skb(skb);
6112 if (++work >= quota) {
6113 rps_input_queue_head_add(sd, work);
6117 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6119 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6121 backlog_lock_irq_disable(sd);
6122 if (skb_queue_empty(&sd->input_pkt_queue)) {
6124 * Inline a custom version of __napi_complete().
6125 * only current cpu owns and manipulates this napi,
6126 * and NAPI_STATE_SCHED is the only possible flag set
6128 * We can use a plain write instead of clear_bit(),
6129 * and we dont need an smp_mb() memory barrier.
6131 napi->state &= NAPIF_STATE_THREADED;
6134 local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
6135 skb_queue_splice_tail_init(&sd->input_pkt_queue,
6136 &sd->process_queue);
6137 local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
6139 backlog_unlock_irq_enable(sd);
6143 rps_input_queue_head_add(sd, work);
6148 * __napi_schedule - schedule for receive
6149 * @n: entry to schedule
6151 * The entry's receive function will be scheduled to run.
6152 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
6154 void __napi_schedule(struct napi_struct *n)
6156 unsigned long flags;
6158 local_irq_save(flags);
6159 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6160 local_irq_restore(flags);
6162 EXPORT_SYMBOL(__napi_schedule);
6165 * napi_schedule_prep - check if napi can be scheduled
6168 * Test if NAPI routine is already running, and if not mark
6169 * it as running. This is used as a condition variable to
6170 * insure only one NAPI poll instance runs. We also make
6171 * sure there is no pending NAPI disable.
6173 bool napi_schedule_prep(struct napi_struct *n)
6175 unsigned long new, val = READ_ONCE(n->state);
6178 if (unlikely(val & NAPIF_STATE_DISABLE))
6180 new = val | NAPIF_STATE_SCHED;
6182 /* Sets STATE_MISSED bit if STATE_SCHED was already set
6183 * This was suggested by Alexander Duyck, as compiler
6184 * emits better code than :
6185 * if (val & NAPIF_STATE_SCHED)
6186 * new |= NAPIF_STATE_MISSED;
6188 new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
6190 } while (!try_cmpxchg(&n->state, &val, new));
6192 return !(val & NAPIF_STATE_SCHED);
6194 EXPORT_SYMBOL(napi_schedule_prep);
6197 * __napi_schedule_irqoff - schedule for receive
6198 * @n: entry to schedule
6200 * Variant of __napi_schedule() assuming hard irqs are masked.
6202 * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
6203 * because the interrupt disabled assumption might not be true
6204 * due to force-threaded interrupts and spinlock substitution.
6206 void __napi_schedule_irqoff(struct napi_struct *n)
6208 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6209 ____napi_schedule(this_cpu_ptr(&softnet_data), n);
6213 EXPORT_SYMBOL(__napi_schedule_irqoff);
6215 bool napi_complete_done(struct napi_struct *n, int work_done)
6217 unsigned long flags, val, new, timeout = 0;
6221 * 1) Don't let napi dequeue from the cpu poll list
6222 * just in case its running on a different cpu.
6223 * 2) If we are busy polling, do nothing here, we have
6224 * the guarantee we will be called later.
6226 if (unlikely(n->state & (NAPIF_STATE_NPSVC |
6227 NAPIF_STATE_IN_BUSY_POLL)))
6232 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6233 n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
6235 if (n->defer_hard_irqs_count > 0) {
6236 n->defer_hard_irqs_count--;
6237 timeout = READ_ONCE(n->dev->gro_flush_timeout);
6241 if (n->gro_bitmask) {
6242 /* When the NAPI instance uses a timeout and keeps postponing
6243 * it, we need to bound somehow the time packets are kept in
6246 napi_gro_flush(n, !!timeout);
6251 if (unlikely(!list_empty(&n->poll_list))) {
6252 /* If n->poll_list is not empty, we need to mask irqs */
6253 local_irq_save(flags);
6254 list_del_init(&n->poll_list);
6255 local_irq_restore(flags);
6257 WRITE_ONCE(n->list_owner, -1);
6259 val = READ_ONCE(n->state);
6261 WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
6263 new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
6264 NAPIF_STATE_SCHED_THREADED |
6265 NAPIF_STATE_PREFER_BUSY_POLL);
6267 /* If STATE_MISSED was set, leave STATE_SCHED set,
6268 * because we will call napi->poll() one more time.
6269 * This C code was suggested by Alexander Duyck to help gcc.
6271 new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
6273 } while (!try_cmpxchg(&n->state, &val, new));
6275 if (unlikely(val & NAPIF_STATE_MISSED)) {
6281 hrtimer_start(&n->timer, ns_to_ktime(timeout),
6282 HRTIMER_MODE_REL_PINNED);
6285 EXPORT_SYMBOL(napi_complete_done);
6287 /* must be called under rcu_read_lock(), as we dont take a reference */
6288 struct napi_struct *napi_by_id(unsigned int napi_id)
6290 unsigned int hash = napi_id % HASH_SIZE(napi_hash);
6291 struct napi_struct *napi;
6293 hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
6294 if (napi->napi_id == napi_id)
6300 static void skb_defer_free_flush(struct softnet_data *sd)
6302 struct sk_buff *skb, *next;
6304 /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
6305 if (!READ_ONCE(sd->defer_list))
6308 spin_lock(&sd->defer_lock);
6309 skb = sd->defer_list;
6310 sd->defer_list = NULL;
6311 sd->defer_count = 0;
6312 spin_unlock(&sd->defer_lock);
6314 while (skb != NULL) {
6316 napi_consume_skb(skb, 1);
6321 #if defined(CONFIG_NET_RX_BUSY_POLL)
6323 static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
6325 if (!skip_schedule) {
6326 gro_normal_list(napi);
6327 __napi_schedule(napi);
6331 if (napi->gro_bitmask) {
6332 /* flush too old packets
6333 * If HZ < 1000, flush all packets.
6335 napi_gro_flush(napi, HZ >= 1000);
6338 gro_normal_list(napi);
6339 clear_bit(NAPI_STATE_SCHED, &napi->state);
6343 NAPI_F_PREFER_BUSY_POLL = 1,
6344 NAPI_F_END_ON_RESCHED = 2,
6347 static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock,
6348 unsigned flags, u16 budget)
6350 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6351 bool skip_schedule = false;
6352 unsigned long timeout;
6355 /* Busy polling means there is a high chance device driver hard irq
6356 * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
6357 * set in napi_schedule_prep().
6358 * Since we are about to call napi->poll() once more, we can safely
6359 * clear NAPI_STATE_MISSED.
6361 * Note: x86 could use a single "lock and ..." instruction
6362 * to perform these two clear_bit()
6364 clear_bit(NAPI_STATE_MISSED, &napi->state);
6365 clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
6368 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6370 if (flags & NAPI_F_PREFER_BUSY_POLL) {
6371 napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
6372 timeout = READ_ONCE(napi->dev->gro_flush_timeout);
6373 if (napi->defer_hard_irqs_count && timeout) {
6374 hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
6375 skip_schedule = true;
6379 /* All we really want here is to re-enable device interrupts.
6380 * Ideally, a new ndo_busy_poll_stop() could avoid another round.
6382 rc = napi->poll(napi, budget);
6383 /* We can't gro_normal_list() here, because napi->poll() might have
6384 * rearmed the napi (napi_complete_done()) in which case it could
6385 * already be running on another CPU.
6387 trace_napi_poll(napi, rc, budget);
6388 netpoll_poll_unlock(have_poll_lock);
6390 __busy_poll_stop(napi, skip_schedule);
6391 bpf_net_ctx_clear(bpf_net_ctx);
6395 static void __napi_busy_loop(unsigned int napi_id,
6396 bool (*loop_end)(void *, unsigned long),
6397 void *loop_end_arg, unsigned flags, u16 budget)
6399 unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
6400 int (*napi_poll)(struct napi_struct *napi, int budget);
6401 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6402 void *have_poll_lock = NULL;
6403 struct napi_struct *napi;
6405 WARN_ON_ONCE(!rcu_read_lock_held());
6410 napi = napi_by_id(napi_id);
6414 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6420 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6422 unsigned long val = READ_ONCE(napi->state);
6424 /* If multiple threads are competing for this napi,
6425 * we avoid dirtying napi->state as much as we can.
6427 if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
6428 NAPIF_STATE_IN_BUSY_POLL)) {
6429 if (flags & NAPI_F_PREFER_BUSY_POLL)
6430 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6433 if (cmpxchg(&napi->state, val,
6434 val | NAPIF_STATE_IN_BUSY_POLL |
6435 NAPIF_STATE_SCHED) != val) {
6436 if (flags & NAPI_F_PREFER_BUSY_POLL)
6437 set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6440 have_poll_lock = netpoll_poll_lock(napi);
6441 napi_poll = napi->poll;
6443 work = napi_poll(napi, budget);
6444 trace_napi_poll(napi, work, budget);
6445 gro_normal_list(napi);
6448 __NET_ADD_STATS(dev_net(napi->dev),
6449 LINUX_MIB_BUSYPOLLRXPACKETS, work);
6450 skb_defer_free_flush(this_cpu_ptr(&softnet_data));
6451 bpf_net_ctx_clear(bpf_net_ctx);
6454 if (!loop_end || loop_end(loop_end_arg, start_time))
6457 if (unlikely(need_resched())) {
6458 if (flags & NAPI_F_END_ON_RESCHED)
6461 busy_poll_stop(napi, have_poll_lock, flags, budget);
6462 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6467 if (loop_end(loop_end_arg, start_time))
6474 busy_poll_stop(napi, have_poll_lock, flags, budget);
6475 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6479 void napi_busy_loop_rcu(unsigned int napi_id,
6480 bool (*loop_end)(void *, unsigned long),
6481 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6483 unsigned flags = NAPI_F_END_ON_RESCHED;
6485 if (prefer_busy_poll)
6486 flags |= NAPI_F_PREFER_BUSY_POLL;
6488 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
6491 void napi_busy_loop(unsigned int napi_id,
6492 bool (*loop_end)(void *, unsigned long),
6493 void *loop_end_arg, bool prefer_busy_poll, u16 budget)
6495 unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0;
6498 __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
6501 EXPORT_SYMBOL(napi_busy_loop);
6503 #endif /* CONFIG_NET_RX_BUSY_POLL */
6505 static void napi_hash_add(struct napi_struct *napi)
6507 if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
6510 spin_lock(&napi_hash_lock);
6512 /* 0..NR_CPUS range is reserved for sender_cpu use */
6514 if (unlikely(++napi_gen_id < MIN_NAPI_ID))
6515 napi_gen_id = MIN_NAPI_ID;
6516 } while (napi_by_id(napi_gen_id));
6517 napi->napi_id = napi_gen_id;
6519 hlist_add_head_rcu(&napi->napi_hash_node,
6520 &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
6522 spin_unlock(&napi_hash_lock);
6525 /* Warning : caller is responsible to make sure rcu grace period
6526 * is respected before freeing memory containing @napi
6528 static void napi_hash_del(struct napi_struct *napi)
6530 spin_lock(&napi_hash_lock);
6532 hlist_del_init_rcu(&napi->napi_hash_node);
6534 spin_unlock(&napi_hash_lock);
6537 static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
6539 struct napi_struct *napi;
6541 napi = container_of(timer, struct napi_struct, timer);
6543 /* Note : we use a relaxed variant of napi_schedule_prep() not setting
6544 * NAPI_STATE_MISSED, since we do not react to a device IRQ.
6546 if (!napi_disable_pending(napi) &&
6547 !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
6548 clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
6549 __napi_schedule_irqoff(napi);
6552 return HRTIMER_NORESTART;
6555 static void init_gro_hash(struct napi_struct *napi)
6559 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6560 INIT_LIST_HEAD(&napi->gro_hash[i].list);
6561 napi->gro_hash[i].count = 0;
6563 napi->gro_bitmask = 0;
6566 int dev_set_threaded(struct net_device *dev, bool threaded)
6568 struct napi_struct *napi;
6571 if (dev->threaded == threaded)
6575 list_for_each_entry(napi, &dev->napi_list, dev_list) {
6576 if (!napi->thread) {
6577 err = napi_kthread_create(napi);
6586 WRITE_ONCE(dev->threaded, threaded);
6588 /* Make sure kthread is created before THREADED bit
6591 smp_mb__before_atomic();
6593 /* Setting/unsetting threaded mode on a napi might not immediately
6594 * take effect, if the current napi instance is actively being
6595 * polled. In this case, the switch between threaded mode and
6596 * softirq mode will happen in the next round of napi_schedule().
6597 * This should not cause hiccups/stalls to the live traffic.
6599 list_for_each_entry(napi, &dev->napi_list, dev_list)
6600 assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
6604 EXPORT_SYMBOL(dev_set_threaded);
6607 * netif_queue_set_napi - Associate queue with the napi
6608 * @dev: device to which NAPI and queue belong
6609 * @queue_index: Index of queue
6610 * @type: queue type as RX or TX
6611 * @napi: NAPI context, pass NULL to clear previously set NAPI
6613 * Set queue with its corresponding napi context. This should be done after
6614 * registering the NAPI handler for the queue-vector and the queues have been
6615 * mapped to the corresponding interrupt vector.
6617 void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
6618 enum netdev_queue_type type, struct napi_struct *napi)
6620 struct netdev_rx_queue *rxq;
6621 struct netdev_queue *txq;
6623 if (WARN_ON_ONCE(napi && !napi->dev))
6625 if (dev->reg_state >= NETREG_REGISTERED)
6629 case NETDEV_QUEUE_TYPE_RX:
6630 rxq = __netif_get_rx_queue(dev, queue_index);
6633 case NETDEV_QUEUE_TYPE_TX:
6634 txq = netdev_get_tx_queue(dev, queue_index);
6641 EXPORT_SYMBOL(netif_queue_set_napi);
6643 void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
6644 int (*poll)(struct napi_struct *, int), int weight)
6646 if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
6649 INIT_LIST_HEAD(&napi->poll_list);
6650 INIT_HLIST_NODE(&napi->napi_hash_node);
6651 hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6652 napi->timer.function = napi_watchdog;
6653 init_gro_hash(napi);
6655 INIT_LIST_HEAD(&napi->rx_list);
6658 if (weight > NAPI_POLL_WEIGHT)
6659 netdev_err_once(dev, "%s() called with weight %d\n", __func__,
6661 napi->weight = weight;
6663 #ifdef CONFIG_NETPOLL
6664 napi->poll_owner = -1;
6666 napi->list_owner = -1;
6667 set_bit(NAPI_STATE_SCHED, &napi->state);
6668 set_bit(NAPI_STATE_NPSVC, &napi->state);
6669 list_add_rcu(&napi->dev_list, &dev->napi_list);
6670 napi_hash_add(napi);
6671 napi_get_frags_check(napi);
6672 /* Create kthread for this napi if dev->threaded is set.
6673 * Clear dev->threaded if kthread creation failed so that
6674 * threaded mode will not be enabled in napi_enable().
6676 if (dev->threaded && napi_kthread_create(napi))
6677 dev->threaded = false;
6678 netif_napi_set_irq(napi, -1);
6680 EXPORT_SYMBOL(netif_napi_add_weight);
6682 void napi_disable(struct napi_struct *n)
6684 unsigned long val, new;
6687 set_bit(NAPI_STATE_DISABLE, &n->state);
6689 val = READ_ONCE(n->state);
6691 while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
6692 usleep_range(20, 200);
6693 val = READ_ONCE(n->state);
6696 new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
6697 new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
6698 } while (!try_cmpxchg(&n->state, &val, new));
6700 hrtimer_cancel(&n->timer);
6702 clear_bit(NAPI_STATE_DISABLE, &n->state);
6704 EXPORT_SYMBOL(napi_disable);
6707 * napi_enable - enable NAPI scheduling
6710 * Resume NAPI from being scheduled on this context.
6711 * Must be paired with napi_disable.
6713 void napi_enable(struct napi_struct *n)
6715 unsigned long new, val = READ_ONCE(n->state);
6718 BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
6720 new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
6721 if (n->dev->threaded && n->thread)
6722 new |= NAPIF_STATE_THREADED;
6723 } while (!try_cmpxchg(&n->state, &val, new));
6725 EXPORT_SYMBOL(napi_enable);
6727 static void flush_gro_hash(struct napi_struct *napi)
6731 for (i = 0; i < GRO_HASH_BUCKETS; i++) {
6732 struct sk_buff *skb, *n;
6734 list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
6736 napi->gro_hash[i].count = 0;
6740 /* Must be called in process context */
6741 void __netif_napi_del(struct napi_struct *napi)
6743 if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
6746 napi_hash_del(napi);
6747 list_del_rcu(&napi->dev_list);
6748 napi_free_frags(napi);
6750 flush_gro_hash(napi);
6751 napi->gro_bitmask = 0;
6754 kthread_stop(napi->thread);
6755 napi->thread = NULL;
6758 EXPORT_SYMBOL(__netif_napi_del);
6760 static int __napi_poll(struct napi_struct *n, bool *repoll)
6766 /* This NAPI_STATE_SCHED test is for avoiding a race
6767 * with netpoll's poll_napi(). Only the entity which
6768 * obtains the lock and sees NAPI_STATE_SCHED set will
6769 * actually make the ->poll() call. Therefore we avoid
6770 * accidentally calling ->poll() when NAPI is not scheduled.
6773 if (napi_is_scheduled(n)) {
6774 work = n->poll(n, weight);
6775 trace_napi_poll(n, work, weight);
6777 xdp_do_check_flushed(n);
6780 if (unlikely(work > weight))
6781 netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
6782 n->poll, work, weight);
6784 if (likely(work < weight))
6787 /* Drivers must not modify the NAPI state if they
6788 * consume the entire weight. In such cases this code
6789 * still "owns" the NAPI instance and therefore can
6790 * move the instance around on the list at-will.
6792 if (unlikely(napi_disable_pending(n))) {
6797 /* The NAPI context has more processing work, but busy-polling
6798 * is preferred. Exit early.
6800 if (napi_prefer_busy_poll(n)) {
6801 if (napi_complete_done(n, work)) {
6802 /* If timeout is not set, we need to make sure
6803 * that the NAPI is re-scheduled.
6810 if (n->gro_bitmask) {
6811 /* flush too old packets
6812 * If HZ < 1000, flush all packets.
6814 napi_gro_flush(n, HZ >= 1000);
6819 /* Some drivers may have called napi_schedule
6820 * prior to exhausting their budget.
6822 if (unlikely(!list_empty(&n->poll_list))) {
6823 pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
6824 n->dev ? n->dev->name : "backlog");
6833 static int napi_poll(struct napi_struct *n, struct list_head *repoll)
6835 bool do_repoll = false;
6839 list_del_init(&n->poll_list);
6841 have = netpoll_poll_lock(n);
6843 work = __napi_poll(n, &do_repoll);
6846 list_add_tail(&n->poll_list, repoll);
6848 netpoll_poll_unlock(have);
6853 static int napi_thread_wait(struct napi_struct *napi)
6855 set_current_state(TASK_INTERRUPTIBLE);
6857 while (!kthread_should_stop()) {
6858 /* Testing SCHED_THREADED bit here to make sure the current
6859 * kthread owns this napi and could poll on this napi.
6860 * Testing SCHED bit is not enough because SCHED bit might be
6861 * set by some other busy poll thread or by napi_disable().
6863 if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) {
6864 WARN_ON(!list_empty(&napi->poll_list));
6865 __set_current_state(TASK_RUNNING);
6870 set_current_state(TASK_INTERRUPTIBLE);
6872 __set_current_state(TASK_RUNNING);
6877 static void napi_threaded_poll_loop(struct napi_struct *napi)
6879 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6880 struct softnet_data *sd;
6881 unsigned long last_qs = jiffies;
6884 bool repoll = false;
6888 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6890 sd = this_cpu_ptr(&softnet_data);
6891 sd->in_napi_threaded_poll = true;
6893 have = netpoll_poll_lock(napi);
6894 __napi_poll(napi, &repoll);
6895 netpoll_poll_unlock(have);
6897 sd->in_napi_threaded_poll = false;
6900 if (sd_has_rps_ipi_waiting(sd)) {
6901 local_irq_disable();
6902 net_rps_action_and_irq_enable(sd);
6904 skb_defer_free_flush(sd);
6905 bpf_net_ctx_clear(bpf_net_ctx);
6911 rcu_softirq_qs_periodic(last_qs);
6916 static int napi_threaded_poll(void *data)
6918 struct napi_struct *napi = data;
6920 while (!napi_thread_wait(napi))
6921 napi_threaded_poll_loop(napi);
6926 static __latent_entropy void net_rx_action(struct softirq_action *h)
6928 struct softnet_data *sd = this_cpu_ptr(&softnet_data);
6929 unsigned long time_limit = jiffies +
6930 usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs));
6931 struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
6932 int budget = READ_ONCE(net_hotdata.netdev_budget);
6936 bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
6938 sd->in_net_rx_action = true;
6939 local_irq_disable();
6940 list_splice_init(&sd->poll_list, &list);
6944 struct napi_struct *n;
6946 skb_defer_free_flush(sd);
6948 if (list_empty(&list)) {
6949 if (list_empty(&repoll)) {
6950 sd->in_net_rx_action = false;
6952 /* We need to check if ____napi_schedule()
6953 * had refilled poll_list while
6954 * sd->in_net_rx_action was true.
6956 if (!list_empty(&sd->poll_list))
6958 if (!sd_has_rps_ipi_waiting(sd))
6964 n = list_first_entry(&list, struct napi_struct, poll_list);
6965 budget -= napi_poll(n, &repoll);
6967 /* If softirq window is exhausted then punt.
6968 * Allow this to run for 2 jiffies since which will allow
6969 * an average latency of 1.5/HZ.
6971 if (unlikely(budget <= 0 ||
6972 time_after_eq(jiffies, time_limit))) {
6978 local_irq_disable();
6980 list_splice_tail_init(&sd->poll_list, &list);
6981 list_splice_tail(&repoll, &list);
6982 list_splice(&list, &sd->poll_list);
6983 if (!list_empty(&sd->poll_list))
6984 __raise_softirq_irqoff(NET_RX_SOFTIRQ);
6986 sd->in_net_rx_action = false;
6988 net_rps_action_and_irq_enable(sd);
6990 bpf_net_ctx_clear(bpf_net_ctx);
6993 struct netdev_adjacent {
6994 struct net_device *dev;
6995 netdevice_tracker dev_tracker;
6997 /* upper master flag, there can only be one master device per list */
7000 /* lookup ignore flag */
7003 /* counter for the number of times this device was added to us */
7006 /* private field for the users */
7009 struct list_head list;
7010 struct rcu_head rcu;
7013 static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
7014 struct list_head *adj_list)
7016 struct netdev_adjacent *adj;
7018 list_for_each_entry(adj, adj_list, list) {
7019 if (adj->dev == adj_dev)
7025 static int ____netdev_has_upper_dev(struct net_device *upper_dev,
7026 struct netdev_nested_priv *priv)
7028 struct net_device *dev = (struct net_device *)priv->data;
7030 return upper_dev == dev;
7034 * netdev_has_upper_dev - Check if device is linked to an upper device
7036 * @upper_dev: upper device to check
7038 * Find out if a device is linked to specified upper device and return true
7039 * in case it is. Note that this checks only immediate upper device,
7040 * not through a complete stack of devices. The caller must hold the RTNL lock.
7042 bool netdev_has_upper_dev(struct net_device *dev,
7043 struct net_device *upper_dev)
7045 struct netdev_nested_priv priv = {
7046 .data = (void *)upper_dev,
7051 return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7054 EXPORT_SYMBOL(netdev_has_upper_dev);
7057 * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
7059 * @upper_dev: upper device to check
7061 * Find out if a device is linked to specified upper device and return true
7062 * in case it is. Note that this checks the entire upper device chain.
7063 * The caller must hold rcu lock.
7066 bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
7067 struct net_device *upper_dev)
7069 struct netdev_nested_priv priv = {
7070 .data = (void *)upper_dev,
7073 return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
7076 EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
7079 * netdev_has_any_upper_dev - Check if device is linked to some device
7082 * Find out if a device is linked to an upper device and return true in case
7083 * it is. The caller must hold the RTNL lock.
7085 bool netdev_has_any_upper_dev(struct net_device *dev)
7089 return !list_empty(&dev->adj_list.upper);
7091 EXPORT_SYMBOL(netdev_has_any_upper_dev);
7094 * netdev_master_upper_dev_get - Get master upper device
7097 * Find a master upper device and return pointer to it or NULL in case
7098 * it's not there. The caller must hold the RTNL lock.
7100 struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
7102 struct netdev_adjacent *upper;
7106 if (list_empty(&dev->adj_list.upper))
7109 upper = list_first_entry(&dev->adj_list.upper,
7110 struct netdev_adjacent, list);
7111 if (likely(upper->master))
7115 EXPORT_SYMBOL(netdev_master_upper_dev_get);
7117 static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
7119 struct netdev_adjacent *upper;
7123 if (list_empty(&dev->adj_list.upper))
7126 upper = list_first_entry(&dev->adj_list.upper,
7127 struct netdev_adjacent, list);
7128 if (likely(upper->master) && !upper->ignore)
7134 * netdev_has_any_lower_dev - Check if device is linked to some device
7137 * Find out if a device is linked to a lower device and return true in case
7138 * it is. The caller must hold the RTNL lock.
7140 static bool netdev_has_any_lower_dev(struct net_device *dev)
7144 return !list_empty(&dev->adj_list.lower);
7147 void *netdev_adjacent_get_private(struct list_head *adj_list)
7149 struct netdev_adjacent *adj;
7151 adj = list_entry(adj_list, struct netdev_adjacent, list);
7153 return adj->private;
7155 EXPORT_SYMBOL(netdev_adjacent_get_private);
7158 * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
7160 * @iter: list_head ** of the current position
7162 * Gets the next device from the dev's upper list, starting from iter
7163 * position. The caller must hold RCU read lock.
7165 struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
7166 struct list_head **iter)
7168 struct netdev_adjacent *upper;
7170 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7172 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7174 if (&upper->list == &dev->adj_list.upper)
7177 *iter = &upper->list;
7181 EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
7183 static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
7184 struct list_head **iter,
7187 struct netdev_adjacent *upper;
7189 upper = list_entry((*iter)->next, struct netdev_adjacent, list);
7191 if (&upper->list == &dev->adj_list.upper)
7194 *iter = &upper->list;
7195 *ignore = upper->ignore;
7200 static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
7201 struct list_head **iter)
7203 struct netdev_adjacent *upper;
7205 WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
7207 upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7209 if (&upper->list == &dev->adj_list.upper)
7212 *iter = &upper->list;
7217 static int __netdev_walk_all_upper_dev(struct net_device *dev,
7218 int (*fn)(struct net_device *dev,
7219 struct netdev_nested_priv *priv),
7220 struct netdev_nested_priv *priv)
7222 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7223 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7228 iter = &dev->adj_list.upper;
7232 ret = fn(now, priv);
7239 udev = __netdev_next_upper_dev(now, &iter, &ignore);
7246 niter = &udev->adj_list.upper;
7247 dev_stack[cur] = now;
7248 iter_stack[cur++] = iter;
7255 next = dev_stack[--cur];
7256 niter = iter_stack[cur];
7266 int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
7267 int (*fn)(struct net_device *dev,
7268 struct netdev_nested_priv *priv),
7269 struct netdev_nested_priv *priv)
7271 struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7272 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7276 iter = &dev->adj_list.upper;
7280 ret = fn(now, priv);
7287 udev = netdev_next_upper_dev_rcu(now, &iter);
7292 niter = &udev->adj_list.upper;
7293 dev_stack[cur] = now;
7294 iter_stack[cur++] = iter;
7301 next = dev_stack[--cur];
7302 niter = iter_stack[cur];
7311 EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
7313 static bool __netdev_has_upper_dev(struct net_device *dev,
7314 struct net_device *upper_dev)
7316 struct netdev_nested_priv priv = {
7318 .data = (void *)upper_dev,
7323 return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
7328 * netdev_lower_get_next_private - Get the next ->private from the
7329 * lower neighbour list
7331 * @iter: list_head ** of the current position
7333 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7334 * list, starting from iter position. The caller must hold either hold the
7335 * RTNL lock or its own locking that guarantees that the neighbour lower
7336 * list will remain unchanged.
7338 void *netdev_lower_get_next_private(struct net_device *dev,
7339 struct list_head **iter)
7341 struct netdev_adjacent *lower;
7343 lower = list_entry(*iter, struct netdev_adjacent, list);
7345 if (&lower->list == &dev->adj_list.lower)
7348 *iter = lower->list.next;
7350 return lower->private;
7352 EXPORT_SYMBOL(netdev_lower_get_next_private);
7355 * netdev_lower_get_next_private_rcu - Get the next ->private from the
7356 * lower neighbour list, RCU
7359 * @iter: list_head ** of the current position
7361 * Gets the next netdev_adjacent->private from the dev's lower neighbour
7362 * list, starting from iter position. The caller must hold RCU read lock.
7364 void *netdev_lower_get_next_private_rcu(struct net_device *dev,
7365 struct list_head **iter)
7367 struct netdev_adjacent *lower;
7369 WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
7371 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7373 if (&lower->list == &dev->adj_list.lower)
7376 *iter = &lower->list;
7378 return lower->private;
7380 EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
7383 * netdev_lower_get_next - Get the next device from the lower neighbour
7386 * @iter: list_head ** of the current position
7388 * Gets the next netdev_adjacent from the dev's lower neighbour
7389 * list, starting from iter position. The caller must hold RTNL lock or
7390 * its own locking that guarantees that the neighbour lower
7391 * list will remain unchanged.
7393 void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
7395 struct netdev_adjacent *lower;
7397 lower = list_entry(*iter, struct netdev_adjacent, list);
7399 if (&lower->list == &dev->adj_list.lower)
7402 *iter = lower->list.next;
7406 EXPORT_SYMBOL(netdev_lower_get_next);
7408 static struct net_device *netdev_next_lower_dev(struct net_device *dev,
7409 struct list_head **iter)
7411 struct netdev_adjacent *lower;
7413 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7415 if (&lower->list == &dev->adj_list.lower)
7418 *iter = &lower->list;
7423 static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
7424 struct list_head **iter,
7427 struct netdev_adjacent *lower;
7429 lower = list_entry((*iter)->next, struct netdev_adjacent, list);
7431 if (&lower->list == &dev->adj_list.lower)
7434 *iter = &lower->list;
7435 *ignore = lower->ignore;
7440 int netdev_walk_all_lower_dev(struct net_device *dev,
7441 int (*fn)(struct net_device *dev,
7442 struct netdev_nested_priv *priv),
7443 struct netdev_nested_priv *priv)
7445 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7446 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7450 iter = &dev->adj_list.lower;
7454 ret = fn(now, priv);
7461 ldev = netdev_next_lower_dev(now, &iter);
7466 niter = &ldev->adj_list.lower;
7467 dev_stack[cur] = now;
7468 iter_stack[cur++] = iter;
7475 next = dev_stack[--cur];
7476 niter = iter_stack[cur];
7485 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
7487 static int __netdev_walk_all_lower_dev(struct net_device *dev,
7488 int (*fn)(struct net_device *dev,
7489 struct netdev_nested_priv *priv),
7490 struct netdev_nested_priv *priv)
7492 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7493 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7498 iter = &dev->adj_list.lower;
7502 ret = fn(now, priv);
7509 ldev = __netdev_next_lower_dev(now, &iter, &ignore);
7516 niter = &ldev->adj_list.lower;
7517 dev_stack[cur] = now;
7518 iter_stack[cur++] = iter;
7525 next = dev_stack[--cur];
7526 niter = iter_stack[cur];
7536 struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
7537 struct list_head **iter)
7539 struct netdev_adjacent *lower;
7541 lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
7542 if (&lower->list == &dev->adj_list.lower)
7545 *iter = &lower->list;
7549 EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
7551 static u8 __netdev_upper_depth(struct net_device *dev)
7553 struct net_device *udev;
7554 struct list_head *iter;
7558 for (iter = &dev->adj_list.upper,
7559 udev = __netdev_next_upper_dev(dev, &iter, &ignore);
7561 udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
7564 if (max_depth < udev->upper_level)
7565 max_depth = udev->upper_level;
7571 static u8 __netdev_lower_depth(struct net_device *dev)
7573 struct net_device *ldev;
7574 struct list_head *iter;
7578 for (iter = &dev->adj_list.lower,
7579 ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
7581 ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
7584 if (max_depth < ldev->lower_level)
7585 max_depth = ldev->lower_level;
7591 static int __netdev_update_upper_level(struct net_device *dev,
7592 struct netdev_nested_priv *__unused)
7594 dev->upper_level = __netdev_upper_depth(dev) + 1;
7598 #ifdef CONFIG_LOCKDEP
7599 static LIST_HEAD(net_unlink_list);
7601 static void net_unlink_todo(struct net_device *dev)
7603 if (list_empty(&dev->unlink_list))
7604 list_add_tail(&dev->unlink_list, &net_unlink_list);
7608 static int __netdev_update_lower_level(struct net_device *dev,
7609 struct netdev_nested_priv *priv)
7611 dev->lower_level = __netdev_lower_depth(dev) + 1;
7613 #ifdef CONFIG_LOCKDEP
7617 if (priv->flags & NESTED_SYNC_IMM)
7618 dev->nested_level = dev->lower_level - 1;
7619 if (priv->flags & NESTED_SYNC_TODO)
7620 net_unlink_todo(dev);
7625 int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
7626 int (*fn)(struct net_device *dev,
7627 struct netdev_nested_priv *priv),
7628 struct netdev_nested_priv *priv)
7630 struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
7631 struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
7635 iter = &dev->adj_list.lower;
7639 ret = fn(now, priv);
7646 ldev = netdev_next_lower_dev_rcu(now, &iter);
7651 niter = &ldev->adj_list.lower;
7652 dev_stack[cur] = now;
7653 iter_stack[cur++] = iter;
7660 next = dev_stack[--cur];
7661 niter = iter_stack[cur];
7670 EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
7673 * netdev_lower_get_first_private_rcu - Get the first ->private from the
7674 * lower neighbour list, RCU
7678 * Gets the first netdev_adjacent->private from the dev's lower neighbour
7679 * list. The caller must hold RCU read lock.
7681 void *netdev_lower_get_first_private_rcu(struct net_device *dev)
7683 struct netdev_adjacent *lower;
7685 lower = list_first_or_null_rcu(&dev->adj_list.lower,
7686 struct netdev_adjacent, list);
7688 return lower->private;
7691 EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
7694 * netdev_master_upper_dev_get_rcu - Get master upper device
7697 * Find a master upper device and return pointer to it or NULL in case
7698 * it's not there. The caller must hold the RCU read lock.
7700 struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
7702 struct netdev_adjacent *upper;
7704 upper = list_first_or_null_rcu(&dev->adj_list.upper,
7705 struct netdev_adjacent, list);
7706 if (upper && likely(upper->master))
7710 EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
7712 static int netdev_adjacent_sysfs_add(struct net_device *dev,
7713 struct net_device *adj_dev,
7714 struct list_head *dev_list)
7716 char linkname[IFNAMSIZ+7];
7718 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7719 "upper_%s" : "lower_%s", adj_dev->name);
7720 return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
7723 static void netdev_adjacent_sysfs_del(struct net_device *dev,
7725 struct list_head *dev_list)
7727 char linkname[IFNAMSIZ+7];
7729 sprintf(linkname, dev_list == &dev->adj_list.upper ?
7730 "upper_%s" : "lower_%s", name);
7731 sysfs_remove_link(&(dev->dev.kobj), linkname);
7734 static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
7735 struct net_device *adj_dev,
7736 struct list_head *dev_list)
7738 return (dev_list == &dev->adj_list.upper ||
7739 dev_list == &dev->adj_list.lower) &&
7740 net_eq(dev_net(dev), dev_net(adj_dev));
7743 static int __netdev_adjacent_dev_insert(struct net_device *dev,
7744 struct net_device *adj_dev,
7745 struct list_head *dev_list,
7746 void *private, bool master)
7748 struct netdev_adjacent *adj;
7751 adj = __netdev_find_adj(adj_dev, dev_list);
7755 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
7756 dev->name, adj_dev->name, adj->ref_nr);
7761 adj = kmalloc(sizeof(*adj), GFP_KERNEL);
7766 adj->master = master;
7768 adj->private = private;
7769 adj->ignore = false;
7770 netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
7772 pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
7773 dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
7775 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
7776 ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
7781 /* Ensure that master link is always the first item in list. */
7783 ret = sysfs_create_link(&(dev->dev.kobj),
7784 &(adj_dev->dev.kobj), "master");
7786 goto remove_symlinks;
7788 list_add_rcu(&adj->list, dev_list);
7790 list_add_tail_rcu(&adj->list, dev_list);
7796 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7797 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7799 netdev_put(adj_dev, &adj->dev_tracker);
7805 static void __netdev_adjacent_dev_remove(struct net_device *dev,
7806 struct net_device *adj_dev,
7808 struct list_head *dev_list)
7810 struct netdev_adjacent *adj;
7812 pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
7813 dev->name, adj_dev->name, ref_nr);
7815 adj = __netdev_find_adj(adj_dev, dev_list);
7818 pr_err("Adjacency does not exist for device %s from %s\n",
7819 dev->name, adj_dev->name);
7824 if (adj->ref_nr > ref_nr) {
7825 pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
7826 dev->name, adj_dev->name, ref_nr,
7827 adj->ref_nr - ref_nr);
7828 adj->ref_nr -= ref_nr;
7833 sysfs_remove_link(&(dev->dev.kobj), "master");
7835 if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
7836 netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
7838 list_del_rcu(&adj->list);
7839 pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
7840 adj_dev->name, dev->name, adj_dev->name);
7841 netdev_put(adj_dev, &adj->dev_tracker);
7842 kfree_rcu(adj, rcu);
7845 static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
7846 struct net_device *upper_dev,
7847 struct list_head *up_list,
7848 struct list_head *down_list,
7849 void *private, bool master)
7853 ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
7858 ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
7861 __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
7868 static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
7869 struct net_device *upper_dev,
7871 struct list_head *up_list,
7872 struct list_head *down_list)
7874 __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
7875 __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
7878 static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
7879 struct net_device *upper_dev,
7880 void *private, bool master)
7882 return __netdev_adjacent_dev_link_lists(dev, upper_dev,
7883 &dev->adj_list.upper,
7884 &upper_dev->adj_list.lower,
7888 static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
7889 struct net_device *upper_dev)
7891 __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
7892 &dev->adj_list.upper,
7893 &upper_dev->adj_list.lower);
7896 static int __netdev_upper_dev_link(struct net_device *dev,
7897 struct net_device *upper_dev, bool master,
7898 void *upper_priv, void *upper_info,
7899 struct netdev_nested_priv *priv,
7900 struct netlink_ext_ack *extack)
7902 struct netdev_notifier_changeupper_info changeupper_info = {
7907 .upper_dev = upper_dev,
7910 .upper_info = upper_info,
7912 struct net_device *master_dev;
7917 if (dev == upper_dev)
7920 /* To prevent loops, check if dev is not upper device to upper_dev. */
7921 if (__netdev_has_upper_dev(upper_dev, dev))
7924 if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
7928 if (__netdev_has_upper_dev(dev, upper_dev))
7931 master_dev = __netdev_master_upper_dev_get(dev);
7933 return master_dev == upper_dev ? -EEXIST : -EBUSY;
7936 ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
7937 &changeupper_info.info);
7938 ret = notifier_to_errno(ret);
7942 ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
7947 ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
7948 &changeupper_info.info);
7949 ret = notifier_to_errno(ret);
7953 __netdev_update_upper_level(dev, NULL);
7954 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
7956 __netdev_update_lower_level(upper_dev, priv);
7957 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
7963 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
7969 * netdev_upper_dev_link - Add a link to the upper device
7971 * @upper_dev: new upper device
7972 * @extack: netlink extended ack
7974 * Adds a link to device which is upper to this one. The caller must hold
7975 * the RTNL lock. On a failure a negative errno code is returned.
7976 * On success the reference counts are adjusted and the function
7979 int netdev_upper_dev_link(struct net_device *dev,
7980 struct net_device *upper_dev,
7981 struct netlink_ext_ack *extack)
7983 struct netdev_nested_priv priv = {
7984 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
7988 return __netdev_upper_dev_link(dev, upper_dev, false,
7989 NULL, NULL, &priv, extack);
7991 EXPORT_SYMBOL(netdev_upper_dev_link);
7994 * netdev_master_upper_dev_link - Add a master link to the upper device
7996 * @upper_dev: new upper device
7997 * @upper_priv: upper device private
7998 * @upper_info: upper info to be passed down via notifier
7999 * @extack: netlink extended ack
8001 * Adds a link to device which is upper to this one. In this case, only
8002 * one master upper device can be linked, although other non-master devices
8003 * might be linked as well. The caller must hold the RTNL lock.
8004 * On a failure a negative errno code is returned. On success the reference
8005 * counts are adjusted and the function returns zero.
8007 int netdev_master_upper_dev_link(struct net_device *dev,
8008 struct net_device *upper_dev,
8009 void *upper_priv, void *upper_info,
8010 struct netlink_ext_ack *extack)
8012 struct netdev_nested_priv priv = {
8013 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8017 return __netdev_upper_dev_link(dev, upper_dev, true,
8018 upper_priv, upper_info, &priv, extack);
8020 EXPORT_SYMBOL(netdev_master_upper_dev_link);
8022 static void __netdev_upper_dev_unlink(struct net_device *dev,
8023 struct net_device *upper_dev,
8024 struct netdev_nested_priv *priv)
8026 struct netdev_notifier_changeupper_info changeupper_info = {
8030 .upper_dev = upper_dev,
8036 changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
8038 call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
8039 &changeupper_info.info);
8041 __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
8043 call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
8044 &changeupper_info.info);
8046 __netdev_update_upper_level(dev, NULL);
8047 __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
8049 __netdev_update_lower_level(upper_dev, priv);
8050 __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
8055 * netdev_upper_dev_unlink - Removes a link to upper device
8057 * @upper_dev: new upper device
8059 * Removes a link to device which is upper to this one. The caller must hold
8062 void netdev_upper_dev_unlink(struct net_device *dev,
8063 struct net_device *upper_dev)
8065 struct netdev_nested_priv priv = {
8066 .flags = NESTED_SYNC_TODO,
8070 __netdev_upper_dev_unlink(dev, upper_dev, &priv);
8072 EXPORT_SYMBOL(netdev_upper_dev_unlink);
8074 static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
8075 struct net_device *lower_dev,
8078 struct netdev_adjacent *adj;
8080 adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
8084 adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
8089 static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
8090 struct net_device *lower_dev)
8092 __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
8095 static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
8096 struct net_device *lower_dev)
8098 __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
8101 int netdev_adjacent_change_prepare(struct net_device *old_dev,
8102 struct net_device *new_dev,
8103 struct net_device *dev,
8104 struct netlink_ext_ack *extack)
8106 struct netdev_nested_priv priv = {
8115 if (old_dev && new_dev != old_dev)
8116 netdev_adjacent_dev_disable(dev, old_dev);
8117 err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
8120 if (old_dev && new_dev != old_dev)
8121 netdev_adjacent_dev_enable(dev, old_dev);
8127 EXPORT_SYMBOL(netdev_adjacent_change_prepare);
8129 void netdev_adjacent_change_commit(struct net_device *old_dev,
8130 struct net_device *new_dev,
8131 struct net_device *dev)
8133 struct netdev_nested_priv priv = {
8134 .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
8138 if (!new_dev || !old_dev)
8141 if (new_dev == old_dev)
8144 netdev_adjacent_dev_enable(dev, old_dev);
8145 __netdev_upper_dev_unlink(old_dev, dev, &priv);
8147 EXPORT_SYMBOL(netdev_adjacent_change_commit);
8149 void netdev_adjacent_change_abort(struct net_device *old_dev,
8150 struct net_device *new_dev,
8151 struct net_device *dev)
8153 struct netdev_nested_priv priv = {
8161 if (old_dev && new_dev != old_dev)
8162 netdev_adjacent_dev_enable(dev, old_dev);
8164 __netdev_upper_dev_unlink(new_dev, dev, &priv);
8166 EXPORT_SYMBOL(netdev_adjacent_change_abort);
8169 * netdev_bonding_info_change - Dispatch event about slave change
8171 * @bonding_info: info to dispatch
8173 * Send NETDEV_BONDING_INFO to netdev notifiers with info.
8174 * The caller must hold the RTNL lock.
8176 void netdev_bonding_info_change(struct net_device *dev,
8177 struct netdev_bonding_info *bonding_info)
8179 struct netdev_notifier_bonding_info info = {
8183 memcpy(&info.bonding_info, bonding_info,
8184 sizeof(struct netdev_bonding_info));
8185 call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
8188 EXPORT_SYMBOL(netdev_bonding_info_change);
8190 static int netdev_offload_xstats_enable_l3(struct net_device *dev,
8191 struct netlink_ext_ack *extack)
8193 struct netdev_notifier_offload_xstats_info info = {
8195 .info.extack = extack,
8196 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8201 dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
8203 if (!dev->offload_xstats_l3)
8206 rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
8207 NETDEV_OFFLOAD_XSTATS_DISABLE,
8209 err = notifier_to_errno(rc);
8216 kfree(dev->offload_xstats_l3);
8217 dev->offload_xstats_l3 = NULL;
8221 int netdev_offload_xstats_enable(struct net_device *dev,
8222 enum netdev_offload_xstats_type type,
8223 struct netlink_ext_ack *extack)
8227 if (netdev_offload_xstats_enabled(dev, type))
8231 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8232 return netdev_offload_xstats_enable_l3(dev, extack);
8238 EXPORT_SYMBOL(netdev_offload_xstats_enable);
8240 static void netdev_offload_xstats_disable_l3(struct net_device *dev)
8242 struct netdev_notifier_offload_xstats_info info = {
8244 .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
8247 call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
8249 kfree(dev->offload_xstats_l3);
8250 dev->offload_xstats_l3 = NULL;
8253 int netdev_offload_xstats_disable(struct net_device *dev,
8254 enum netdev_offload_xstats_type type)
8258 if (!netdev_offload_xstats_enabled(dev, type))
8262 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8263 netdev_offload_xstats_disable_l3(dev);
8270 EXPORT_SYMBOL(netdev_offload_xstats_disable);
8272 static void netdev_offload_xstats_disable_all(struct net_device *dev)
8274 netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
8277 static struct rtnl_hw_stats64 *
8278 netdev_offload_xstats_get_ptr(const struct net_device *dev,
8279 enum netdev_offload_xstats_type type)
8282 case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
8283 return dev->offload_xstats_l3;
8290 bool netdev_offload_xstats_enabled(const struct net_device *dev,
8291 enum netdev_offload_xstats_type type)
8295 return netdev_offload_xstats_get_ptr(dev, type);
8297 EXPORT_SYMBOL(netdev_offload_xstats_enabled);
8299 struct netdev_notifier_offload_xstats_ru {
8303 struct netdev_notifier_offload_xstats_rd {
8304 struct rtnl_hw_stats64 stats;
8308 static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
8309 const struct rtnl_hw_stats64 *src)
8311 dest->rx_packets += src->rx_packets;
8312 dest->tx_packets += src->tx_packets;
8313 dest->rx_bytes += src->rx_bytes;
8314 dest->tx_bytes += src->tx_bytes;
8315 dest->rx_errors += src->rx_errors;
8316 dest->tx_errors += src->tx_errors;
8317 dest->rx_dropped += src->rx_dropped;
8318 dest->tx_dropped += src->tx_dropped;
8319 dest->multicast += src->multicast;
8322 static int netdev_offload_xstats_get_used(struct net_device *dev,
8323 enum netdev_offload_xstats_type type,
8325 struct netlink_ext_ack *extack)
8327 struct netdev_notifier_offload_xstats_ru report_used = {};
8328 struct netdev_notifier_offload_xstats_info info = {
8330 .info.extack = extack,
8332 .report_used = &report_used,
8336 WARN_ON(!netdev_offload_xstats_enabled(dev, type));
8337 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
8339 *p_used = report_used.used;
8340 return notifier_to_errno(rc);
8343 static int netdev_offload_xstats_get_stats(struct net_device *dev,
8344 enum netdev_offload_xstats_type type,
8345 struct rtnl_hw_stats64 *p_stats,
8347 struct netlink_ext_ack *extack)
8349 struct netdev_notifier_offload_xstats_rd report_delta = {};
8350 struct netdev_notifier_offload_xstats_info info = {
8352 .info.extack = extack,
8354 .report_delta = &report_delta,
8356 struct rtnl_hw_stats64 *stats;
8359 stats = netdev_offload_xstats_get_ptr(dev, type);
8360 if (WARN_ON(!stats))
8363 rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
8366 /* Cache whatever we got, even if there was an error, otherwise the
8367 * successful stats retrievals would get lost.
8369 netdev_hw_stats64_add(stats, &report_delta.stats);
8373 *p_used = report_delta.used;
8375 return notifier_to_errno(rc);
8378 int netdev_offload_xstats_get(struct net_device *dev,
8379 enum netdev_offload_xstats_type type,
8380 struct rtnl_hw_stats64 *p_stats, bool *p_used,
8381 struct netlink_ext_ack *extack)
8386 return netdev_offload_xstats_get_stats(dev, type, p_stats,
8389 return netdev_offload_xstats_get_used(dev, type, p_used,
8392 EXPORT_SYMBOL(netdev_offload_xstats_get);
8395 netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
8396 const struct rtnl_hw_stats64 *stats)
8398 report_delta->used = true;
8399 netdev_hw_stats64_add(&report_delta->stats, stats);
8401 EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
8404 netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
8406 report_used->used = true;
8408 EXPORT_SYMBOL(netdev_offload_xstats_report_used);
8410 void netdev_offload_xstats_push_delta(struct net_device *dev,
8411 enum netdev_offload_xstats_type type,
8412 const struct rtnl_hw_stats64 *p_stats)
8414 struct rtnl_hw_stats64 *stats;
8418 stats = netdev_offload_xstats_get_ptr(dev, type);
8419 if (WARN_ON(!stats))
8422 netdev_hw_stats64_add(stats, p_stats);
8424 EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
8427 * netdev_get_xmit_slave - Get the xmit slave of master device
8430 * @all_slaves: assume all the slaves are active
8432 * The reference counters are not incremented so the caller must be
8433 * careful with locks. The caller must hold RCU lock.
8434 * %NULL is returned if no slave is found.
8437 struct net_device *netdev_get_xmit_slave(struct net_device *dev,
8438 struct sk_buff *skb,
8441 const struct net_device_ops *ops = dev->netdev_ops;
8443 if (!ops->ndo_get_xmit_slave)
8445 return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
8447 EXPORT_SYMBOL(netdev_get_xmit_slave);
8449 static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
8452 const struct net_device_ops *ops = dev->netdev_ops;
8454 if (!ops->ndo_sk_get_lower_dev)
8456 return ops->ndo_sk_get_lower_dev(dev, sk);
8460 * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
8464 * %NULL is returned if no lower device is found.
8467 struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
8470 struct net_device *lower;
8472 lower = netdev_sk_get_lower_dev(dev, sk);
8475 lower = netdev_sk_get_lower_dev(dev, sk);
8480 EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
8482 static void netdev_adjacent_add_links(struct net_device *dev)
8484 struct netdev_adjacent *iter;
8486 struct net *net = dev_net(dev);
8488 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8489 if (!net_eq(net, dev_net(iter->dev)))
8491 netdev_adjacent_sysfs_add(iter->dev, dev,
8492 &iter->dev->adj_list.lower);
8493 netdev_adjacent_sysfs_add(dev, iter->dev,
8494 &dev->adj_list.upper);
8497 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8498 if (!net_eq(net, dev_net(iter->dev)))
8500 netdev_adjacent_sysfs_add(iter->dev, dev,
8501 &iter->dev->adj_list.upper);
8502 netdev_adjacent_sysfs_add(dev, iter->dev,
8503 &dev->adj_list.lower);
8507 static void netdev_adjacent_del_links(struct net_device *dev)
8509 struct netdev_adjacent *iter;
8511 struct net *net = dev_net(dev);
8513 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8514 if (!net_eq(net, dev_net(iter->dev)))
8516 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8517 &iter->dev->adj_list.lower);
8518 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8519 &dev->adj_list.upper);
8522 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8523 if (!net_eq(net, dev_net(iter->dev)))
8525 netdev_adjacent_sysfs_del(iter->dev, dev->name,
8526 &iter->dev->adj_list.upper);
8527 netdev_adjacent_sysfs_del(dev, iter->dev->name,
8528 &dev->adj_list.lower);
8532 void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
8534 struct netdev_adjacent *iter;
8536 struct net *net = dev_net(dev);
8538 list_for_each_entry(iter, &dev->adj_list.upper, list) {
8539 if (!net_eq(net, dev_net(iter->dev)))
8541 netdev_adjacent_sysfs_del(iter->dev, oldname,
8542 &iter->dev->adj_list.lower);
8543 netdev_adjacent_sysfs_add(iter->dev, dev,
8544 &iter->dev->adj_list.lower);
8547 list_for_each_entry(iter, &dev->adj_list.lower, list) {
8548 if (!net_eq(net, dev_net(iter->dev)))
8550 netdev_adjacent_sysfs_del(iter->dev, oldname,
8551 &iter->dev->adj_list.upper);
8552 netdev_adjacent_sysfs_add(iter->dev, dev,
8553 &iter->dev->adj_list.upper);
8557 void *netdev_lower_dev_get_private(struct net_device *dev,
8558 struct net_device *lower_dev)
8560 struct netdev_adjacent *lower;
8564 lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
8568 return lower->private;
8570 EXPORT_SYMBOL(netdev_lower_dev_get_private);
8574 * netdev_lower_state_changed - Dispatch event about lower device state change
8575 * @lower_dev: device
8576 * @lower_state_info: state to dispatch
8578 * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
8579 * The caller must hold the RTNL lock.
8581 void netdev_lower_state_changed(struct net_device *lower_dev,
8582 void *lower_state_info)
8584 struct netdev_notifier_changelowerstate_info changelowerstate_info = {
8585 .info.dev = lower_dev,
8589 changelowerstate_info.lower_state_info = lower_state_info;
8590 call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
8591 &changelowerstate_info.info);
8593 EXPORT_SYMBOL(netdev_lower_state_changed);
8595 static void dev_change_rx_flags(struct net_device *dev, int flags)
8597 const struct net_device_ops *ops = dev->netdev_ops;
8599 if (ops->ndo_change_rx_flags)
8600 ops->ndo_change_rx_flags(dev, flags);
8603 static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
8605 unsigned int old_flags = dev->flags;
8606 unsigned int promiscuity, flags;
8612 promiscuity = dev->promiscuity + inc;
8613 if (promiscuity == 0) {
8616 * If inc causes overflow, untouch promisc and return error.
8618 if (unlikely(inc > 0)) {
8619 netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
8622 flags = old_flags & ~IFF_PROMISC;
8624 flags = old_flags | IFF_PROMISC;
8626 WRITE_ONCE(dev->promiscuity, promiscuity);
8627 if (flags != old_flags) {
8628 WRITE_ONCE(dev->flags, flags);
8629 netdev_info(dev, "%s promiscuous mode\n",
8630 dev->flags & IFF_PROMISC ? "entered" : "left");
8631 if (audit_enabled) {
8632 current_uid_gid(&uid, &gid);
8633 audit_log(audit_context(), GFP_ATOMIC,
8634 AUDIT_ANOM_PROMISCUOUS,
8635 "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
8636 dev->name, (dev->flags & IFF_PROMISC),
8637 (old_flags & IFF_PROMISC),
8638 from_kuid(&init_user_ns, audit_get_loginuid(current)),
8639 from_kuid(&init_user_ns, uid),
8640 from_kgid(&init_user_ns, gid),
8641 audit_get_sessionid(current));
8644 dev_change_rx_flags(dev, IFF_PROMISC);
8647 __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
8652 * dev_set_promiscuity - update promiscuity count on a device
8656 * Add or remove promiscuity from a device. While the count in the device
8657 * remains above zero the interface remains promiscuous. Once it hits zero
8658 * the device reverts back to normal filtering operation. A negative inc
8659 * value is used to drop promiscuity on the device.
8660 * Return 0 if successful or a negative errno code on error.
8662 int dev_set_promiscuity(struct net_device *dev, int inc)
8664 unsigned int old_flags = dev->flags;
8667 err = __dev_set_promiscuity(dev, inc, true);
8670 if (dev->flags != old_flags)
8671 dev_set_rx_mode(dev);
8674 EXPORT_SYMBOL(dev_set_promiscuity);
8676 static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
8678 unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
8679 unsigned int allmulti, flags;
8683 allmulti = dev->allmulti + inc;
8684 if (allmulti == 0) {
8687 * If inc causes overflow, untouch allmulti and return error.
8689 if (unlikely(inc > 0)) {
8690 netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
8693 flags = old_flags & ~IFF_ALLMULTI;
8695 flags = old_flags | IFF_ALLMULTI;
8697 WRITE_ONCE(dev->allmulti, allmulti);
8698 if (flags != old_flags) {
8699 WRITE_ONCE(dev->flags, flags);
8700 netdev_info(dev, "%s allmulticast mode\n",
8701 dev->flags & IFF_ALLMULTI ? "entered" : "left");
8702 dev_change_rx_flags(dev, IFF_ALLMULTI);
8703 dev_set_rx_mode(dev);
8705 __dev_notify_flags(dev, old_flags,
8706 dev->gflags ^ old_gflags, 0, NULL);
8712 * dev_set_allmulti - update allmulti count on a device
8716 * Add or remove reception of all multicast frames to a device. While the
8717 * count in the device remains above zero the interface remains listening
8718 * to all interfaces. Once it hits zero the device reverts back to normal
8719 * filtering operation. A negative @inc value is used to drop the counter
8720 * when releasing a resource needing all multicasts.
8721 * Return 0 if successful or a negative errno code on error.
8724 int dev_set_allmulti(struct net_device *dev, int inc)
8726 return __dev_set_allmulti(dev, inc, true);
8728 EXPORT_SYMBOL(dev_set_allmulti);
8731 * Upload unicast and multicast address lists to device and
8732 * configure RX filtering. When the device doesn't support unicast
8733 * filtering it is put in promiscuous mode while unicast addresses
8736 void __dev_set_rx_mode(struct net_device *dev)
8738 const struct net_device_ops *ops = dev->netdev_ops;
8740 /* dev_open will call this function so the list will stay sane. */
8741 if (!(dev->flags&IFF_UP))
8744 if (!netif_device_present(dev))
8747 if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
8748 /* Unicast addresses changes may only happen under the rtnl,
8749 * therefore calling __dev_set_promiscuity here is safe.
8751 if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
8752 __dev_set_promiscuity(dev, 1, false);
8753 dev->uc_promisc = true;
8754 } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
8755 __dev_set_promiscuity(dev, -1, false);
8756 dev->uc_promisc = false;
8760 if (ops->ndo_set_rx_mode)
8761 ops->ndo_set_rx_mode(dev);
8764 void dev_set_rx_mode(struct net_device *dev)
8766 netif_addr_lock_bh(dev);
8767 __dev_set_rx_mode(dev);
8768 netif_addr_unlock_bh(dev);
8772 * dev_get_flags - get flags reported to userspace
8775 * Get the combination of flag bits exported through APIs to userspace.
8777 unsigned int dev_get_flags(const struct net_device *dev)
8781 flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC |
8786 (READ_ONCE(dev->gflags) & (IFF_PROMISC |
8789 if (netif_running(dev)) {
8790 if (netif_oper_up(dev))
8791 flags |= IFF_RUNNING;
8792 if (netif_carrier_ok(dev))
8793 flags |= IFF_LOWER_UP;
8794 if (netif_dormant(dev))
8795 flags |= IFF_DORMANT;
8800 EXPORT_SYMBOL(dev_get_flags);
8802 int __dev_change_flags(struct net_device *dev, unsigned int flags,
8803 struct netlink_ext_ack *extack)
8805 unsigned int old_flags = dev->flags;
8811 * Set the flags on our device.
8814 dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
8815 IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
8817 (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
8821 * Load in the correct multicast list now the flags have changed.
8824 if ((old_flags ^ flags) & IFF_MULTICAST)
8825 dev_change_rx_flags(dev, IFF_MULTICAST);
8827 dev_set_rx_mode(dev);
8830 * Have we downed the interface. We handle IFF_UP ourselves
8831 * according to user attempts to set it, rather than blindly
8836 if ((old_flags ^ flags) & IFF_UP) {
8837 if (old_flags & IFF_UP)
8840 ret = __dev_open(dev, extack);
8843 if ((flags ^ dev->gflags) & IFF_PROMISC) {
8844 int inc = (flags & IFF_PROMISC) ? 1 : -1;
8845 unsigned int old_flags = dev->flags;
8847 dev->gflags ^= IFF_PROMISC;
8849 if (__dev_set_promiscuity(dev, inc, false) >= 0)
8850 if (dev->flags != old_flags)
8851 dev_set_rx_mode(dev);
8854 /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
8855 * is important. Some (broken) drivers set IFF_PROMISC, when
8856 * IFF_ALLMULTI is requested not asking us and not reporting.
8858 if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
8859 int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
8861 dev->gflags ^= IFF_ALLMULTI;
8862 __dev_set_allmulti(dev, inc, false);
8868 void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
8869 unsigned int gchanges, u32 portid,
8870 const struct nlmsghdr *nlh)
8872 unsigned int changes = dev->flags ^ old_flags;
8875 rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
8877 if (changes & IFF_UP) {
8878 if (dev->flags & IFF_UP)
8879 call_netdevice_notifiers(NETDEV_UP, dev);
8881 call_netdevice_notifiers(NETDEV_DOWN, dev);
8884 if (dev->flags & IFF_UP &&
8885 (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
8886 struct netdev_notifier_change_info change_info = {
8890 .flags_changed = changes,
8893 call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
8898 * dev_change_flags - change device settings
8900 * @flags: device state flags
8901 * @extack: netlink extended ack
8903 * Change settings on device based state flags. The flags are
8904 * in the userspace exported format.
8906 int dev_change_flags(struct net_device *dev, unsigned int flags,
8907 struct netlink_ext_ack *extack)
8910 unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
8912 ret = __dev_change_flags(dev, flags, extack);
8916 changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
8917 __dev_notify_flags(dev, old_flags, changes, 0, NULL);
8920 EXPORT_SYMBOL(dev_change_flags);
8922 int __dev_set_mtu(struct net_device *dev, int new_mtu)
8924 const struct net_device_ops *ops = dev->netdev_ops;
8926 if (ops->ndo_change_mtu)
8927 return ops->ndo_change_mtu(dev, new_mtu);
8929 /* Pairs with all the lockless reads of dev->mtu in the stack */
8930 WRITE_ONCE(dev->mtu, new_mtu);
8933 EXPORT_SYMBOL(__dev_set_mtu);
8935 int dev_validate_mtu(struct net_device *dev, int new_mtu,
8936 struct netlink_ext_ack *extack)
8938 /* MTU must be positive, and in range */
8939 if (new_mtu < 0 || new_mtu < dev->min_mtu) {
8940 NL_SET_ERR_MSG(extack, "mtu less than device minimum");
8944 if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
8945 NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
8952 * dev_set_mtu_ext - Change maximum transfer unit
8954 * @new_mtu: new transfer unit
8955 * @extack: netlink extended ack
8957 * Change the maximum transfer size of the network device.
8959 int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
8960 struct netlink_ext_ack *extack)
8964 if (new_mtu == dev->mtu)
8967 err = dev_validate_mtu(dev, new_mtu, extack);
8971 if (!netif_device_present(dev))
8974 err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
8975 err = notifier_to_errno(err);
8979 orig_mtu = dev->mtu;
8980 err = __dev_set_mtu(dev, new_mtu);
8983 err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8985 err = notifier_to_errno(err);
8987 /* setting mtu back and notifying everyone again,
8988 * so that they have a chance to revert changes.
8990 __dev_set_mtu(dev, orig_mtu);
8991 call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
8998 int dev_set_mtu(struct net_device *dev, int new_mtu)
9000 struct netlink_ext_ack extack;
9003 memset(&extack, 0, sizeof(extack));
9004 err = dev_set_mtu_ext(dev, new_mtu, &extack);
9005 if (err && extack._msg)
9006 net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
9009 EXPORT_SYMBOL(dev_set_mtu);
9012 * dev_change_tx_queue_len - Change TX queue length of a netdevice
9014 * @new_len: new tx queue length
9016 int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
9018 unsigned int orig_len = dev->tx_queue_len;
9021 if (new_len != (unsigned int)new_len)
9024 if (new_len != orig_len) {
9025 WRITE_ONCE(dev->tx_queue_len, new_len);
9026 res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
9027 res = notifier_to_errno(res);
9030 res = dev_qdisc_change_tx_queue_len(dev);
9038 netdev_err(dev, "refused to change device tx_queue_len\n");
9039 WRITE_ONCE(dev->tx_queue_len, orig_len);
9044 * dev_set_group - Change group this device belongs to
9046 * @new_group: group this device should belong to
9048 void dev_set_group(struct net_device *dev, int new_group)
9050 dev->group = new_group;
9054 * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
9056 * @addr: new address
9057 * @extack: netlink extended ack
9059 int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
9060 struct netlink_ext_ack *extack)
9062 struct netdev_notifier_pre_changeaddr_info info = {
9064 .info.extack = extack,
9069 rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
9070 return notifier_to_errno(rc);
9072 EXPORT_SYMBOL(dev_pre_changeaddr_notify);
9075 * dev_set_mac_address - Change Media Access Control Address
9078 * @extack: netlink extended ack
9080 * Change the hardware (MAC) address of the device
9082 int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
9083 struct netlink_ext_ack *extack)
9085 const struct net_device_ops *ops = dev->netdev_ops;
9088 if (!ops->ndo_set_mac_address)
9090 if (sa->sa_family != dev->type)
9092 if (!netif_device_present(dev))
9094 err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
9097 if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
9098 err = ops->ndo_set_mac_address(dev, sa);
9102 dev->addr_assign_type = NET_ADDR_SET;
9103 call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
9104 add_device_randomness(dev->dev_addr, dev->addr_len);
9107 EXPORT_SYMBOL(dev_set_mac_address);
9109 DECLARE_RWSEM(dev_addr_sem);
9111 int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
9112 struct netlink_ext_ack *extack)
9116 down_write(&dev_addr_sem);
9117 ret = dev_set_mac_address(dev, sa, extack);
9118 up_write(&dev_addr_sem);
9121 EXPORT_SYMBOL(dev_set_mac_address_user);
9123 int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
9125 size_t size = sizeof(sa->sa_data_min);
9126 struct net_device *dev;
9129 down_read(&dev_addr_sem);
9132 dev = dev_get_by_name_rcu(net, dev_name);
9138 memset(sa->sa_data, 0, size);
9140 memcpy(sa->sa_data, dev->dev_addr,
9141 min_t(size_t, size, dev->addr_len));
9142 sa->sa_family = dev->type;
9146 up_read(&dev_addr_sem);
9149 EXPORT_SYMBOL(dev_get_mac_address);
9152 * dev_change_carrier - Change device carrier
9154 * @new_carrier: new value
9156 * Change device carrier
9158 int dev_change_carrier(struct net_device *dev, bool new_carrier)
9160 const struct net_device_ops *ops = dev->netdev_ops;
9162 if (!ops->ndo_change_carrier)
9164 if (!netif_device_present(dev))
9166 return ops->ndo_change_carrier(dev, new_carrier);
9170 * dev_get_phys_port_id - Get device physical port ID
9174 * Get device physical port ID
9176 int dev_get_phys_port_id(struct net_device *dev,
9177 struct netdev_phys_item_id *ppid)
9179 const struct net_device_ops *ops = dev->netdev_ops;
9181 if (!ops->ndo_get_phys_port_id)
9183 return ops->ndo_get_phys_port_id(dev, ppid);
9187 * dev_get_phys_port_name - Get device physical port name
9190 * @len: limit of bytes to copy to name
9192 * Get device physical port name
9194 int dev_get_phys_port_name(struct net_device *dev,
9195 char *name, size_t len)
9197 const struct net_device_ops *ops = dev->netdev_ops;
9200 if (ops->ndo_get_phys_port_name) {
9201 err = ops->ndo_get_phys_port_name(dev, name, len);
9202 if (err != -EOPNOTSUPP)
9205 return devlink_compat_phys_port_name_get(dev, name, len);
9209 * dev_get_port_parent_id - Get the device's port parent identifier
9210 * @dev: network device
9211 * @ppid: pointer to a storage for the port's parent identifier
9212 * @recurse: allow/disallow recursion to lower devices
9214 * Get the devices's port parent identifier
9216 int dev_get_port_parent_id(struct net_device *dev,
9217 struct netdev_phys_item_id *ppid,
9220 const struct net_device_ops *ops = dev->netdev_ops;
9221 struct netdev_phys_item_id first = { };
9222 struct net_device *lower_dev;
9223 struct list_head *iter;
9226 if (ops->ndo_get_port_parent_id) {
9227 err = ops->ndo_get_port_parent_id(dev, ppid);
9228 if (err != -EOPNOTSUPP)
9232 err = devlink_compat_switch_id_get(dev, ppid);
9233 if (!recurse || err != -EOPNOTSUPP)
9236 netdev_for_each_lower_dev(dev, lower_dev, iter) {
9237 err = dev_get_port_parent_id(lower_dev, ppid, true);
9242 else if (memcmp(&first, ppid, sizeof(*ppid)))
9248 EXPORT_SYMBOL(dev_get_port_parent_id);
9251 * netdev_port_same_parent_id - Indicate if two network devices have
9252 * the same port parent identifier
9253 * @a: first network device
9254 * @b: second network device
9256 bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
9258 struct netdev_phys_item_id a_id = { };
9259 struct netdev_phys_item_id b_id = { };
9261 if (dev_get_port_parent_id(a, &a_id, true) ||
9262 dev_get_port_parent_id(b, &b_id, true))
9265 return netdev_phys_item_id_same(&a_id, &b_id);
9267 EXPORT_SYMBOL(netdev_port_same_parent_id);
9270 * dev_change_proto_down - set carrier according to proto_down.
9273 * @proto_down: new value
9275 int dev_change_proto_down(struct net_device *dev, bool proto_down)
9277 if (!dev->change_proto_down)
9279 if (!netif_device_present(dev))
9282 netif_carrier_off(dev);
9284 netif_carrier_on(dev);
9285 WRITE_ONCE(dev->proto_down, proto_down);
9290 * dev_change_proto_down_reason - proto down reason
9293 * @mask: proto down mask
9294 * @value: proto down value
9296 void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
9299 u32 proto_down_reason;
9303 proto_down_reason = value;
9305 proto_down_reason = dev->proto_down_reason;
9306 for_each_set_bit(b, &mask, 32) {
9307 if (value & (1 << b))
9308 proto_down_reason |= BIT(b);
9310 proto_down_reason &= ~BIT(b);
9313 WRITE_ONCE(dev->proto_down_reason, proto_down_reason);
9316 struct bpf_xdp_link {
9317 struct bpf_link link;
9318 struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
9322 static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
9324 if (flags & XDP_FLAGS_HW_MODE)
9326 if (flags & XDP_FLAGS_DRV_MODE)
9327 return XDP_MODE_DRV;
9328 if (flags & XDP_FLAGS_SKB_MODE)
9329 return XDP_MODE_SKB;
9330 return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
9333 static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
9337 return generic_xdp_install;
9340 return dev->netdev_ops->ndo_bpf;
9346 static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
9347 enum bpf_xdp_mode mode)
9349 return dev->xdp_state[mode].link;
9352 static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
9353 enum bpf_xdp_mode mode)
9355 struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
9358 return link->link.prog;
9359 return dev->xdp_state[mode].prog;
9362 u8 dev_xdp_prog_count(struct net_device *dev)
9367 for (i = 0; i < __MAX_XDP_MODE; i++)
9368 if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
9372 EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
9374 int dev_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
9376 if (!dev->netdev_ops->ndo_bpf)
9379 return dev->netdev_ops->ndo_bpf(dev, bpf);
9381 EXPORT_SYMBOL_GPL(dev_xdp_propagate);
9383 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
9385 struct bpf_prog *prog = dev_xdp_prog(dev, mode);
9387 return prog ? prog->aux->id : 0;
9390 static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
9391 struct bpf_xdp_link *link)
9393 dev->xdp_state[mode].link = link;
9394 dev->xdp_state[mode].prog = NULL;
9397 static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
9398 struct bpf_prog *prog)
9400 dev->xdp_state[mode].link = NULL;
9401 dev->xdp_state[mode].prog = prog;
9404 static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
9405 bpf_op_t bpf_op, struct netlink_ext_ack *extack,
9406 u32 flags, struct bpf_prog *prog)
9408 struct netdev_bpf xdp;
9411 memset(&xdp, 0, sizeof(xdp));
9412 xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
9413 xdp.extack = extack;
9417 /* Drivers assume refcnt is already incremented (i.e, prog pointer is
9418 * "moved" into driver), so they don't increment it on their own, but
9419 * they do decrement refcnt when program is detached or replaced.
9420 * Given net_device also owns link/prog, we need to bump refcnt here
9421 * to prevent drivers from underflowing it.
9425 err = bpf_op(dev, &xdp);
9432 if (mode != XDP_MODE_HW)
9433 bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
9438 static void dev_xdp_uninstall(struct net_device *dev)
9440 struct bpf_xdp_link *link;
9441 struct bpf_prog *prog;
9442 enum bpf_xdp_mode mode;
9447 for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
9448 prog = dev_xdp_prog(dev, mode);
9452 bpf_op = dev_xdp_bpf_op(dev, mode);
9456 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9458 /* auto-detach link from net device */
9459 link = dev_xdp_link(dev, mode);
9465 dev_xdp_set_link(dev, mode, NULL);
9469 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
9470 struct bpf_xdp_link *link, struct bpf_prog *new_prog,
9471 struct bpf_prog *old_prog, u32 flags)
9473 unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
9474 struct bpf_prog *cur_prog;
9475 struct net_device *upper;
9476 struct list_head *iter;
9477 enum bpf_xdp_mode mode;
9483 /* either link or prog attachment, never both */
9484 if (link && (new_prog || old_prog))
9486 /* link supports only XDP mode flags */
9487 if (link && (flags & ~XDP_FLAGS_MODES)) {
9488 NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
9491 /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
9492 if (num_modes > 1) {
9493 NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
9496 /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
9497 if (!num_modes && dev_xdp_prog_count(dev) > 1) {
9498 NL_SET_ERR_MSG(extack,
9499 "More than one program loaded, unset mode is ambiguous");
9502 /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
9503 if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
9504 NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
9508 mode = dev_xdp_mode(dev, flags);
9509 /* can't replace attached link */
9510 if (dev_xdp_link(dev, mode)) {
9511 NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
9515 /* don't allow if an upper device already has a program */
9516 netdev_for_each_upper_dev_rcu(dev, upper, iter) {
9517 if (dev_xdp_prog_count(upper) > 0) {
9518 NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
9523 cur_prog = dev_xdp_prog(dev, mode);
9524 /* can't replace attached prog with link */
9525 if (link && cur_prog) {
9526 NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
9529 if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
9530 NL_SET_ERR_MSG(extack, "Active program does not match expected");
9534 /* put effective new program into new_prog */
9536 new_prog = link->link.prog;
9539 bool offload = mode == XDP_MODE_HW;
9540 enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
9541 ? XDP_MODE_DRV : XDP_MODE_SKB;
9543 if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
9544 NL_SET_ERR_MSG(extack, "XDP program already attached");
9547 if (!offload && dev_xdp_prog(dev, other_mode)) {
9548 NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
9551 if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
9552 NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
9555 if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
9556 NL_SET_ERR_MSG(extack, "Program bound to different device");
9559 if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
9560 NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
9563 if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
9564 NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
9569 /* don't call drivers if the effective program didn't change */
9570 if (new_prog != cur_prog) {
9571 bpf_op = dev_xdp_bpf_op(dev, mode);
9573 NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
9577 err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
9583 dev_xdp_set_link(dev, mode, link);
9585 dev_xdp_set_prog(dev, mode, new_prog);
9587 bpf_prog_put(cur_prog);
9592 static int dev_xdp_attach_link(struct net_device *dev,
9593 struct netlink_ext_ack *extack,
9594 struct bpf_xdp_link *link)
9596 return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
9599 static int dev_xdp_detach_link(struct net_device *dev,
9600 struct netlink_ext_ack *extack,
9601 struct bpf_xdp_link *link)
9603 enum bpf_xdp_mode mode;
9608 mode = dev_xdp_mode(dev, link->flags);
9609 if (dev_xdp_link(dev, mode) != link)
9612 bpf_op = dev_xdp_bpf_op(dev, mode);
9613 WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
9614 dev_xdp_set_link(dev, mode, NULL);
9618 static void bpf_xdp_link_release(struct bpf_link *link)
9620 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9624 /* if racing with net_device's tear down, xdp_link->dev might be
9625 * already NULL, in which case link was already auto-detached
9627 if (xdp_link->dev) {
9628 WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
9629 xdp_link->dev = NULL;
9635 static int bpf_xdp_link_detach(struct bpf_link *link)
9637 bpf_xdp_link_release(link);
9641 static void bpf_xdp_link_dealloc(struct bpf_link *link)
9643 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9648 static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
9649 struct seq_file *seq)
9651 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9656 ifindex = xdp_link->dev->ifindex;
9659 seq_printf(seq, "ifindex:\t%u\n", ifindex);
9662 static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
9663 struct bpf_link_info *info)
9665 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9670 ifindex = xdp_link->dev->ifindex;
9673 info->xdp.ifindex = ifindex;
9677 static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
9678 struct bpf_prog *old_prog)
9680 struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
9681 enum bpf_xdp_mode mode;
9687 /* link might have been auto-released already, so fail */
9688 if (!xdp_link->dev) {
9693 if (old_prog && link->prog != old_prog) {
9697 old_prog = link->prog;
9698 if (old_prog->type != new_prog->type ||
9699 old_prog->expected_attach_type != new_prog->expected_attach_type) {
9704 if (old_prog == new_prog) {
9705 /* no-op, don't disturb drivers */
9706 bpf_prog_put(new_prog);
9710 mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
9711 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
9712 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
9713 xdp_link->flags, new_prog);
9717 old_prog = xchg(&link->prog, new_prog);
9718 bpf_prog_put(old_prog);
9725 static const struct bpf_link_ops bpf_xdp_link_lops = {
9726 .release = bpf_xdp_link_release,
9727 .dealloc = bpf_xdp_link_dealloc,
9728 .detach = bpf_xdp_link_detach,
9729 .show_fdinfo = bpf_xdp_link_show_fdinfo,
9730 .fill_link_info = bpf_xdp_link_fill_link_info,
9731 .update_prog = bpf_xdp_link_update,
9734 int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
9736 struct net *net = current->nsproxy->net_ns;
9737 struct bpf_link_primer link_primer;
9738 struct netlink_ext_ack extack = {};
9739 struct bpf_xdp_link *link;
9740 struct net_device *dev;
9744 dev = dev_get_by_index(net, attr->link_create.target_ifindex);
9750 link = kzalloc(sizeof(*link), GFP_USER);
9756 bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
9758 link->flags = attr->link_create.flags;
9760 err = bpf_link_prime(&link->link, &link_primer);
9766 err = dev_xdp_attach_link(dev, &extack, link);
9771 bpf_link_cleanup(&link_primer);
9772 trace_bpf_xdp_link_attach_failed(extack._msg);
9776 fd = bpf_link_settle(&link_primer);
9777 /* link itself doesn't hold dev's refcnt to not complicate shutdown */
9790 * dev_change_xdp_fd - set or clear a bpf program for a device rx path
9792 * @extack: netlink extended ack
9793 * @fd: new program fd or negative value to clear
9794 * @expected_fd: old program fd that userspace expects to replace or clear
9795 * @flags: xdp-related flags
9797 * Set or clear a bpf program for a device
9799 int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
9800 int fd, int expected_fd, u32 flags)
9802 enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
9803 struct bpf_prog *new_prog = NULL, *old_prog = NULL;
9809 new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
9810 mode != XDP_MODE_SKB);
9811 if (IS_ERR(new_prog))
9812 return PTR_ERR(new_prog);
9815 if (expected_fd >= 0) {
9816 old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
9817 mode != XDP_MODE_SKB);
9818 if (IS_ERR(old_prog)) {
9819 err = PTR_ERR(old_prog);
9825 err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
9828 if (err && new_prog)
9829 bpf_prog_put(new_prog);
9831 bpf_prog_put(old_prog);
9836 * dev_index_reserve() - allocate an ifindex in a namespace
9837 * @net: the applicable net namespace
9838 * @ifindex: requested ifindex, pass %0 to get one allocated
9840 * Allocate a ifindex for a new device. Caller must either use the ifindex
9841 * to store the device (via list_netdevice()) or call dev_index_release()
9842 * to give the index up.
9844 * Return: a suitable unique value for a new device interface number or -errno.
9846 static int dev_index_reserve(struct net *net, u32 ifindex)
9850 if (ifindex > INT_MAX) {
9851 DEBUG_NET_WARN_ON_ONCE(1);
9856 err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
9857 xa_limit_31b, &net->ifindex, GFP_KERNEL);
9859 err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
9866 static void dev_index_release(struct net *net, int ifindex)
9868 /* Expect only unused indexes, unlist_netdevice() removes the used */
9869 WARN_ON(xa_erase(&net->dev_by_index, ifindex));
9872 /* Delayed registration/unregisteration */
9873 LIST_HEAD(net_todo_list);
9874 DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
9875 atomic_t dev_unreg_count = ATOMIC_INIT(0);
9877 static void net_set_todo(struct net_device *dev)
9879 list_add_tail(&dev->todo_list, &net_todo_list);
9882 static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
9883 struct net_device *upper, netdev_features_t features)
9885 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9886 netdev_features_t feature;
9889 for_each_netdev_feature(upper_disables, feature_bit) {
9890 feature = __NETIF_F_BIT(feature_bit);
9891 if (!(upper->wanted_features & feature)
9892 && (features & feature)) {
9893 netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
9894 &feature, upper->name);
9895 features &= ~feature;
9902 static void netdev_sync_lower_features(struct net_device *upper,
9903 struct net_device *lower, netdev_features_t features)
9905 netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
9906 netdev_features_t feature;
9909 for_each_netdev_feature(upper_disables, feature_bit) {
9910 feature = __NETIF_F_BIT(feature_bit);
9911 if (!(features & feature) && (lower->features & feature)) {
9912 netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
9913 &feature, lower->name);
9914 lower->wanted_features &= ~feature;
9915 __netdev_update_features(lower);
9917 if (unlikely(lower->features & feature))
9918 netdev_WARN(upper, "failed to disable %pNF on %s!\n",
9919 &feature, lower->name);
9921 netdev_features_change(lower);
9926 static bool netdev_has_ip_or_hw_csum(netdev_features_t features)
9928 netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
9929 bool ip_csum = (features & ip_csum_mask) == ip_csum_mask;
9930 bool hw_csum = features & NETIF_F_HW_CSUM;
9932 return ip_csum || hw_csum;
9935 static netdev_features_t netdev_fix_features(struct net_device *dev,
9936 netdev_features_t features)
9938 /* Fix illegal checksum combinations */
9939 if ((features & NETIF_F_HW_CSUM) &&
9940 (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
9941 netdev_warn(dev, "mixed HW and IP checksum settings.\n");
9942 features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
9945 /* TSO requires that SG is present as well. */
9946 if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
9947 netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
9948 features &= ~NETIF_F_ALL_TSO;
9951 if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
9952 !(features & NETIF_F_IP_CSUM)) {
9953 netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
9954 features &= ~NETIF_F_TSO;
9955 features &= ~NETIF_F_TSO_ECN;
9958 if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
9959 !(features & NETIF_F_IPV6_CSUM)) {
9960 netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
9961 features &= ~NETIF_F_TSO6;
9964 /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
9965 if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
9966 features &= ~NETIF_F_TSO_MANGLEID;
9968 /* TSO ECN requires that TSO is present as well. */
9969 if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
9970 features &= ~NETIF_F_TSO_ECN;
9972 /* Software GSO depends on SG. */
9973 if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
9974 netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
9975 features &= ~NETIF_F_GSO;
9978 /* GSO partial features require GSO partial be set */
9979 if ((features & dev->gso_partial_features) &&
9980 !(features & NETIF_F_GSO_PARTIAL)) {
9982 "Dropping partially supported GSO features since no GSO partial.\n");
9983 features &= ~dev->gso_partial_features;
9986 if (!(features & NETIF_F_RXCSUM)) {
9987 /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
9988 * successfully merged by hardware must also have the
9989 * checksum verified by hardware. If the user does not
9990 * want to enable RXCSUM, logically, we should disable GRO_HW.
9992 if (features & NETIF_F_GRO_HW) {
9993 netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
9994 features &= ~NETIF_F_GRO_HW;
9998 /* LRO/HW-GRO features cannot be combined with RX-FCS */
9999 if (features & NETIF_F_RXFCS) {
10000 if (features & NETIF_F_LRO) {
10001 netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
10002 features &= ~NETIF_F_LRO;
10005 if (features & NETIF_F_GRO_HW) {
10006 netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
10007 features &= ~NETIF_F_GRO_HW;
10011 if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
10012 netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
10013 features &= ~NETIF_F_LRO;
10016 if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) {
10017 netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
10018 features &= ~NETIF_F_HW_TLS_TX;
10021 if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
10022 netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
10023 features &= ~NETIF_F_HW_TLS_RX;
10026 if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) {
10027 netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n");
10028 features &= ~NETIF_F_GSO_UDP_L4;
10034 int __netdev_update_features(struct net_device *dev)
10036 struct net_device *upper, *lower;
10037 netdev_features_t features;
10038 struct list_head *iter;
10043 features = netdev_get_wanted_features(dev);
10045 if (dev->netdev_ops->ndo_fix_features)
10046 features = dev->netdev_ops->ndo_fix_features(dev, features);
10048 /* driver might be less strict about feature dependencies */
10049 features = netdev_fix_features(dev, features);
10051 /* some features can't be enabled if they're off on an upper device */
10052 netdev_for_each_upper_dev_rcu(dev, upper, iter)
10053 features = netdev_sync_upper_features(dev, upper, features);
10055 if (dev->features == features)
10058 netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
10059 &dev->features, &features);
10061 if (dev->netdev_ops->ndo_set_features)
10062 err = dev->netdev_ops->ndo_set_features(dev, features);
10066 if (unlikely(err < 0)) {
10068 "set_features() failed (%d); wanted %pNF, left %pNF\n",
10069 err, &features, &dev->features);
10070 /* return non-0 since some features might have changed and
10071 * it's better to fire a spurious notification than miss it
10077 /* some features must be disabled on lower devices when disabled
10078 * on an upper device (think: bonding master or bridge)
10080 netdev_for_each_lower_dev(dev, lower, iter)
10081 netdev_sync_lower_features(dev, lower, features);
10084 netdev_features_t diff = features ^ dev->features;
10086 if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
10087 /* udp_tunnel_{get,drop}_rx_info both need
10088 * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
10089 * device, or they won't do anything.
10090 * Thus we need to update dev->features
10091 * *before* calling udp_tunnel_get_rx_info,
10092 * but *after* calling udp_tunnel_drop_rx_info.
10094 if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
10095 dev->features = features;
10096 udp_tunnel_get_rx_info(dev);
10098 udp_tunnel_drop_rx_info(dev);
10102 if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
10103 if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
10104 dev->features = features;
10105 err |= vlan_get_rx_ctag_filter_info(dev);
10107 vlan_drop_rx_ctag_filter_info(dev);
10111 if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
10112 if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
10113 dev->features = features;
10114 err |= vlan_get_rx_stag_filter_info(dev);
10116 vlan_drop_rx_stag_filter_info(dev);
10120 dev->features = features;
10123 return err < 0 ? 0 : 1;
10127 * netdev_update_features - recalculate device features
10128 * @dev: the device to check
10130 * Recalculate dev->features set and send notifications if it
10131 * has changed. Should be called after driver or hardware dependent
10132 * conditions might have changed that influence the features.
10134 void netdev_update_features(struct net_device *dev)
10136 if (__netdev_update_features(dev))
10137 netdev_features_change(dev);
10139 EXPORT_SYMBOL(netdev_update_features);
10142 * netdev_change_features - recalculate device features
10143 * @dev: the device to check
10145 * Recalculate dev->features set and send notifications even
10146 * if they have not changed. Should be called instead of
10147 * netdev_update_features() if also dev->vlan_features might
10148 * have changed to allow the changes to be propagated to stacked
10151 void netdev_change_features(struct net_device *dev)
10153 __netdev_update_features(dev);
10154 netdev_features_change(dev);
10156 EXPORT_SYMBOL(netdev_change_features);
10159 * netif_stacked_transfer_operstate - transfer operstate
10160 * @rootdev: the root or lower level device to transfer state from
10161 * @dev: the device to transfer operstate to
10163 * Transfer operational state from root to device. This is normally
10164 * called when a stacking relationship exists between the root
10165 * device and the device(a leaf device).
10167 void netif_stacked_transfer_operstate(const struct net_device *rootdev,
10168 struct net_device *dev)
10170 if (rootdev->operstate == IF_OPER_DORMANT)
10171 netif_dormant_on(dev);
10173 netif_dormant_off(dev);
10175 if (rootdev->operstate == IF_OPER_TESTING)
10176 netif_testing_on(dev);
10178 netif_testing_off(dev);
10180 if (netif_carrier_ok(rootdev))
10181 netif_carrier_on(dev);
10183 netif_carrier_off(dev);
10185 EXPORT_SYMBOL(netif_stacked_transfer_operstate);
10187 static int netif_alloc_rx_queues(struct net_device *dev)
10189 unsigned int i, count = dev->num_rx_queues;
10190 struct netdev_rx_queue *rx;
10191 size_t sz = count * sizeof(*rx);
10196 rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10202 for (i = 0; i < count; i++) {
10205 /* XDP RX-queue setup */
10206 err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
10213 /* Rollback successful reg's and free other resources */
10215 xdp_rxq_info_unreg(&rx[i].xdp_rxq);
10221 static void netif_free_rx_queues(struct net_device *dev)
10223 unsigned int i, count = dev->num_rx_queues;
10225 /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
10229 for (i = 0; i < count; i++)
10230 xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
10235 static void netdev_init_one_queue(struct net_device *dev,
10236 struct netdev_queue *queue, void *_unused)
10238 /* Initialize queue lock */
10239 spin_lock_init(&queue->_xmit_lock);
10240 netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
10241 queue->xmit_lock_owner = -1;
10242 netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
10245 dql_init(&queue->dql, HZ);
10249 static void netif_free_tx_queues(struct net_device *dev)
10254 static int netif_alloc_netdev_queues(struct net_device *dev)
10256 unsigned int count = dev->num_tx_queues;
10257 struct netdev_queue *tx;
10258 size_t sz = count * sizeof(*tx);
10260 if (count < 1 || count > 0xffff)
10263 tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
10269 netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
10270 spin_lock_init(&dev->tx_global_lock);
10275 void netif_tx_stop_all_queues(struct net_device *dev)
10279 for (i = 0; i < dev->num_tx_queues; i++) {
10280 struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
10282 netif_tx_stop_queue(txq);
10285 EXPORT_SYMBOL(netif_tx_stop_all_queues);
10287 static int netdev_do_alloc_pcpu_stats(struct net_device *dev)
10291 /* Drivers implementing ndo_get_peer_dev must support tstat
10292 * accounting, so that skb_do_redirect() can bump the dev's
10293 * RX stats upon network namespace switch.
10295 if (dev->netdev_ops->ndo_get_peer_dev &&
10296 dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS)
10297 return -EOPNOTSUPP;
10299 switch (dev->pcpu_stat_type) {
10300 case NETDEV_PCPU_STAT_NONE:
10302 case NETDEV_PCPU_STAT_LSTATS:
10303 v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
10305 case NETDEV_PCPU_STAT_TSTATS:
10306 v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
10308 case NETDEV_PCPU_STAT_DSTATS:
10309 v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
10315 return v ? 0 : -ENOMEM;
10318 static void netdev_do_free_pcpu_stats(struct net_device *dev)
10320 switch (dev->pcpu_stat_type) {
10321 case NETDEV_PCPU_STAT_NONE:
10323 case NETDEV_PCPU_STAT_LSTATS:
10324 free_percpu(dev->lstats);
10326 case NETDEV_PCPU_STAT_TSTATS:
10327 free_percpu(dev->tstats);
10329 case NETDEV_PCPU_STAT_DSTATS:
10330 free_percpu(dev->dstats);
10335 static void netdev_free_phy_link_topology(struct net_device *dev)
10337 struct phy_link_topology *topo = dev->link_topo;
10339 if (IS_ENABLED(CONFIG_PHYLIB) && topo) {
10340 xa_destroy(&topo->phys);
10342 dev->link_topo = NULL;
10347 * register_netdevice() - register a network device
10348 * @dev: device to register
10350 * Take a prepared network device structure and make it externally accessible.
10351 * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
10352 * Callers must hold the rtnl lock - you may want register_netdev()
10355 int register_netdevice(struct net_device *dev)
10358 struct net *net = dev_net(dev);
10360 BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
10361 NETDEV_FEATURE_COUNT);
10362 BUG_ON(dev_boot_phase);
10367 /* When net_device's are persistent, this will be fatal. */
10368 BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
10371 ret = ethtool_check_ops(dev->ethtool_ops);
10375 /* rss ctx ID 0 is reserved for the default context, start from 1 */
10376 xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1);
10377 mutex_init(&dev->ethtool->rss_lock);
10379 spin_lock_init(&dev->addr_list_lock);
10380 netdev_set_addr_lockdep_class(dev);
10382 ret = dev_get_valid_name(net, dev, dev->name);
10387 dev->name_node = netdev_name_node_head_alloc(dev);
10388 if (!dev->name_node)
10391 /* Init, if this function is available */
10392 if (dev->netdev_ops->ndo_init) {
10393 ret = dev->netdev_ops->ndo_init(dev);
10397 goto err_free_name;
10401 if (((dev->hw_features | dev->features) &
10402 NETIF_F_HW_VLAN_CTAG_FILTER) &&
10403 (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
10404 !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
10405 netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
10410 ret = netdev_do_alloc_pcpu_stats(dev);
10414 ret = dev_index_reserve(net, dev->ifindex);
10416 goto err_free_pcpu;
10417 dev->ifindex = ret;
10419 /* Transfer changeable features to wanted_features and enable
10420 * software offloads (GSO and GRO).
10422 dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
10423 dev->features |= NETIF_F_SOFT_FEATURES;
10425 if (dev->udp_tunnel_nic_info) {
10426 dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10427 dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
10430 dev->wanted_features = dev->features & dev->hw_features;
10432 if (!(dev->flags & IFF_LOOPBACK))
10433 dev->hw_features |= NETIF_F_NOCACHE_COPY;
10435 /* If IPv4 TCP segmentation offload is supported we should also
10436 * allow the device to enable segmenting the frame with the option
10437 * of ignoring a static IP ID value. This doesn't enable the
10438 * feature itself but allows the user to enable it later.
10440 if (dev->hw_features & NETIF_F_TSO)
10441 dev->hw_features |= NETIF_F_TSO_MANGLEID;
10442 if (dev->vlan_features & NETIF_F_TSO)
10443 dev->vlan_features |= NETIF_F_TSO_MANGLEID;
10444 if (dev->mpls_features & NETIF_F_TSO)
10445 dev->mpls_features |= NETIF_F_TSO_MANGLEID;
10446 if (dev->hw_enc_features & NETIF_F_TSO)
10447 dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
10449 /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
10451 dev->vlan_features |= NETIF_F_HIGHDMA;
10453 /* Make NETIF_F_SG inheritable to tunnel devices.
10455 dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
10457 /* Make NETIF_F_SG inheritable to MPLS.
10459 dev->mpls_features |= NETIF_F_SG;
10461 ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
10462 ret = notifier_to_errno(ret);
10464 goto err_ifindex_release;
10466 ret = netdev_register_kobject(dev);
10468 WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED);
10471 goto err_uninit_notify;
10473 __netdev_update_features(dev);
10476 * Default initial state at registry is that the
10477 * device is present.
10480 set_bit(__LINK_STATE_PRESENT, &dev->state);
10482 linkwatch_init_dev(dev);
10484 dev_init_scheduler(dev);
10486 netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
10487 list_netdevice(dev);
10489 add_device_randomness(dev->dev_addr, dev->addr_len);
10491 /* If the device has permanent device address, driver should
10492 * set dev_addr and also addr_assign_type should be set to
10493 * NET_ADDR_PERM (default value).
10495 if (dev->addr_assign_type == NET_ADDR_PERM)
10496 memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
10498 /* Notify protocols, that a new device appeared. */
10499 ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
10500 ret = notifier_to_errno(ret);
10502 /* Expect explicit free_netdev() on failure */
10503 dev->needs_free_netdev = false;
10504 unregister_netdevice_queue(dev, NULL);
10508 * Prevent userspace races by waiting until the network
10509 * device is fully setup before sending notifications.
10511 if (!dev->rtnl_link_ops ||
10512 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
10513 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
10519 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
10520 err_ifindex_release:
10521 dev_index_release(net, dev->ifindex);
10523 netdev_do_free_pcpu_stats(dev);
10525 if (dev->netdev_ops->ndo_uninit)
10526 dev->netdev_ops->ndo_uninit(dev);
10527 if (dev->priv_destructor)
10528 dev->priv_destructor(dev);
10530 netdev_name_node_free(dev->name_node);
10533 EXPORT_SYMBOL(register_netdevice);
10535 /* Initialize the core of a dummy net device.
10536 * This is useful if you are calling this function after alloc_netdev(),
10537 * since it does not memset the net_device fields.
10539 static void init_dummy_netdev_core(struct net_device *dev)
10541 /* make sure we BUG if trying to hit standard
10542 * register/unregister code path
10544 dev->reg_state = NETREG_DUMMY;
10546 /* NAPI wants this */
10547 INIT_LIST_HEAD(&dev->napi_list);
10549 /* a dummy interface is started by default */
10550 set_bit(__LINK_STATE_PRESENT, &dev->state);
10551 set_bit(__LINK_STATE_START, &dev->state);
10553 /* napi_busy_loop stats accounting wants this */
10554 dev_net_set(dev, &init_net);
10556 /* Note : We dont allocate pcpu_refcnt for dummy devices,
10557 * because users of this 'device' dont need to change
10563 * init_dummy_netdev - init a dummy network device for NAPI
10564 * @dev: device to init
10566 * This takes a network device structure and initializes the minimum
10567 * amount of fields so it can be used to schedule NAPI polls without
10568 * registering a full blown interface. This is to be used by drivers
10569 * that need to tie several hardware interfaces to a single NAPI
10570 * poll scheduler due to HW limitations.
10572 void init_dummy_netdev(struct net_device *dev)
10574 /* Clear everything. Note we don't initialize spinlocks
10575 * as they aren't supposed to be taken by any of the
10576 * NAPI code and this dummy netdev is supposed to be
10577 * only ever used for NAPI polls
10579 memset(dev, 0, sizeof(struct net_device));
10580 init_dummy_netdev_core(dev);
10582 EXPORT_SYMBOL_GPL(init_dummy_netdev);
10585 * register_netdev - register a network device
10586 * @dev: device to register
10588 * Take a completed network device structure and add it to the kernel
10589 * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
10590 * chain. 0 is returned on success. A negative errno code is returned
10591 * on a failure to set up the device, or if the name is a duplicate.
10593 * This is a wrapper around register_netdevice that takes the rtnl semaphore
10594 * and expands the device name if you passed a format string to
10597 int register_netdev(struct net_device *dev)
10601 if (rtnl_lock_killable())
10603 err = register_netdevice(dev);
10607 EXPORT_SYMBOL(register_netdev);
10609 int netdev_refcnt_read(const struct net_device *dev)
10611 #ifdef CONFIG_PCPU_DEV_REFCNT
10614 for_each_possible_cpu(i)
10615 refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
10618 return refcount_read(&dev->dev_refcnt);
10621 EXPORT_SYMBOL(netdev_refcnt_read);
10623 int netdev_unregister_timeout_secs __read_mostly = 10;
10625 #define WAIT_REFS_MIN_MSECS 1
10626 #define WAIT_REFS_MAX_MSECS 250
10628 * netdev_wait_allrefs_any - wait until all references are gone.
10629 * @list: list of net_devices to wait on
10631 * This is called when unregistering network devices.
10633 * Any protocol or device that holds a reference should register
10634 * for netdevice notification, and cleanup and put back the
10635 * reference if they receive an UNREGISTER event.
10636 * We can get stuck here if buggy protocols don't correctly
10639 static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
10641 unsigned long rebroadcast_time, warning_time;
10642 struct net_device *dev;
10645 rebroadcast_time = warning_time = jiffies;
10647 list_for_each_entry(dev, list, todo_list)
10648 if (netdev_refcnt_read(dev) == 1)
10652 if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
10655 /* Rebroadcast unregister notification */
10656 list_for_each_entry(dev, list, todo_list)
10657 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
10663 list_for_each_entry(dev, list, todo_list)
10664 if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
10666 /* We must not have linkwatch events
10667 * pending on unregister. If this
10668 * happens, we simply run the queue
10669 * unscheduled, resulting in a noop
10672 linkwatch_run_queue();
10678 rebroadcast_time = jiffies;
10684 wait = WAIT_REFS_MIN_MSECS;
10687 wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
10690 list_for_each_entry(dev, list, todo_list)
10691 if (netdev_refcnt_read(dev) == 1)
10694 if (time_after(jiffies, warning_time +
10695 READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
10696 list_for_each_entry(dev, list, todo_list) {
10697 pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
10698 dev->name, netdev_refcnt_read(dev));
10699 ref_tracker_dir_print(&dev->refcnt_tracker, 10);
10702 warning_time = jiffies;
10707 /* The sequence is:
10711 * register_netdevice(x1);
10712 * register_netdevice(x2);
10714 * unregister_netdevice(y1);
10715 * unregister_netdevice(y2);
10721 * We are invoked by rtnl_unlock().
10722 * This allows us to deal with problems:
10723 * 1) We can delete sysfs objects which invoke hotplug
10724 * without deadlocking with linkwatch via keventd.
10725 * 2) Since we run with the RTNL semaphore not held, we can sleep
10726 * safely in order to wait for the netdev refcnt to drop to zero.
10728 * We must not return until all unregister events added during
10729 * the interval the lock was held have been completed.
10731 void netdev_run_todo(void)
10733 struct net_device *dev, *tmp;
10734 struct list_head list;
10736 #ifdef CONFIG_LOCKDEP
10737 struct list_head unlink_list;
10739 list_replace_init(&net_unlink_list, &unlink_list);
10741 while (!list_empty(&unlink_list)) {
10742 struct net_device *dev = list_first_entry(&unlink_list,
10745 list_del_init(&dev->unlink_list);
10746 dev->nested_level = dev->lower_level - 1;
10750 /* Snapshot list, allow later requests */
10751 list_replace_init(&net_todo_list, &list);
10755 /* Wait for rcu callbacks to finish before next phase */
10756 if (!list_empty(&list))
10759 list_for_each_entry_safe(dev, tmp, &list, todo_list) {
10760 if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
10761 netdev_WARN(dev, "run_todo but not unregistering\n");
10762 list_del(&dev->todo_list);
10766 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED);
10767 linkwatch_sync_dev(dev);
10771 while (!list_empty(&list)) {
10772 dev = netdev_wait_allrefs_any(&list);
10773 list_del(&dev->todo_list);
10776 BUG_ON(netdev_refcnt_read(dev) != 1);
10777 BUG_ON(!list_empty(&dev->ptype_all));
10778 BUG_ON(!list_empty(&dev->ptype_specific));
10779 WARN_ON(rcu_access_pointer(dev->ip_ptr));
10780 WARN_ON(rcu_access_pointer(dev->ip6_ptr));
10782 netdev_do_free_pcpu_stats(dev);
10783 if (dev->priv_destructor)
10784 dev->priv_destructor(dev);
10785 if (dev->needs_free_netdev)
10790 /* Free network device */
10791 kobject_put(&dev->dev.kobj);
10793 if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count))
10794 wake_up(&netdev_unregistering_wq);
10797 /* Collate per-cpu network dstats statistics
10799 * Read per-cpu network statistics from dev->dstats and populate the related
10802 static void dev_fetch_dstats(struct rtnl_link_stats64 *s,
10803 const struct pcpu_dstats __percpu *dstats)
10807 for_each_possible_cpu(cpu) {
10808 u64 rx_packets, rx_bytes, rx_drops;
10809 u64 tx_packets, tx_bytes, tx_drops;
10810 const struct pcpu_dstats *stats;
10811 unsigned int start;
10813 stats = per_cpu_ptr(dstats, cpu);
10815 start = u64_stats_fetch_begin(&stats->syncp);
10816 rx_packets = u64_stats_read(&stats->rx_packets);
10817 rx_bytes = u64_stats_read(&stats->rx_bytes);
10818 rx_drops = u64_stats_read(&stats->rx_drops);
10819 tx_packets = u64_stats_read(&stats->tx_packets);
10820 tx_bytes = u64_stats_read(&stats->tx_bytes);
10821 tx_drops = u64_stats_read(&stats->tx_drops);
10822 } while (u64_stats_fetch_retry(&stats->syncp, start));
10824 s->rx_packets += rx_packets;
10825 s->rx_bytes += rx_bytes;
10826 s->rx_dropped += rx_drops;
10827 s->tx_packets += tx_packets;
10828 s->tx_bytes += tx_bytes;
10829 s->tx_dropped += tx_drops;
10833 /* ndo_get_stats64 implementation for dtstats-based accounting.
10835 * Populate @s from dev->stats and dev->dstats. This is used internally by the
10836 * core for NETDEV_PCPU_STAT_DSTAT-type stats collection.
10838 static void dev_get_dstats64(const struct net_device *dev,
10839 struct rtnl_link_stats64 *s)
10841 netdev_stats_to_stats64(s, &dev->stats);
10842 dev_fetch_dstats(s, dev->dstats);
10845 /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
10846 * all the same fields in the same order as net_device_stats, with only
10847 * the type differing, but rtnl_link_stats64 may have additional fields
10848 * at the end for newer counters.
10850 void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
10851 const struct net_device_stats *netdev_stats)
10853 size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
10854 const atomic_long_t *src = (atomic_long_t *)netdev_stats;
10855 u64 *dst = (u64 *)stats64;
10857 BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
10858 for (i = 0; i < n; i++)
10859 dst[i] = (unsigned long)atomic_long_read(&src[i]);
10860 /* zero out counters that only exist in rtnl_link_stats64 */
10861 memset((char *)stats64 + n * sizeof(u64), 0,
10862 sizeof(*stats64) - n * sizeof(u64));
10864 EXPORT_SYMBOL(netdev_stats_to_stats64);
10866 static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc(
10867 struct net_device *dev)
10869 struct net_device_core_stats __percpu *p;
10871 p = alloc_percpu_gfp(struct net_device_core_stats,
10872 GFP_ATOMIC | __GFP_NOWARN);
10874 if (p && cmpxchg(&dev->core_stats, NULL, p))
10877 /* This READ_ONCE() pairs with the cmpxchg() above */
10878 return READ_ONCE(dev->core_stats);
10881 noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset)
10883 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10884 struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats);
10885 unsigned long __percpu *field;
10887 if (unlikely(!p)) {
10888 p = netdev_core_stats_alloc(dev);
10893 field = (unsigned long __percpu *)((void __percpu *)p + offset);
10894 this_cpu_inc(*field);
10896 EXPORT_SYMBOL_GPL(netdev_core_stats_inc);
10899 * dev_get_stats - get network device statistics
10900 * @dev: device to get statistics from
10901 * @storage: place to store stats
10903 * Get network statistics from device. Return @storage.
10904 * The device driver may provide its own method by setting
10905 * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
10906 * otherwise the internal statistics structure is used.
10908 struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
10909 struct rtnl_link_stats64 *storage)
10911 const struct net_device_ops *ops = dev->netdev_ops;
10912 const struct net_device_core_stats __percpu *p;
10914 if (ops->ndo_get_stats64) {
10915 memset(storage, 0, sizeof(*storage));
10916 ops->ndo_get_stats64(dev, storage);
10917 } else if (ops->ndo_get_stats) {
10918 netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
10919 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) {
10920 dev_get_tstats64(dev, storage);
10921 } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) {
10922 dev_get_dstats64(dev, storage);
10924 netdev_stats_to_stats64(storage, &dev->stats);
10927 /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
10928 p = READ_ONCE(dev->core_stats);
10930 const struct net_device_core_stats *core_stats;
10933 for_each_possible_cpu(i) {
10934 core_stats = per_cpu_ptr(p, i);
10935 storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
10936 storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
10937 storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
10938 storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
10943 EXPORT_SYMBOL(dev_get_stats);
10946 * dev_fetch_sw_netstats - get per-cpu network device statistics
10947 * @s: place to store stats
10948 * @netstats: per-cpu network stats to read from
10950 * Read per-cpu network statistics and populate the related fields in @s.
10952 void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
10953 const struct pcpu_sw_netstats __percpu *netstats)
10957 for_each_possible_cpu(cpu) {
10958 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
10959 const struct pcpu_sw_netstats *stats;
10960 unsigned int start;
10962 stats = per_cpu_ptr(netstats, cpu);
10964 start = u64_stats_fetch_begin(&stats->syncp);
10965 rx_packets = u64_stats_read(&stats->rx_packets);
10966 rx_bytes = u64_stats_read(&stats->rx_bytes);
10967 tx_packets = u64_stats_read(&stats->tx_packets);
10968 tx_bytes = u64_stats_read(&stats->tx_bytes);
10969 } while (u64_stats_fetch_retry(&stats->syncp, start));
10971 s->rx_packets += rx_packets;
10972 s->rx_bytes += rx_bytes;
10973 s->tx_packets += tx_packets;
10974 s->tx_bytes += tx_bytes;
10977 EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
10980 * dev_get_tstats64 - ndo_get_stats64 implementation
10981 * @dev: device to get statistics from
10982 * @s: place to store stats
10984 * Populate @s from dev->stats and dev->tstats. Can be used as
10985 * ndo_get_stats64() callback.
10987 void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
10989 netdev_stats_to_stats64(s, &dev->stats);
10990 dev_fetch_sw_netstats(s, dev->tstats);
10992 EXPORT_SYMBOL_GPL(dev_get_tstats64);
10994 struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
10996 struct netdev_queue *queue = dev_ingress_queue(dev);
10998 #ifdef CONFIG_NET_CLS_ACT
11001 queue = kzalloc(sizeof(*queue), GFP_KERNEL);
11004 netdev_init_one_queue(dev, queue, NULL);
11005 RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
11006 RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
11007 rcu_assign_pointer(dev->ingress_queue, queue);
11012 static const struct ethtool_ops default_ethtool_ops;
11014 void netdev_set_default_ethtool_ops(struct net_device *dev,
11015 const struct ethtool_ops *ops)
11017 if (dev->ethtool_ops == &default_ethtool_ops)
11018 dev->ethtool_ops = ops;
11020 EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
11023 * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
11024 * @dev: netdev to enable the IRQ coalescing on
11026 * Sets a conservative default for SW IRQ coalescing. Users can use
11027 * sysfs attributes to override the default values.
11029 void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
11031 WARN_ON(dev->reg_state == NETREG_REGISTERED);
11033 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
11034 dev->gro_flush_timeout = 20000;
11035 dev->napi_defer_hard_irqs = 1;
11038 EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
11041 * alloc_netdev_mqs - allocate network device
11042 * @sizeof_priv: size of private data to allocate space for
11043 * @name: device name format string
11044 * @name_assign_type: origin of device name
11045 * @setup: callback to initialize device
11046 * @txqs: the number of TX subqueues to allocate
11047 * @rxqs: the number of RX subqueues to allocate
11049 * Allocates a struct net_device with private data area for driver use
11050 * and performs basic initialization. Also allocates subqueue structs
11051 * for each queue on the device.
11053 struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
11054 unsigned char name_assign_type,
11055 void (*setup)(struct net_device *),
11056 unsigned int txqs, unsigned int rxqs)
11058 struct net_device *dev;
11060 BUG_ON(strlen(name) >= sizeof(dev->name));
11063 pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
11068 pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
11072 dev = kvzalloc(struct_size(dev, priv, sizeof_priv),
11073 GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
11077 dev->priv_len = sizeof_priv;
11079 ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
11080 #ifdef CONFIG_PCPU_DEV_REFCNT
11081 dev->pcpu_refcnt = alloc_percpu(int);
11082 if (!dev->pcpu_refcnt)
11086 refcount_set(&dev->dev_refcnt, 1);
11089 if (dev_addr_init(dev))
11095 dev_net_set(dev, &init_net);
11097 dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
11098 dev->xdp_zc_max_segs = 1;
11099 dev->gso_max_segs = GSO_MAX_SEGS;
11100 dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
11101 dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
11102 dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
11103 dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
11104 dev->tso_max_segs = TSO_MAX_SEGS;
11105 dev->upper_level = 1;
11106 dev->lower_level = 1;
11107 #ifdef CONFIG_LOCKDEP
11108 dev->nested_level = 0;
11109 INIT_LIST_HEAD(&dev->unlink_list);
11112 INIT_LIST_HEAD(&dev->napi_list);
11113 INIT_LIST_HEAD(&dev->unreg_list);
11114 INIT_LIST_HEAD(&dev->close_list);
11115 INIT_LIST_HEAD(&dev->link_watch_list);
11116 INIT_LIST_HEAD(&dev->adj_list.upper);
11117 INIT_LIST_HEAD(&dev->adj_list.lower);
11118 INIT_LIST_HEAD(&dev->ptype_all);
11119 INIT_LIST_HEAD(&dev->ptype_specific);
11120 INIT_LIST_HEAD(&dev->net_notifier_list);
11121 #ifdef CONFIG_NET_SCHED
11122 hash_init(dev->qdisc_hash);
11125 dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
11128 if (!dev->tx_queue_len) {
11129 dev->priv_flags |= IFF_NO_QUEUE;
11130 dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
11133 dev->num_tx_queues = txqs;
11134 dev->real_num_tx_queues = txqs;
11135 if (netif_alloc_netdev_queues(dev))
11138 dev->num_rx_queues = rxqs;
11139 dev->real_num_rx_queues = rxqs;
11140 if (netif_alloc_rx_queues(dev))
11142 dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT);
11146 strscpy(dev->name, name);
11147 dev->name_assign_type = name_assign_type;
11148 dev->group = INIT_NETDEV_GROUP;
11149 if (!dev->ethtool_ops)
11150 dev->ethtool_ops = &default_ethtool_ops;
11152 nf_hook_netdev_init(dev);
11161 #ifdef CONFIG_PCPU_DEV_REFCNT
11162 free_percpu(dev->pcpu_refcnt);
11168 EXPORT_SYMBOL(alloc_netdev_mqs);
11171 * free_netdev - free network device
11174 * This function does the last stage of destroying an allocated device
11175 * interface. The reference to the device object is released. If this
11176 * is the last reference then it will be freed.Must be called in process
11179 void free_netdev(struct net_device *dev)
11181 struct napi_struct *p, *n;
11185 /* When called immediately after register_netdevice() failed the unwind
11186 * handling may still be dismantling the device. Handle that case by
11187 * deferring the free.
11189 if (dev->reg_state == NETREG_UNREGISTERING) {
11191 dev->needs_free_netdev = true;
11195 kfree(dev->ethtool);
11196 netif_free_tx_queues(dev);
11197 netif_free_rx_queues(dev);
11199 kfree(rcu_dereference_protected(dev->ingress_queue, 1));
11201 /* Flush device addresses */
11202 dev_addr_flush(dev);
11204 list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
11207 ref_tracker_dir_exit(&dev->refcnt_tracker);
11208 #ifdef CONFIG_PCPU_DEV_REFCNT
11209 free_percpu(dev->pcpu_refcnt);
11210 dev->pcpu_refcnt = NULL;
11212 free_percpu(dev->core_stats);
11213 dev->core_stats = NULL;
11214 free_percpu(dev->xdp_bulkq);
11215 dev->xdp_bulkq = NULL;
11217 netdev_free_phy_link_topology(dev);
11219 /* Compatibility with error handling in drivers */
11220 if (dev->reg_state == NETREG_UNINITIALIZED ||
11221 dev->reg_state == NETREG_DUMMY) {
11226 BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
11227 WRITE_ONCE(dev->reg_state, NETREG_RELEASED);
11229 /* will free via device release */
11230 put_device(&dev->dev);
11232 EXPORT_SYMBOL(free_netdev);
11235 * alloc_netdev_dummy - Allocate and initialize a dummy net device.
11236 * @sizeof_priv: size of private data to allocate space for
11238 * Return: the allocated net_device on success, NULL otherwise
11240 struct net_device *alloc_netdev_dummy(int sizeof_priv)
11242 return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN,
11243 init_dummy_netdev_core);
11245 EXPORT_SYMBOL_GPL(alloc_netdev_dummy);
11248 * synchronize_net - Synchronize with packet receive processing
11250 * Wait for packets currently being received to be done.
11251 * Does not block later packets from starting.
11253 void synchronize_net(void)
11256 if (rtnl_is_locked())
11257 synchronize_rcu_expedited();
11261 EXPORT_SYMBOL(synchronize_net);
11263 static void netdev_rss_contexts_free(struct net_device *dev)
11265 struct ethtool_rxfh_context *ctx;
11266 unsigned long context;
11268 mutex_lock(&dev->ethtool->rss_lock);
11269 xa_for_each(&dev->ethtool->rss_ctx, context, ctx) {
11270 struct ethtool_rxfh_param rxfh;
11272 rxfh.indir = ethtool_rxfh_context_indir(ctx);
11273 rxfh.key = ethtool_rxfh_context_key(ctx);
11274 rxfh.hfunc = ctx->hfunc;
11275 rxfh.input_xfrm = ctx->input_xfrm;
11276 rxfh.rss_context = context;
11277 rxfh.rss_delete = true;
11279 xa_erase(&dev->ethtool->rss_ctx, context);
11280 if (dev->ethtool_ops->create_rxfh_context)
11281 dev->ethtool_ops->remove_rxfh_context(dev, ctx,
11284 dev->ethtool_ops->set_rxfh(dev, &rxfh, NULL);
11287 xa_destroy(&dev->ethtool->rss_ctx);
11288 mutex_unlock(&dev->ethtool->rss_lock);
11292 * unregister_netdevice_queue - remove device from the kernel
11296 * This function shuts down a device interface and removes it
11297 * from the kernel tables.
11298 * If head not NULL, device is queued to be unregistered later.
11300 * Callers must hold the rtnl semaphore. You may want
11301 * unregister_netdev() instead of this.
11304 void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
11309 list_move_tail(&dev->unreg_list, head);
11313 list_add(&dev->unreg_list, &single);
11314 unregister_netdevice_many(&single);
11317 EXPORT_SYMBOL(unregister_netdevice_queue);
11319 void unregister_netdevice_many_notify(struct list_head *head,
11320 u32 portid, const struct nlmsghdr *nlh)
11322 struct net_device *dev, *tmp;
11323 LIST_HEAD(close_head);
11326 BUG_ON(dev_boot_phase);
11329 if (list_empty(head))
11332 list_for_each_entry_safe(dev, tmp, head, unreg_list) {
11333 /* Some devices call without registering
11334 * for initialization unwind. Remove those
11335 * devices and proceed with the remaining.
11337 if (dev->reg_state == NETREG_UNINITIALIZED) {
11338 pr_debug("unregister_netdevice: device %s/%p never was registered\n",
11342 list_del(&dev->unreg_list);
11345 dev->dismantle = true;
11346 BUG_ON(dev->reg_state != NETREG_REGISTERED);
11349 /* If device is running, close it first. */
11350 list_for_each_entry(dev, head, unreg_list)
11351 list_add_tail(&dev->close_list, &close_head);
11352 dev_close_many(&close_head, true);
11354 list_for_each_entry(dev, head, unreg_list) {
11355 /* And unlink it from device chain. */
11356 unlist_netdevice(dev);
11357 WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING);
11359 flush_all_backlogs();
11363 list_for_each_entry(dev, head, unreg_list) {
11364 struct sk_buff *skb = NULL;
11366 /* Shutdown queueing discipline. */
11368 dev_tcx_uninstall(dev);
11369 dev_xdp_uninstall(dev);
11370 bpf_dev_bound_netdev_unregister(dev);
11372 netdev_offload_xstats_disable_all(dev);
11374 /* Notify protocols, that we are about to destroy
11375 * this device. They should clean all the things.
11377 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11379 if (!dev->rtnl_link_ops ||
11380 dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
11381 skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
11382 GFP_KERNEL, NULL, 0,
11386 * Flush the unicast and multicast chains
11391 netdev_name_node_alt_flush(dev);
11392 netdev_name_node_free(dev->name_node);
11394 netdev_rss_contexts_free(dev);
11396 call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
11398 if (dev->netdev_ops->ndo_uninit)
11399 dev->netdev_ops->ndo_uninit(dev);
11401 mutex_destroy(&dev->ethtool->rss_lock);
11404 rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
11406 /* Notifier chain MUST detach us all upper devices. */
11407 WARN_ON(netdev_has_any_upper_dev(dev));
11408 WARN_ON(netdev_has_any_lower_dev(dev));
11410 /* Remove entries from kobject tree */
11411 netdev_unregister_kobject(dev);
11413 /* Remove XPS queueing entries */
11414 netif_reset_xps_queues_gt(dev, 0);
11420 list_for_each_entry(dev, head, unreg_list) {
11421 netdev_put(dev, &dev->dev_registered_tracker);
11425 atomic_add(cnt, &dev_unreg_count);
11431 * unregister_netdevice_many - unregister many devices
11432 * @head: list of devices
11434 * Note: As most callers use a stack allocated list_head,
11435 * we force a list_del() to make sure stack won't be corrupted later.
11437 void unregister_netdevice_many(struct list_head *head)
11439 unregister_netdevice_many_notify(head, 0, NULL);
11441 EXPORT_SYMBOL(unregister_netdevice_many);
11444 * unregister_netdev - remove device from the kernel
11447 * This function shuts down a device interface and removes it
11448 * from the kernel tables.
11450 * This is just a wrapper for unregister_netdevice that takes
11451 * the rtnl semaphore. In general you want to use this and not
11452 * unregister_netdevice.
11454 void unregister_netdev(struct net_device *dev)
11457 unregister_netdevice(dev);
11460 EXPORT_SYMBOL(unregister_netdev);
11463 * __dev_change_net_namespace - move device to different nethost namespace
11465 * @net: network namespace
11466 * @pat: If not NULL name pattern to try if the current device name
11467 * is already taken in the destination network namespace.
11468 * @new_ifindex: If not zero, specifies device index in the target
11471 * This function shuts down a device interface and moves it
11472 * to a new network namespace. On success 0 is returned, on
11473 * a failure a netagive errno code is returned.
11475 * Callers must hold the rtnl semaphore.
11478 int __dev_change_net_namespace(struct net_device *dev, struct net *net,
11479 const char *pat, int new_ifindex)
11481 struct netdev_name_node *name_node;
11482 struct net *net_old = dev_net(dev);
11483 char new_name[IFNAMSIZ] = {};
11488 /* Don't allow namespace local devices to be moved. */
11490 if (dev->netns_local)
11493 /* Ensure the device has been registered */
11494 if (dev->reg_state != NETREG_REGISTERED)
11497 /* Get out if there is nothing todo */
11499 if (net_eq(net_old, net))
11502 /* Pick the destination device name, and ensure
11503 * we can use it in the destination network namespace.
11506 if (netdev_name_in_use(net, dev->name)) {
11507 /* We get here if we can't use the current device name */
11510 err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST);
11514 /* Check that none of the altnames conflicts. */
11516 netdev_for_each_altname(dev, name_node)
11517 if (netdev_name_in_use(net, name_node->name))
11520 /* Check that new_ifindex isn't used yet. */
11522 err = dev_index_reserve(net, new_ifindex);
11526 /* If there is an ifindex conflict assign a new one */
11527 err = dev_index_reserve(net, dev->ifindex);
11529 err = dev_index_reserve(net, 0);
11536 * And now a mini version of register_netdevice unregister_netdevice.
11539 /* If device is running close it first. */
11542 /* And unlink it from device chain */
11543 unlist_netdevice(dev);
11547 /* Shutdown queueing discipline. */
11550 /* Notify protocols, that we are about to destroy
11551 * this device. They should clean all the things.
11553 * Note that dev->reg_state stays at NETREG_REGISTERED.
11554 * This is wanted because this way 8021q and macvlan know
11555 * the device is just moving and can keep their slaves up.
11557 call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
11560 new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
11562 rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
11566 * Flush the unicast and multicast chains
11571 /* Send a netdev-removed uevent to the old namespace */
11572 kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
11573 netdev_adjacent_del_links(dev);
11575 /* Move per-net netdevice notifiers that are following the netdevice */
11576 move_netdevice_notifiers_dev_net(dev, net);
11578 /* Actually switch the network namespace */
11579 dev_net_set(dev, net);
11580 dev->ifindex = new_ifindex;
11583 /* Rename the netdev to prepared name */
11584 write_seqlock_bh(&netdev_rename_lock);
11585 strscpy(dev->name, new_name, IFNAMSIZ);
11586 write_sequnlock_bh(&netdev_rename_lock);
11589 /* Fixup kobjects */
11590 dev_set_uevent_suppress(&dev->dev, 1);
11591 err = device_rename(&dev->dev, dev->name);
11592 dev_set_uevent_suppress(&dev->dev, 0);
11595 /* Send a netdev-add uevent to the new namespace */
11596 kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
11597 netdev_adjacent_add_links(dev);
11599 /* Adapt owner in case owning user namespace of target network
11600 * namespace is different from the original one.
11602 err = netdev_change_owner(dev, net_old, net);
11605 /* Add the device back in the hashes */
11606 list_netdevice(dev);
11608 /* Notify protocols, that a new device appeared. */
11609 call_netdevice_notifiers(NETDEV_REGISTER, dev);
11612 * Prevent userspace races by waiting until the network
11613 * device is fully setup before sending notifications.
11615 rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
11622 EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
11624 static int dev_cpu_dead(unsigned int oldcpu)
11626 struct sk_buff **list_skb;
11627 struct sk_buff *skb;
11629 struct softnet_data *sd, *oldsd, *remsd = NULL;
11631 local_irq_disable();
11632 cpu = smp_processor_id();
11633 sd = &per_cpu(softnet_data, cpu);
11634 oldsd = &per_cpu(softnet_data, oldcpu);
11636 /* Find end of our completion_queue. */
11637 list_skb = &sd->completion_queue;
11639 list_skb = &(*list_skb)->next;
11640 /* Append completion queue from offline CPU. */
11641 *list_skb = oldsd->completion_queue;
11642 oldsd->completion_queue = NULL;
11644 /* Append output queue from offline CPU. */
11645 if (oldsd->output_queue) {
11646 *sd->output_queue_tailp = oldsd->output_queue;
11647 sd->output_queue_tailp = oldsd->output_queue_tailp;
11648 oldsd->output_queue = NULL;
11649 oldsd->output_queue_tailp = &oldsd->output_queue;
11651 /* Append NAPI poll list from offline CPU, with one exception :
11652 * process_backlog() must be called by cpu owning percpu backlog.
11653 * We properly handle process_queue & input_pkt_queue later.
11655 while (!list_empty(&oldsd->poll_list)) {
11656 struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
11657 struct napi_struct,
11660 list_del_init(&napi->poll_list);
11661 if (napi->poll == process_backlog)
11662 napi->state &= NAPIF_STATE_THREADED;
11664 ____napi_schedule(sd, napi);
11667 raise_softirq_irqoff(NET_TX_SOFTIRQ);
11668 local_irq_enable();
11670 if (!use_backlog_threads()) {
11672 remsd = oldsd->rps_ipi_list;
11673 oldsd->rps_ipi_list = NULL;
11675 /* send out pending IPI's on offline CPU */
11676 net_rps_send_ipi(remsd);
11679 /* Process offline CPU's input_pkt_queue */
11680 while ((skb = __skb_dequeue(&oldsd->process_queue))) {
11682 rps_input_queue_head_incr(oldsd);
11684 while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
11686 rps_input_queue_head_incr(oldsd);
11693 * netdev_increment_features - increment feature set by one
11694 * @all: current feature set
11695 * @one: new feature set
11696 * @mask: mask feature set
11698 * Computes a new feature set after adding a device with feature set
11699 * @one to the master device with current feature set @all. Will not
11700 * enable anything that is off in @mask. Returns the new feature set.
11702 netdev_features_t netdev_increment_features(netdev_features_t all,
11703 netdev_features_t one, netdev_features_t mask)
11705 if (mask & NETIF_F_HW_CSUM)
11706 mask |= NETIF_F_CSUM_MASK;
11707 mask |= NETIF_F_VLAN_CHALLENGED;
11709 all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
11710 all &= one | ~NETIF_F_ALL_FOR_ALL;
11712 /* If one device supports hw checksumming, set for all. */
11713 if (all & NETIF_F_HW_CSUM)
11714 all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
11718 EXPORT_SYMBOL(netdev_increment_features);
11720 static struct hlist_head * __net_init netdev_create_hash(void)
11723 struct hlist_head *hash;
11725 hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
11727 for (i = 0; i < NETDEV_HASHENTRIES; i++)
11728 INIT_HLIST_HEAD(&hash[i]);
11733 /* Initialize per network namespace state */
11734 static int __net_init netdev_init(struct net *net)
11736 BUILD_BUG_ON(GRO_HASH_BUCKETS >
11737 8 * sizeof_field(struct napi_struct, gro_bitmask));
11739 INIT_LIST_HEAD(&net->dev_base_head);
11741 net->dev_name_head = netdev_create_hash();
11742 if (net->dev_name_head == NULL)
11745 net->dev_index_head = netdev_create_hash();
11746 if (net->dev_index_head == NULL)
11749 xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
11751 RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
11756 kfree(net->dev_name_head);
11762 * netdev_drivername - network driver for the device
11763 * @dev: network device
11765 * Determine network driver for device.
11767 const char *netdev_drivername(const struct net_device *dev)
11769 const struct device_driver *driver;
11770 const struct device *parent;
11771 const char *empty = "";
11773 parent = dev->dev.parent;
11777 driver = parent->driver;
11778 if (driver && driver->name)
11779 return driver->name;
11783 static void __netdev_printk(const char *level, const struct net_device *dev,
11784 struct va_format *vaf)
11786 if (dev && dev->dev.parent) {
11787 dev_printk_emit(level[1] - '0',
11790 dev_driver_string(dev->dev.parent),
11791 dev_name(dev->dev.parent),
11792 netdev_name(dev), netdev_reg_state(dev),
11795 printk("%s%s%s: %pV",
11796 level, netdev_name(dev), netdev_reg_state(dev), vaf);
11798 printk("%s(NULL net_device): %pV", level, vaf);
11802 void netdev_printk(const char *level, const struct net_device *dev,
11803 const char *format, ...)
11805 struct va_format vaf;
11808 va_start(args, format);
11813 __netdev_printk(level, dev, &vaf);
11817 EXPORT_SYMBOL(netdev_printk);
11819 #define define_netdev_printk_level(func, level) \
11820 void func(const struct net_device *dev, const char *fmt, ...) \
11822 struct va_format vaf; \
11825 va_start(args, fmt); \
11830 __netdev_printk(level, dev, &vaf); \
11834 EXPORT_SYMBOL(func);
11836 define_netdev_printk_level(netdev_emerg, KERN_EMERG);
11837 define_netdev_printk_level(netdev_alert, KERN_ALERT);
11838 define_netdev_printk_level(netdev_crit, KERN_CRIT);
11839 define_netdev_printk_level(netdev_err, KERN_ERR);
11840 define_netdev_printk_level(netdev_warn, KERN_WARNING);
11841 define_netdev_printk_level(netdev_notice, KERN_NOTICE);
11842 define_netdev_printk_level(netdev_info, KERN_INFO);
11844 static void __net_exit netdev_exit(struct net *net)
11846 kfree(net->dev_name_head);
11847 kfree(net->dev_index_head);
11848 xa_destroy(&net->dev_by_index);
11849 if (net != &init_net)
11850 WARN_ON_ONCE(!list_empty(&net->dev_base_head));
11853 static struct pernet_operations __net_initdata netdev_net_ops = {
11854 .init = netdev_init,
11855 .exit = netdev_exit,
11858 static void __net_exit default_device_exit_net(struct net *net)
11860 struct netdev_name_node *name_node, *tmp;
11861 struct net_device *dev, *aux;
11863 * Push all migratable network devices back to the
11864 * initial network namespace
11867 for_each_netdev_safe(net, dev, aux) {
11869 char fb_name[IFNAMSIZ];
11871 /* Ignore unmoveable devices (i.e. loopback) */
11872 if (dev->netns_local)
11875 /* Leave virtual devices for the generic cleanup */
11876 if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
11879 /* Push remaining network devices to init_net */
11880 snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
11881 if (netdev_name_in_use(&init_net, fb_name))
11882 snprintf(fb_name, IFNAMSIZ, "dev%%d");
11884 netdev_for_each_altname_safe(dev, name_node, tmp)
11885 if (netdev_name_in_use(&init_net, name_node->name))
11886 __netdev_name_node_alt_destroy(name_node);
11888 err = dev_change_net_namespace(dev, &init_net, fb_name);
11890 pr_emerg("%s: failed to move %s to init_net: %d\n",
11891 __func__, dev->name, err);
11897 static void __net_exit default_device_exit_batch(struct list_head *net_list)
11899 /* At exit all network devices most be removed from a network
11900 * namespace. Do this in the reverse order of registration.
11901 * Do this across as many network namespaces as possible to
11902 * improve batching efficiency.
11904 struct net_device *dev;
11906 LIST_HEAD(dev_kill_list);
11909 list_for_each_entry(net, net_list, exit_list) {
11910 default_device_exit_net(net);
11914 list_for_each_entry(net, net_list, exit_list) {
11915 for_each_netdev_reverse(net, dev) {
11916 if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
11917 dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
11919 unregister_netdevice_queue(dev, &dev_kill_list);
11922 unregister_netdevice_many(&dev_kill_list);
11926 static struct pernet_operations __net_initdata default_device_ops = {
11927 .exit_batch = default_device_exit_batch,
11930 static void __init net_dev_struct_check(void)
11932 /* TX read-mostly hotpath */
11933 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast);
11934 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops);
11935 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops);
11936 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx);
11937 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues);
11938 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size);
11939 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size);
11940 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs);
11941 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features);
11942 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc);
11943 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu);
11944 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom);
11945 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq);
11947 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps);
11949 #ifdef CONFIG_NETFILTER_EGRESS
11950 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress);
11952 #ifdef CONFIG_NET_XGRESS
11953 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress);
11955 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160);
11957 /* TXRX read-mostly hotpath */
11958 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats);
11959 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state);
11960 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags);
11961 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len);
11962 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features);
11963 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr);
11964 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46);
11966 /* RX read-mostly hotpath */
11967 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific);
11968 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex);
11969 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues);
11970 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx);
11971 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_flush_timeout);
11972 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, napi_defer_hard_irqs);
11973 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size);
11974 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size);
11975 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler);
11976 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data);
11977 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net);
11978 #ifdef CONFIG_NETPOLL
11979 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo);
11981 #ifdef CONFIG_NET_XGRESS
11982 CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress);
11984 CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 104);
11988 * Initialize the DEV module. At boot time this walks the device list and
11989 * unhooks any devices that fail to initialise (normally hardware not
11990 * present) and leaves us with a valid list of present and active devices.
11994 /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */
11995 #define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE)
11997 static int net_page_pool_create(int cpuid)
11999 #if IS_ENABLED(CONFIG_PAGE_POOL)
12000 struct page_pool_params page_pool_params = {
12001 .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE,
12002 .flags = PP_FLAG_SYSTEM_POOL,
12003 .nid = cpu_to_mem(cpuid),
12005 struct page_pool *pp_ptr;
12007 pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid);
12008 if (IS_ERR(pp_ptr))
12011 per_cpu(system_page_pool, cpuid) = pp_ptr;
12016 static int backlog_napi_should_run(unsigned int cpu)
12018 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12019 struct napi_struct *napi = &sd->backlog;
12021 return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
12024 static void run_backlog_napi(unsigned int cpu)
12026 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12028 napi_threaded_poll_loop(&sd->backlog);
12031 static void backlog_napi_setup(unsigned int cpu)
12033 struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
12034 struct napi_struct *napi = &sd->backlog;
12036 napi->thread = this_cpu_read(backlog_napi);
12037 set_bit(NAPI_STATE_THREADED, &napi->state);
12040 static struct smp_hotplug_thread backlog_threads = {
12041 .store = &backlog_napi,
12042 .thread_should_run = backlog_napi_should_run,
12043 .thread_fn = run_backlog_napi,
12044 .thread_comm = "backlog_napi/%u",
12045 .setup = backlog_napi_setup,
12049 * This is called single threaded during boot, so no need
12050 * to take the rtnl semaphore.
12052 static int __init net_dev_init(void)
12054 int i, rc = -ENOMEM;
12056 BUG_ON(!dev_boot_phase);
12058 net_dev_struct_check();
12060 if (dev_proc_init())
12063 if (netdev_kobject_init())
12066 for (i = 0; i < PTYPE_HASH_SIZE; i++)
12067 INIT_LIST_HEAD(&ptype_base[i]);
12069 if (register_pernet_subsys(&netdev_net_ops))
12073 * Initialise the packet receive queues.
12076 for_each_possible_cpu(i) {
12077 struct work_struct *flush = per_cpu_ptr(&flush_works, i);
12078 struct softnet_data *sd = &per_cpu(softnet_data, i);
12080 INIT_WORK(flush, flush_backlog);
12082 skb_queue_head_init(&sd->input_pkt_queue);
12083 skb_queue_head_init(&sd->process_queue);
12084 #ifdef CONFIG_XFRM_OFFLOAD
12085 skb_queue_head_init(&sd->xfrm_backlog);
12087 INIT_LIST_HEAD(&sd->poll_list);
12088 sd->output_queue_tailp = &sd->output_queue;
12090 INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
12093 INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
12094 spin_lock_init(&sd->defer_lock);
12096 init_gro_hash(&sd->backlog);
12097 sd->backlog.poll = process_backlog;
12098 sd->backlog.weight = weight_p;
12099 INIT_LIST_HEAD(&sd->backlog.poll_list);
12101 if (net_page_pool_create(i))
12104 if (use_backlog_threads())
12105 smpboot_register_percpu_thread(&backlog_threads);
12107 dev_boot_phase = 0;
12109 /* The loopback device is special if any other network devices
12110 * is present in a network namespace the loopback device must
12111 * be present. Since we now dynamically allocate and free the
12112 * loopback device ensure this invariant is maintained by
12113 * keeping the loopback device as the first device on the
12114 * list of network devices. Ensuring the loopback devices
12115 * is the first device that appears and the last network device
12118 if (register_pernet_device(&loopback_net_ops))
12121 if (register_pernet_device(&default_device_ops))
12124 open_softirq(NET_TX_SOFTIRQ, net_tx_action);
12125 open_softirq(NET_RX_SOFTIRQ, net_rx_action);
12127 rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
12128 NULL, dev_cpu_dead);
12132 /* avoid static key IPIs to isolated CPUs */
12133 if (housekeeping_enabled(HK_TYPE_MISC))
12134 net_enable_timestamp();
12137 for_each_possible_cpu(i) {
12138 struct page_pool *pp_ptr;
12140 pp_ptr = per_cpu(system_page_pool, i);
12144 page_pool_destroy(pp_ptr);
12145 per_cpu(system_page_pool, i) = NULL;
12152 subsys_initcall(net_dev_init);