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