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