xref: /linux-6.15/include/net/netdev_lock.h (revision 4b702f8b)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
3 #ifndef _NET_NETDEV_LOCK_H
4 #define _NET_NETDEV_LOCK_H
5 
6 #include <linux/lockdep.h>
7 #include <linux/netdevice.h>
8 #include <linux/rtnetlink.h>
9 
10 static inline bool netdev_trylock(struct net_device *dev)
11 {
12 	return mutex_trylock(&dev->lock);
13 }
14 
15 static inline void netdev_assert_locked(const struct net_device *dev)
16 {
17 	lockdep_assert_held(&dev->lock);
18 }
19 
20 static inline void
21 netdev_assert_locked_or_invisible(const struct net_device *dev)
22 {
23 	if (dev->reg_state == NETREG_REGISTERED ||
24 	    dev->reg_state == NETREG_UNREGISTERING)
25 		netdev_assert_locked(dev);
26 }
27 
28 static inline bool netdev_need_ops_lock(const struct net_device *dev)
29 {
30 	bool ret = dev->request_ops_lock || !!dev->queue_mgmt_ops;
31 
32 #if IS_ENABLED(CONFIG_NET_SHAPER)
33 	ret |= !!dev->netdev_ops->net_shaper_ops;
34 #endif
35 
36 	return ret;
37 }
38 
39 static inline void netdev_lock_ops(struct net_device *dev)
40 {
41 	if (netdev_need_ops_lock(dev))
42 		netdev_lock(dev);
43 }
44 
45 static inline void netdev_unlock_ops(struct net_device *dev)
46 {
47 	if (netdev_need_ops_lock(dev))
48 		netdev_unlock(dev);
49 }
50 
51 static inline void netdev_ops_assert_locked(const struct net_device *dev)
52 {
53 	if (netdev_need_ops_lock(dev))
54 		lockdep_assert_held(&dev->lock);
55 	else
56 		ASSERT_RTNL();
57 }
58 
59 static inline int netdev_lock_cmp_fn(const struct lockdep_map *a,
60 				     const struct lockdep_map *b)
61 {
62 	/* Only lower devices currently grab the instance lock, so no
63 	 * real ordering issues can occur. In the near future, only
64 	 * hardware devices will grab instance lock which also does not
65 	 * involve any ordering. Suppress lockdep ordering warnings
66 	 * until (if) we start grabbing instance lock on pure SW
67 	 * devices (bond/team/veth/etc).
68 	 */
69 	if (a == b)
70 		return 0;
71 	return -1;
72 }
73 
74 #define netdev_lockdep_set_classes(dev)				\
75 {								\
76 	static struct lock_class_key qdisc_tx_busylock_key;	\
77 	static struct lock_class_key qdisc_xmit_lock_key;	\
78 	static struct lock_class_key dev_addr_list_lock_key;	\
79 	static struct lock_class_key dev_instance_lock_key;	\
80 	unsigned int i;						\
81 								\
82 	(dev)->qdisc_tx_busylock = &qdisc_tx_busylock_key;	\
83 	lockdep_set_class(&(dev)->addr_list_lock,		\
84 			  &dev_addr_list_lock_key);		\
85 	lockdep_set_class(&(dev)->lock,				\
86 			  &dev_instance_lock_key);		\
87 	lock_set_cmp_fn(&dev->lock, netdev_lock_cmp_fn, NULL);	\
88 	for (i = 0; i < (dev)->num_tx_queues; i++)		\
89 		lockdep_set_class(&(dev)->_tx[i]._xmit_lock,	\
90 				  &qdisc_xmit_lock_key);	\
91 }
92 
93 #endif
94