xref: /freebsd/share/man/man9/mutex.9 (revision e0c4386e)
1.\"
2.\" Copyright (c) 1998 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.4,v 1.1.2.3 1998/04/27 22:53:13 ewv Exp $
29.\"
30.Dd February 17, 2023
31.Dt MUTEX 9
32.Os
33.Sh NAME
34.Nm mutex ,
35.Nm mtx_init ,
36.Nm mtx_destroy ,
37.Nm mtx_lock ,
38.Nm mtx_lock_spin ,
39.Nm mtx_lock_flags ,
40.Nm mtx_lock_spin_flags ,
41.Nm mtx_trylock ,
42.Nm mtx_trylock_flags ,
43.Nm mtx_trylock_spin ,
44.Nm mtx_trylock_spin_flags ,
45.Nm mtx_unlock ,
46.Nm mtx_unlock_spin ,
47.Nm mtx_unlock_flags ,
48.Nm mtx_unlock_spin_flags ,
49.Nm mtx_sleep ,
50.Nm mtx_initialized ,
51.Nm mtx_owned ,
52.Nm mtx_recursed ,
53.Nm mtx_assert ,
54.Nm MTX_SYSINIT
55.Nd kernel synchronization primitives
56.Sh SYNOPSIS
57.In sys/param.h
58.In sys/lock.h
59.In sys/mutex.h
60.Ft void
61.Fn mtx_init "struct mtx *mutex" "const char *name" "const char *type" "int opts"
62.Ft void
63.Fn mtx_destroy "struct mtx *mutex"
64.Ft void
65.Fn mtx_lock "struct mtx *mutex"
66.Ft void
67.Fn mtx_lock_spin "struct mtx *mutex"
68.Ft void
69.Fn mtx_lock_flags "struct mtx *mutex" "int flags"
70.Ft void
71.Fn mtx_lock_spin_flags "struct mtx *mutex" "int flags"
72.Ft int
73.Fn mtx_trylock "struct mtx *mutex"
74.Ft int
75.Fn mtx_trylock_flags "struct mtx *mutex" "int flags"
76.Ft int
77.Fn mtx_trylock_spin "struct mtx *mutex"
78.Ft int
79.Fn mtx_trylock_spin_flags "struct mtx *mutex" "int flags"
80.Ft void
81.Fn mtx_unlock "struct mtx *mutex"
82.Ft void
83.Fn mtx_unlock_spin "struct mtx *mutex"
84.Ft void
85.Fn mtx_unlock_flags "struct mtx *mutex" "int flags"
86.Ft void
87.Fn mtx_unlock_spin_flags "struct mtx *mutex" "int flags"
88.Ft int
89.Fn mtx_sleep "void *chan" "struct mtx *mtx" "int priority" "const char *wmesg" "int timo"
90.Ft int
91.Fn mtx_initialized "const struct mtx *mutex"
92.Ft int
93.Fn mtx_owned "const struct mtx *mutex"
94.Ft int
95.Fn mtx_recursed "const struct mtx *mutex"
96.Pp
97.Cd "options INVARIANTS"
98.Cd "options INVARIANT_SUPPORT"
99.Ft void
100.Fn mtx_assert "const struct mtx *mutex" "int what"
101.In sys/kernel.h
102.Fn MTX_SYSINIT "name" "struct mtx *mtx" "const char *description" "int opts"
103.Sh DESCRIPTION
104Mutexes are the most basic and primary method of thread synchronization.
105The major design considerations for mutexes are:
106.Bl -enum
107.It
108Acquiring and releasing uncontested mutexes should be as cheap
109as possible.
110.It
111They must have the information and storage space to support
112priority propagation.
113.It
114A thread must be able to recursively acquire a mutex,
115provided that the mutex is initialized to support recursion.
116.El
117.Pp
118There are currently two flavors of mutexes, those that context switch
119when they block and those that do not.
120.Pp
121By default,
122.Dv MTX_DEF
123mutexes will context switch when they are already held.
124As an optimization,
125they may spin for some amount
126of time before context switching.
127It is important to remember that since a thread may be preempted at any time,
128the possible context switch introduced by acquiring a mutex is guaranteed
129to not break anything that is not already broken.
130.Pp
131Mutexes which do not context switch are
132.Dv MTX_SPIN
133mutexes.
134These should only be used to protect data shared with primary interrupt
135code.
136This includes interrupt filters and low level scheduling code.
137In all architectures both acquiring and releasing of a
138uncontested spin mutex is more expensive than the same operation
139on a non-spin mutex.
140In order to protect an interrupt service routine from blocking
141against itself all interrupts are either blocked or deferred on a processor
142while holding a spin lock.
143It is permissible to hold multiple spin mutexes.
144.Pp
145Once a spin mutex has been acquired it is not permissible to acquire a
146blocking mutex.
147.Pp
148The storage needed to implement a mutex is provided by a
149.Vt struct mtx .
150In general this should be treated as an opaque object and
151referenced only with the mutex primitives.
152.Pp
153The
154.Fn mtx_init
155function must be used to initialize a mutex
156before it can be passed to any of the other mutex functions.
157The
158.Fa name
159option is used to identify the lock in debugging output etc.
160The
161.Fa type
162option is used by the witness code to classify a mutex when doing checks
163of lock ordering.
164If
165.Fa type
166is
167.Dv NULL ,
168.Fa name
169is used in its place.
170The pointer passed in as
171.Fa name
172and
173.Fa type
174is saved rather than the data it points to.
175The data pointed to must remain stable
176until the mutex is destroyed.
177The
178.Fa opts
179argument is used to set the type of mutex.
180It may contain either
181.Dv MTX_DEF
182or
183.Dv MTX_SPIN
184but not both.
185If the kernel has been compiled with
186.Cd "option INVARIANTS" ,
187.Fn mtx_init
188will assert that the
189.Fa mutex
190has not been initialized multiple times without intervening calls to
191.Fn mtx_destroy
192unless the
193.Dv MTX_NEW
194option is specified.
195See below for additional initialization options.
196.Pp
197The
198.Fn mtx_lock
199function acquires a
200.Dv MTX_DEF
201mutual exclusion lock
202on behalf of the currently running kernel thread.
203If another kernel thread is holding the mutex,
204the caller will be disconnected from the CPU
205until the mutex is available
206(i.e., it will block).
207.Pp
208The
209.Fn mtx_lock_spin
210function acquires a
211.Dv MTX_SPIN
212mutual exclusion lock
213on behalf of the currently running kernel thread.
214If another kernel thread is holding the mutex,
215the caller will spin until the mutex becomes available.
216Interrupts are disabled during the spin and remain disabled
217following the acquiring of the lock.
218.Pp
219It is possible for the same thread to recursively acquire a mutex
220with no ill effects, provided that the
221.Dv MTX_RECURSE
222bit was passed to
223.Fn mtx_init
224during the initialization of the mutex.
225.Pp
226The
227.Fn mtx_lock_flags
228and
229.Fn mtx_lock_spin_flags
230functions acquire a
231.Dv MTX_DEF
232or
233.Dv MTX_SPIN
234lock, respectively, and also accept a
235.Fa flags
236argument.
237In both cases, the only flags presently available for lock acquires are
238.Dv MTX_QUIET
239and
240.Dv MTX_RECURSE .
241If the
242.Dv MTX_QUIET
243bit is turned on in the
244.Fa flags
245argument, then if
246.Dv KTR_LOCK
247tracing is being done,
248it will be silenced during the lock acquire.
249If the
250.Dv MTX_RECURSE
251bit is turned on in the
252.Fa flags
253argument, then the mutex can be acquired recursively.
254.Pp
255The
256.Fn mtx_trylock
257and
258.Fn mtx_trylock_spin
259functions attempt to acquire a
260.Dv MTX_DEF
261or
262.Dv MTX_SPIN
263mutex, respectively, pointed to by
264.Fa mutex .
265If the mutex cannot be immediately acquired, the functions will return 0,
266otherwise the mutex will be acquired and a non-zero value will be returned.
267.Pp
268The
269.Fn mtx_trylock_flags
270and
271.Fn mtx_trylock_spin_flags
272functions have the same behavior as
273.Fn mtx_trylock
274and
275.Fn mtx_trylock_spin
276respectively, but should be used when the caller desires to pass in a
277.Fa flags
278value.
279Presently, the only valid value in the
280.Fn mtx_trylock
281and
282.Fn mtx_trylock_spin
283cases is
284.Dv MTX_QUIET ,
285and its effects are identical to those described for
286.Fn mtx_lock
287above.
288.Pp
289The
290.Fn mtx_unlock
291function releases a
292.Dv MTX_DEF
293mutual exclusion lock.
294The current thread may be preempted if a higher priority thread is waiting
295for the mutex.
296.Pp
297The
298.Fn mtx_unlock_spin
299function releases a
300.Dv MTX_SPIN
301mutual exclusion lock.
302.Pp
303The
304.Fn mtx_unlock_flags
305and
306.Fn mtx_unlock_spin_flags
307functions behave in exactly the same way as do the standard mutex
308unlock routines above, while also allowing a
309.Fa flags
310argument which may specify
311.Dv MTX_QUIET .
312The behavior of
313.Dv MTX_QUIET
314is identical to its behavior in the mutex lock routines.
315.Pp
316The
317.Fn mtx_destroy
318function is used to destroy
319.Fa mutex
320so the data associated with it may be freed
321or otherwise overwritten.
322Any mutex which is destroyed
323must previously have been initialized with
324.Fn mtx_init .
325It is permissible to have a single hold count
326on a mutex when it is destroyed.
327It is not permissible to hold the mutex recursively,
328or have another thread blocked on the mutex
329when it is destroyed.
330.Pp
331The
332.Fn mtx_sleep
333function is used to atomically release
334.Fa mtx
335while waiting for an event.
336For more details on the parameters to this function,
337see
338.Xr sleep 9 .
339.Pp
340The
341.Fn mtx_initialized
342function returns non-zero if
343.Fa mutex
344has been initialized and zero otherwise.
345.Pp
346The
347.Fn mtx_owned
348function returns non-zero
349if the current thread holds
350.Fa mutex .
351If the current thread does not hold
352.Fa mutex
353zero is returned.
354.Pp
355The
356.Fn mtx_recursed
357function returns non-zero if the
358.Fa mutex
359is recursed.
360This check should only be made if the running thread already owns
361.Fa mutex .
362.Pp
363The
364.Fn mtx_assert
365function allows assertions specified in
366.Fa what
367to be made about
368.Fa mutex .
369If the assertions are not true and the kernel is compiled with
370.Cd "options INVARIANTS"
371and
372.Cd "options INVARIANT_SUPPORT" ,
373the kernel will panic.
374Currently the following assertions are supported:
375.Bl -tag -width MA_NOTRECURSED
376.It Dv MA_OWNED
377Assert that the current thread
378holds the mutex
379pointed to by the first argument.
380.It Dv MA_NOTOWNED
381Assert that the current thread
382does not hold the mutex
383pointed to by the first argument.
384.It Dv MA_RECURSED
385Assert that the current thread has recursed on the mutex
386pointed to by the first argument.
387This assertion is only valid in conjunction with
388.Dv MA_OWNED .
389.It Dv MA_NOTRECURSED
390Assert that the current thread has not recursed on the mutex
391pointed to by the first argument.
392This assertion is only valid in conjunction with
393.Dv MA_OWNED .
394.El
395.Pp
396The
397.Fn MTX_SYSINIT
398macro is used to generate a call to the
399.Fn mtx_sysinit
400routine at system startup in order to initialize a given mutex lock.
401The parameters are the same as
402.Fn mtx_init
403but with an additional argument,
404.Fa name ,
405that is used in generating unique variable names for the related structures associated with the lock and the sysinit routine.
406.Ss The Default Mutex Type
407Most kernel code should use the default lock type,
408.Dv MTX_DEF .
409The default lock type will allow the thread
410to be disconnected from the CPU
411if the lock is already held by another thread.
412The implementation
413may treat the lock as a short term spin lock
414under some circumstances.
415However, it is always safe to use these forms of locks
416in an interrupt thread
417without fear of deadlock
418against an interrupted thread on the same CPU.
419.Ss The Spin Mutex Type
420A
421.Dv MTX_SPIN
422mutex will not relinquish the CPU
423when it cannot immediately get the requested lock,
424but will loop, waiting for the mutex to be released by another CPU.
425This could result in deadlock
426if another thread interrupted the thread which held a mutex
427and then tried to acquire the mutex.
428For this reason spin locks disable all interrupts on the local CPU.
429.Pp
430Spin locks are fairly specialized locks
431that are intended to be held for very short periods of time.
432Their primary purpose is to protect portions of the code
433that implement other synchronization primitives such as default mutexes,
434thread scheduling, and interrupt threads.
435.Ss Initialization Options
436The options passed in the
437.Fa opts
438argument of
439.Fn mtx_init
440specify the mutex type.
441One of the
442.Dv MTX_DEF
443or
444.Dv MTX_SPIN
445options is required and only one of those two options may be specified.
446The possibilities are:
447.Bl -tag -width MTX_NOWITNESS
448.It Dv MTX_DEF
449Default mutexes
450will always allow the current thread to be suspended
451to avoid deadlock conditions against interrupt threads.
452The implementation of this lock type
453may spin for a while before suspending the current thread.
454.It Dv MTX_SPIN
455Spin mutexes
456will never relinquish the CPU.
457All interrupts are disabled on the local CPU
458while any spin lock is held.
459.It Dv MTX_RECURSE
460Specifies that the initialized mutex is allowed to recurse.
461This bit must be present if the mutex is permitted to recurse.
462.Pp
463Note that neither
464.Fn mtx_trylock
465nor
466.Fn mtx_trylock_spin
467support recursion;
468that is, attempting to acquire an already-owned mutex fails.
469.It Dv MTX_QUIET
470Do not log any mutex operations for this lock.
471.It Dv MTX_NOWITNESS
472Instruct
473.Xr witness 4
474to ignore this lock.
475.It Dv MTX_DUPOK
476Witness should not log messages about duplicate locks being acquired.
477.It Dv MTX_NOPROFILE
478Do not profile this lock.
479.It Dv MTX_NEW
480Do not check for double-init.
481.El
482.Ss Lock and Unlock Flags
483The flags passed to the
484.Fn mtx_lock_flags ,
485.Fn mtx_lock_spin_flags ,
486.Fn mtx_unlock_flags ,
487and
488.Fn mtx_unlock_spin_flags
489functions provide some basic options to the caller,
490and are often used only under special circumstances to modify lock or
491unlock behavior.
492Standard locking and unlocking should be performed with the
493.Fn mtx_lock ,
494.Fn mtx_lock_spin ,
495.Fn mtx_unlock ,
496and
497.Fn mtx_unlock_spin
498functions.
499Only if a flag is required should the corresponding
500flags-accepting routines be used.
501.Pp
502Options that modify mutex behavior:
503.Bl -tag -width MTX_QUIET
504.It Dv MTX_QUIET
505This option is used to quiet logging messages during individual mutex
506operations.
507This can be used to trim superfluous logging messages for debugging purposes.
508.El
509.Ss Giant
510If
511.Va Giant
512must be acquired, it must be acquired prior to acquiring
513other mutexes.
514Put another way: it is impossible to acquire
515.Va Giant
516non-recursively while
517holding another mutex.
518It is possible to acquire other mutexes while holding
519.Va Giant ,
520and it is possible to acquire
521.Va Giant
522recursively while holding other mutexes.
523.Ss Sleeping
524Sleeping while holding a mutex (except for
525.Va Giant )
526is never safe
527and should be avoided.
528There are numerous assertions which will fail if this is attempted.
529.Ss Functions Which Access Memory in Userspace
530No mutexes should be held (except for
531.Va Giant )
532across functions which
533access memory in userspace, such as
534.Xr copyin 9 ,
535.Xr copyout 9 ,
536.Xr uiomove 9 ,
537.Xr fuword 9 ,
538etc.
539No locks are needed when calling these functions.
540.Sh SEE ALSO
541.Xr condvar 9 ,
542.Xr LOCK_PROFILING 9 ,
543.Xr locking 9 ,
544.Xr mtx_pool 9 ,
545.Xr panic 9 ,
546.Xr rwlock 9 ,
547.Xr sema 9 ,
548.Xr sleep 9 ,
549.Xr sx 9
550.Sh HISTORY
551These
552functions appeared in
553.Bsx 4.1
554and
555.Fx 5.0 .
556The
557.Fn mtx_trylock_spin
558function was added in
559.Fx 11.1 .
560