xref: /freebsd/sys/sys/mutex.h (revision aa0a1e58)
1 /*-
2  * Copyright (c) 1997 Berkeley Software Design, Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. Berkeley Software Design Inc's name may not be used to endorse or
13  *    promote products derived from this software without specific prior
14  *    written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  *	from BSDI $Id: mutex.h,v 2.7.2.35 2000/04/27 03:10:26 cp Exp $
29  * $FreeBSD$
30  */
31 
32 #ifndef _SYS_MUTEX_H_
33 #define _SYS_MUTEX_H_
34 
35 #include <sys/queue.h>
36 #include <sys/_lock.h>
37 #include <sys/_mutex.h>
38 
39 #ifdef _KERNEL
40 #include <sys/pcpu.h>
41 #include <sys/lock_profile.h>
42 #include <sys/lockstat.h>
43 #include <machine/atomic.h>
44 #include <machine/cpufunc.h>
45 
46 /*
47  * Mutex types and options passed to mtx_init().  MTX_QUIET and MTX_DUPOK
48  * can also be passed in.
49  */
50 #define	MTX_DEF		0x00000000	/* DEFAULT (sleep) lock */
51 #define MTX_SPIN	0x00000001	/* Spin lock (disables interrupts) */
52 #define MTX_RECURSE	0x00000004	/* Option: lock allowed to recurse */
53 #define	MTX_NOWITNESS	0x00000008	/* Don't do any witness checking. */
54 #define MTX_NOPROFILE   0x00000020	/* Don't profile this lock */
55 
56 /*
57  * Option flags passed to certain lock/unlock routines, through the use
58  * of corresponding mtx_{lock,unlock}_flags() interface macros.
59  */
60 #define	MTX_QUIET	LOP_QUIET	/* Don't log a mutex event */
61 #define	MTX_DUPOK	LOP_DUPOK	/* Don't log a duplicate acquire */
62 
63 /*
64  * State bits kept in mutex->mtx_lock, for the DEFAULT lock type. None of this,
65  * with the exception of MTX_UNOWNED, applies to spin locks.
66  */
67 #define	MTX_RECURSED	0x00000001	/* lock recursed (for MTX_DEF only) */
68 #define	MTX_CONTESTED	0x00000002	/* lock contested (for MTX_DEF only) */
69 #define MTX_UNOWNED	0x00000004	/* Cookie for free mutex */
70 #define	MTX_FLAGMASK	(MTX_RECURSED | MTX_CONTESTED | MTX_UNOWNED)
71 
72 /*
73  * Value stored in mutex->mtx_lock to denote a destroyed mutex.
74  */
75 #define	MTX_DESTROYED	(MTX_CONTESTED | MTX_UNOWNED)
76 
77 /*
78  * Prototypes
79  *
80  * NOTE: Functions prepended with `_' (underscore) are exported to other parts
81  *	 of the kernel via macros, thus allowing us to use the cpp LOCK_FILE
82  *	 and LOCK_LINE. These functions should not be called directly by any
83  *	 code using the API. Their macros cover their functionality.
84  *
85  * [See below for descriptions]
86  *
87  */
88 void	mtx_init(struct mtx *m, const char *name, const char *type, int opts);
89 void	mtx_destroy(struct mtx *m);
90 void	mtx_sysinit(void *arg);
91 void	mutex_init(void);
92 void	_mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts,
93 	    const char *file, int line);
94 void	_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line);
95 #ifdef SMP
96 void	_mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts,
97 	    const char *file, int line);
98 #endif
99 void	_mtx_unlock_spin(struct mtx *m, int opts, const char *file, int line);
100 int	_mtx_trylock(struct mtx *m, int opts, const char *file, int line);
101 void	_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line);
102 void	_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line);
103 void	_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file,
104 	     int line);
105 void	_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file,
106 	     int line);
107 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
108 void	_mtx_assert(struct mtx *m, int what, const char *file, int line);
109 #endif
110 void	_thread_lock_flags(struct thread *, int, const char *, int);
111 
112 #define	thread_lock(tdp)						\
113     _thread_lock_flags((tdp), 0, __FILE__, __LINE__)
114 #define	thread_lock_flags(tdp, opt)					\
115     _thread_lock_flags((tdp), (opt), __FILE__, __LINE__)
116 #define	thread_unlock(tdp)						\
117        mtx_unlock_spin((tdp)->td_lock)
118 
119 #define	mtx_recurse	lock_object.lo_data
120 
121 /* Very simple operations on mtx_lock. */
122 
123 /* Try to obtain mtx_lock once. */
124 #define _mtx_obtain_lock(mp, tid)					\
125 	atomic_cmpset_acq_ptr(&(mp)->mtx_lock, MTX_UNOWNED, (tid))
126 
127 /* Try to release mtx_lock if it is unrecursed and uncontested. */
128 #define _mtx_release_lock(mp, tid)					\
129 	atomic_cmpset_rel_ptr(&(mp)->mtx_lock, (tid), MTX_UNOWNED)
130 
131 /* Release mtx_lock quickly, assuming we own it. */
132 #define _mtx_release_lock_quick(mp)					\
133 	atomic_store_rel_ptr(&(mp)->mtx_lock, MTX_UNOWNED)
134 
135 /*
136  * Full lock operations that are suitable to be inlined in non-debug
137  * kernels.  If the lock cannot be acquired or released trivially then
138  * the work is deferred to another function.
139  */
140 
141 /* Lock a normal mutex. */
142 #define __mtx_lock(mp, tid, opts, file, line) do {			\
143 	uintptr_t _tid = (uintptr_t)(tid);				\
144 									\
145 	if (!_mtx_obtain_lock((mp), _tid))				\
146 		_mtx_lock_sleep((mp), _tid, (opts), (file), (line));	\
147 	else								\
148               	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_MTX_LOCK_ACQUIRE, \
149 		    mp, 0, 0, (file), (line));				\
150 } while (0)
151 
152 /*
153  * Lock a spin mutex.  For spinlocks, we handle recursion inline (it
154  * turns out that function calls can be significantly expensive on
155  * some architectures).  Since spin locks are not _too_ common,
156  * inlining this code is not too big a deal.
157  */
158 #ifdef SMP
159 #define __mtx_lock_spin(mp, tid, opts, file, line) do {			\
160 	uintptr_t _tid = (uintptr_t)(tid);				\
161 									\
162 	spinlock_enter();						\
163 	if (!_mtx_obtain_lock((mp), _tid)) {				\
164 		if ((mp)->mtx_lock == _tid)				\
165 			(mp)->mtx_recurse++;				\
166 		else							\
167 			_mtx_lock_spin((mp), _tid, (opts), (file), (line)); \
168 	} else 								\
169               	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_MTX_SPIN_LOCK_ACQUIRE, \
170 		    mp, 0, 0, (file), (line));				\
171 } while (0)
172 #else /* SMP */
173 #define __mtx_lock_spin(mp, tid, opts, file, line) do {			\
174 	uintptr_t _tid = (uintptr_t)(tid);				\
175 									\
176 	spinlock_enter();						\
177 	if ((mp)->mtx_lock == _tid)					\
178 		(mp)->mtx_recurse++;					\
179 	else {								\
180 		KASSERT((mp)->mtx_lock == MTX_UNOWNED, ("corrupt spinlock")); \
181 		(mp)->mtx_lock = _tid;					\
182 	}								\
183 } while (0)
184 #endif /* SMP */
185 
186 /* Unlock a normal mutex. */
187 #define __mtx_unlock(mp, tid, opts, file, line) do {			\
188 	uintptr_t _tid = (uintptr_t)(tid);				\
189 									\
190 	if (!_mtx_release_lock((mp), _tid))				\
191 		_mtx_unlock_sleep((mp), (opts), (file), (line));	\
192 } while (0)
193 
194 /*
195  * Unlock a spin mutex.  For spinlocks, we can handle everything
196  * inline, as it's pretty simple and a function call would be too
197  * expensive (at least on some architectures).  Since spin locks are
198  * not _too_ common, inlining this code is not too big a deal.
199  *
200  * Since we always perform a spinlock_enter() when attempting to acquire a
201  * spin lock, we need to always perform a matching spinlock_exit() when
202  * releasing a spin lock.  This includes the recursion cases.
203  */
204 #ifdef SMP
205 #define __mtx_unlock_spin(mp) do {					\
206 	if (mtx_recursed((mp)))						\
207 		(mp)->mtx_recurse--;					\
208 	else {								\
209 		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_MTX_SPIN_UNLOCK_RELEASE, \
210 			mp);						\
211 		_mtx_release_lock_quick((mp));				\
212 	}                                                               \
213 	spinlock_exit();				                \
214 } while (0)
215 #else /* SMP */
216 #define __mtx_unlock_spin(mp) do {					\
217 	if (mtx_recursed((mp)))						\
218 		(mp)->mtx_recurse--;					\
219 	else {								\
220 		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_MTX_SPIN_UNLOCK_RELEASE, \
221 			mp);						\
222 		(mp)->mtx_lock = MTX_UNOWNED;				\
223 	}                                                               \
224 	spinlock_exit();						\
225 } while (0)
226 #endif /* SMP */
227 
228 /*
229  * Exported lock manipulation interface.
230  *
231  * mtx_lock(m) locks MTX_DEF mutex `m'
232  *
233  * mtx_lock_spin(m) locks MTX_SPIN mutex `m'
234  *
235  * mtx_unlock(m) unlocks MTX_DEF mutex `m'
236  *
237  * mtx_unlock_spin(m) unlocks MTX_SPIN mutex `m'
238  *
239  * mtx_lock_spin_flags(m, opts) and mtx_lock_flags(m, opts) locks mutex `m'
240  *     and passes option flags `opts' to the "hard" function, if required.
241  *     With these routines, it is possible to pass flags such as MTX_QUIET
242  *     to the appropriate lock manipulation routines.
243  *
244  * mtx_trylock(m) attempts to acquire MTX_DEF mutex `m' but doesn't sleep if
245  *     it cannot. Rather, it returns 0 on failure and non-zero on success.
246  *     It does NOT handle recursion as we assume that if a caller is properly
247  *     using this part of the interface, he will know that the lock in question
248  *     is _not_ recursed.
249  *
250  * mtx_trylock_flags(m, opts) is used the same way as mtx_trylock() but accepts
251  *     relevant option flags `opts.'
252  *
253  * mtx_initialized(m) returns non-zero if the lock `m' has been initialized.
254  *
255  * mtx_owned(m) returns non-zero if the current thread owns the lock `m'
256  *
257  * mtx_recursed(m) returns non-zero if the lock `m' is presently recursed.
258  */
259 #define mtx_lock(m)		mtx_lock_flags((m), 0)
260 #define mtx_lock_spin(m)	mtx_lock_spin_flags((m), 0)
261 #define mtx_trylock(m)		mtx_trylock_flags((m), 0)
262 #define mtx_unlock(m)		mtx_unlock_flags((m), 0)
263 #define mtx_unlock_spin(m)	mtx_unlock_spin_flags((m), 0)
264 
265 struct mtx_pool;
266 
267 struct mtx_pool *mtx_pool_create(const char *mtx_name, int pool_size, int opts);
268 void mtx_pool_destroy(struct mtx_pool **poolp);
269 struct mtx *mtx_pool_find(struct mtx_pool *pool, void *ptr);
270 struct mtx *mtx_pool_alloc(struct mtx_pool *pool);
271 #define mtx_pool_lock(pool, ptr)					\
272 	mtx_lock(mtx_pool_find((pool), (ptr)))
273 #define mtx_pool_lock_spin(pool, ptr)					\
274 	mtx_lock_spin(mtx_pool_find((pool), (ptr)))
275 #define mtx_pool_unlock(pool, ptr)					\
276 	mtx_unlock(mtx_pool_find((pool), (ptr)))
277 #define mtx_pool_unlock_spin(pool, ptr)					\
278 	mtx_unlock_spin(mtx_pool_find((pool), (ptr)))
279 
280 /*
281  * mtxpool_lockbuilder is a pool of sleep locks that is not witness
282  * checked and should only be used for building higher level locks.
283  *
284  * mtxpool_sleep is a general purpose pool of sleep mutexes.
285  */
286 extern struct mtx_pool *mtxpool_lockbuilder;
287 extern struct mtx_pool *mtxpool_sleep;
288 
289 #ifndef LOCK_DEBUG
290 #error LOCK_DEBUG not defined, include <sys/lock.h> before <sys/mutex.h>
291 #endif
292 #if LOCK_DEBUG > 0 || defined(MUTEX_NOINLINE)
293 #define	mtx_lock_flags(m, opts)						\
294 	_mtx_lock_flags((m), (opts), LOCK_FILE, LOCK_LINE)
295 #define	mtx_unlock_flags(m, opts)					\
296 	_mtx_unlock_flags((m), (opts), LOCK_FILE, LOCK_LINE)
297 #define	mtx_lock_spin_flags(m, opts)					\
298 	_mtx_lock_spin_flags((m), (opts), LOCK_FILE, LOCK_LINE)
299 #define	mtx_unlock_spin_flags(m, opts)					\
300 	_mtx_unlock_spin_flags((m), (opts), LOCK_FILE, LOCK_LINE)
301 #else	/* LOCK_DEBUG == 0 && !MUTEX_NOINLINE */
302 #define	mtx_lock_flags(m, opts)						\
303 	__mtx_lock((m), curthread, (opts), LOCK_FILE, LOCK_LINE)
304 #define	mtx_unlock_flags(m, opts)					\
305 	__mtx_unlock((m), curthread, (opts), LOCK_FILE, LOCK_LINE)
306 #define	mtx_lock_spin_flags(m, opts)					\
307 	__mtx_lock_spin((m), curthread, (opts), LOCK_FILE, LOCK_LINE)
308 #define	mtx_unlock_spin_flags(m, opts)					\
309 	__mtx_unlock_spin((m))
310 #endif	/* LOCK_DEBUG > 0 || MUTEX_NOINLINE */
311 
312 #define mtx_trylock_flags(m, opts)					\
313 	_mtx_trylock((m), (opts), LOCK_FILE, LOCK_LINE)
314 
315 #define	mtx_sleep(chan, mtx, pri, wmesg, timo)				\
316 	_sleep((chan), &(mtx)->lock_object, (pri), (wmesg), (timo))
317 
318 #define	mtx_initialized(m)	lock_initalized(&(m)->lock_object)
319 
320 #define mtx_owned(m)	(((m)->mtx_lock & ~MTX_FLAGMASK) == (uintptr_t)curthread)
321 
322 #define mtx_recursed(m)	((m)->mtx_recurse != 0)
323 
324 #define mtx_name(m)	((m)->lock_object.lo_name)
325 
326 /*
327  * Global locks.
328  */
329 extern struct mtx Giant;
330 extern struct mtx blocked_lock;
331 
332 /*
333  * Giant lock manipulation and clean exit macros.
334  * Used to replace return with an exit Giant and return.
335  *
336  * Note that DROP_GIANT*() needs to be paired with PICKUP_GIANT()
337  * The #ifndef is to allow lint-like tools to redefine DROP_GIANT.
338  */
339 #ifndef DROP_GIANT
340 #define DROP_GIANT()							\
341 do {									\
342 	int _giantcnt = 0;						\
343 	WITNESS_SAVE_DECL(Giant);					\
344 									\
345 	if (mtx_owned(&Giant)) {					\
346 		WITNESS_SAVE(&Giant.lock_object, Giant);		\
347 		for (_giantcnt = 0; mtx_owned(&Giant); _giantcnt++)	\
348 			mtx_unlock(&Giant);				\
349 	}
350 
351 #define PICKUP_GIANT()							\
352 	PARTIAL_PICKUP_GIANT();						\
353 } while (0)
354 
355 #define PARTIAL_PICKUP_GIANT()						\
356 	mtx_assert(&Giant, MA_NOTOWNED);				\
357 	if (_giantcnt > 0) {						\
358 		while (_giantcnt--)					\
359 			mtx_lock(&Giant);				\
360 		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
361 	}
362 #endif
363 
364 #define	UGAR(rval) do {							\
365 	int _val = (rval);						\
366 	mtx_unlock(&Giant);						\
367 	return (_val);							\
368 } while (0)
369 
370 struct mtx_args {
371 	struct mtx	*ma_mtx;
372 	const char 	*ma_desc;
373 	int		 ma_opts;
374 };
375 
376 #define	MTX_SYSINIT(name, mtx, desc, opts)				\
377 	static struct mtx_args name##_args = {				\
378 		(mtx),							\
379 		(desc),							\
380 		(opts)							\
381 	};								\
382 	SYSINIT(name##_mtx_sysinit, SI_SUB_LOCK, SI_ORDER_MIDDLE,	\
383 	    mtx_sysinit, &name##_args);					\
384 	SYSUNINIT(name##_mtx_sysuninit, SI_SUB_LOCK, SI_ORDER_MIDDLE,	\
385 	    mtx_destroy, (mtx))
386 
387 /*
388  * The INVARIANTS-enabled mtx_assert() functionality.
389  *
390  * The constants need to be defined for INVARIANT_SUPPORT infrastructure
391  * support as _mtx_assert() itself uses them and the latter implies that
392  * _mtx_assert() must build.
393  */
394 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
395 #define MA_OWNED	LA_XLOCKED
396 #define MA_NOTOWNED	LA_UNLOCKED
397 #define MA_RECURSED	LA_RECURSED
398 #define MA_NOTRECURSED	LA_NOTRECURSED
399 #endif
400 
401 #ifdef INVARIANTS
402 #define	mtx_assert(m, what)						\
403 	_mtx_assert((m), (what), __FILE__, __LINE__)
404 
405 #define GIANT_REQUIRED	mtx_assert(&Giant, MA_OWNED)
406 
407 #else	/* INVARIANTS */
408 #define mtx_assert(m, what)	(void)0
409 #define GIANT_REQUIRED
410 #endif	/* INVARIANTS */
411 
412 /*
413  * Common lock type names.
414  */
415 #define	MTX_NETWORK_LOCK	"network driver"
416 
417 #endif	/* _KERNEL */
418 #endif	/* _SYS_MUTEX_H_ */
419