xref: /freebsd/share/man/man9/mutex.9 (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
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 April 20, 1998
32.Dt MUTEX 9
33.Sh NAME
34.Nm mutex ,
35.Nm mtx_init ,
36.Nm mtx_enter ,
37.Nm mtx_try_enter ,
38.Nm mtx_exit ,
39.Nm mtx_destroy ,
40.Nm mtx_owned ,
41.Nm mtx_assert ,
42.Nm MUTEX_DECLARE
43.Nd kernel synchronization primitives
44.Sh SYNOPSIS
45.Fd #include <sys/mutex.h>
46.Ft int
47.Fn mtx_init "struct mtx *mutex" "char *name" "flags"
48.Ft void
49.Fn mtx_enter "struct mtx *mutex" "int flags"
50.Ft void
51.Fn mtx_try_enter "struct mtx *mutex" "int flags"
52.Ft void
53.Fn mtx_exit "struct mtx *mutex" "int flags"
54.Ft void
55.Fn mtx_destroy "struct mtx *mutex"
56.Ft int
57.Fn mtx_owned "struct mtx *mutex"
58.Ft void
59.Fn mtx_assert "struct mtx *mutex" "int what"
60.Fn MUTEX_DECLARE "modifiers" "name"
61.Sh DESCRIPTION
62Mutexes are the most basic and primary method of process synchronization.
63The major design considerations for mutexes are:
64.Bl -enum
65.It
66Acquiring and releasing uncontested mutexes should be as cheap
67as possible.
68.It
69They must have the information and storage space to support
70priority propagation.
71.It
72A process must be able to recursively acquire a mutex.
73.El
74.Pp
75There are currently two flavors of mutexes, those that context switch
76when they block and those that do not.
77.Pp
78By default mutexes will context switch when they are already held.
79As a machine dependent optimization they may spin for some amount
80of time before context switching.
81It is important to remember that since a process may be preempted
82at any time, the possible context switch introduced by acquiring a
83mutex is guaranteed to not break anything that isn't already broken.
84.Pp
85Mutexes which do not context switch are spin mutexes.
86These should only be used to protect data shared with device that
87require non-preemptive interrupts, and low level scheduling code.
88In most/all architectures both acquiring and releasing of a
89uncontested spin mutex is more expensive than the same operation
90on a non spin mutex.
91In order to protect an interrupt service routine from blocking
92against itself all interrupts are blocked on a processor while
93holding a spin lock.
94It is permissible to hold multiple spin mutexes.
95In this case it is a required that they be released in the opposite
96order to that which they were acquired.
97.Pp
98Once a spin mutex has been acquired it is not permissible to acquire a
99blocking mutex.
100.Pp
101The storage needed to implement a mutex is provided by a
102.Dv struct mtx .
103In general this should be treated as an opaque object and
104referenced only with the mutex primitives.
105.Pp
106The
107.Fn mtx_init
108function must be used to initialize a mutex
109before it can be passed to
110.Fn mtx_enter .
111The
112.Ar name
113argument is used by the witness code
114to classify a mutex when doing checks of lock ordering.
115The pointer passed in as the
116.Ar name
117is saved rather than the data it points to.
118The data pointed to must remain stable
119until the mutex is destroyed.
120Currently the
121.Ar flag
122argument is unused.
123In the future it will likely be at least
124used to identify spin mutexes
125so that debug code can verify
126consistent use of a mutex.
127It is not permissible to pass the same
128.Ar mutex
129to
130.Fn mtx_init
131multiple times without intervening calls to
132.Fn mtx_destroy .
133.Pp
134The
135.Fn mtx_enter
136function acquires a mutual exclusion lock
137on behalf of the currently running kernel thread.
138If another kernel thread is holding the mutex,
139the caller will be disconnected from the CPU
140until the mutex is available
141(i.e. it will sleep),
142spin wait for the mutex,
143or possibly a combination of both.
144.Pp
145It is possible for the same thread to recursively acquire a mutex
146with no ill effects;
147if recursion on a given mutex can be avoided,
148faster and smaller code will usually be generated.
149.Pp
150The
151.Fn mtx_try_enter
152function is used to acquire exclusive access
153to those objects protected by the mutex
154pointed to by
155.Ar mutex .
156The
157.Ar flag
158argument is used to specify various options,
159typically
160.Dv MTX_DEF
161is supplied.
162If the mutex can not be immediately acquired
163.Fn mtx_try_enter
164will return 0,
165otherwise the mutex will be acquired
166and a non-zero value will be returned.
167.Pp
168The
169.Fn mtx_exit
170function releases a mutual exclusion lock;
171if a higher priority thread is waiting for the mutex,
172the releasing thread may be disconnected
173to allow the higher priority thread to acquire the mutex and run.
174.Pp
175The
176.Fn mtx_destroy
177function is used to destroy
178.Ar mutex
179so the data associated with it may be freed
180or otherwise overwritten.
181Any mutex which is destroyed
182must previously have been initialized with
183.Fn mtx_init .
184It is permissible to have a single hold count
185on a mutex when it is destroyed.
186It is not permissible to hold the mutex recursively,
187or have another process blocked on the mutex
188when it is destroyed.
189.Pp
190The
191.Fn mtx_owned
192function returns non-zero
193if the current process holds
194.Ar mutex .
195If the current process does not hold
196.Ar mutex
197zero is returned.
198.Pp
199The
200.Fn mtx_assert
201function  allows assertions to be made about
202.Ar mutex .
203If the assertions are not true and the kernel is compiled with
204.Dv INVARIANTS
205then the kernel will panic.
206Currently the following assertions are supported:
207.Bl -enum
208.It
209.Dv MA_OWNED
210Assert that the current thread
211holds the mutex
212pointed to by the first argument.
213.It
214.Dv MA_NOTOWNED
215Assert that the current thread
216does not hold the mutex
217pointed to by the first argument.
218.El
219.Pp
220The
221.Fn MUTEX_DECLARE
222macro is used to declare a mutex that is initialized before
223.Xr malloc 9
224is operating.
225Unfortunately, mutex initialization may require
226.Xr malloc 9 .
227However, some mutexes are intialized and used before
228.Xr malloc 9
229can be used.
230Declaring these mutexes with the
231.Fn MUTEX_DECLARE
232macro and then using the
233.Dv MTX_COLD
234flag when calling
235.Fn mtx_init
236allows these early mutexes to be initialized and used before
237.Xr malloc 9
238is available.
239The
240.Ar modifiers
241argument is a list of attributes to be applied to the mutex structure being
242declared such as
243.Dq static .
244The
245.Ar name
246argument is the name of the mutex structure to declare.
247.Pp
248The type of a mutex is not an attribute of the mutex,
249but instead a function of the
250.Fa flags
251argument passed to
252.Fn mtx_enter
253and
254.Fn mtx_exit ;
255this allows code to be generated for the specific mutex type
256at compile time
257and avoids wasting run time on the determination of lock features.
258This does place on the programmer,
259the burden of using matching forms of the
260.Fn mtx_enter
261and
262.Fn mtx_exit
263functions for a given mutex.
264It is an error to acquire a mutex in one mode (e.g. spin)
265and release it in another (e.g. default).
266It is also an error to get the lock in one mode
267and allow another thread to attempt to get the lock in another mode.
268A good general rule is to always use a given mutex in one mode only.
269.Ss The default Mutex Type
270Most kernel code should use the default lock type;
271the default lock type will allow the thread
272to be disconnected from the CPU
273if it cannot get the lock.
274The machine dependent implementation
275may treat the lock as a short term spin lock
276under some circumstances.
277However, it is always safe to use these forms of locks
278in an interrupt thread
279without fear of deadlock
280against an interrupted thread on the same CPU.
281.Ss The spin Mutex Type
282A spin mutex will not relinquish the CPU
283when it cannot immediately get the requested lock,
284but will loop, waiting for the mutex to be released by another CPU.
285This could result in deadlock
286if a thread interrupted the thread which held a mutex
287and then tried to acquire the mutex;
288for this reason spin locks will disable all interrupts
289(on the local CPU only)
290by default.
291.Pp
292Spin locks are fairly specialized locks
293that are intended to be held for very short periods of time;
294their primary purpose is to protect portions of the code
295that implement default (i.e. sleep) locks.
296.Ss Flags
297The flags passed to the
298.Fn mtx_enter
299and
300.Fn mtx_exit
301functions determine what type of mutex is being used
302and also provide various options
303used to generate more efficient code under certain circumstances.
304.Pp
305Both lock types (default and spin)
306can be acquired recursively by the same thread.
307This behavior can be changed with flags.
308.Pp
309The type of the mutex must always be specified:
310.Bl -tag -width MTX_NORECURSE
311.It Dv MTX_DEF
312Default lock type;
313will always allow the current thread to be suspended
314to avoid deadlock conditions against interrupt threads.
315The machine dependent implementation of this lock type
316may spin for a while before suspending the current thread.
317Most locks should be of this type.
318.It Dv MTX_SPIN
319Spin lock;
320will never relinquish the CPU.
321By default all interrupts are disabled on the local CPU
322while any spin lock is held.
323.El
324.Pp
325Options that modify mutex behavior:
326.Bl -tag -width MTX_NORECURSE
327.It Dv MTX_NORECURSE
328If it is known, absolutely,
329that the mutex will not be recursively acquired at this invocation
330then this flag should be specified.
331.Pp
332If the lock is already held by the current thread,
333then a kernel with
334.Dv MUTEX_DEBUG
335defined will panic;
336without debugging enabled,
337the thread may deadlock against itself
338or leave the mutex in a corrupted state.
339.Pp
340This flag prevents generation of additional inline code
341to deal with recursive lock acquisitions
342and should be specified whenever possible
343in the interests of efficiency.
344Not specifying this flag will only cause the generated code
345to be a little larger than necessary;
346it will still operate correctly.
347.It Dv MTX_RLIKELY
348This provides a hint that it is likely that this mutex
349will be held recursively at this invocation.
350The actual optimization used is machine dependent;
351generally, this will inline code to handle recursion
352where a function call would otherwise be needed.
353.Pp
354This is a hint only;
355leaving it out or specifying it inappropriately
356will not cause any great harm other than
357possibly generating less efficient code.
358.It Dv MTX_TOPHALF
359This option applies to spin locks only.
360It indicates that the mutex is never acquired
361from an interrupt thread,
362so it is safe to leave interrupts enabled while holding the lock.
363Since an interrupt may occur while holding the lock,
364this may be detrimental to other processors
365spin waiting for the lock.
366Do not forget to include this option when the lock is released.
367.Pp
368This option should not be used in new code;
369it is documented here for completeness only.
370.It Dv MTX_FIRST
371This option applies to spin locks only.
372It indicates this is the first spin lock acquired by the thread.
373No other spin locks may be held,
374and the requested lock also may not be currently held.
375Do not forget to include this option when the lock is released.
376.It Dv MTX_NOSWITCH
377When releasing a mutex,
378this flag prevents a thread switch that might occur
379if another higher priority thread was waiting for the mutex.
380This may cause priority inversion and should be used carefully.
381.Pp
382This flag is used internally by the lock code.
383It should not be used in general kernel code
384and is documented here for completeness only.
385.It Dv MTX_NOSPIN
386For default locks,
387this hint will prevent spinning before relinquishing the CPU.
388This should be specified when it is known
389that the lock will usually remain unavailable for some time
390when it is not immediately available
391(i.e.: coarse grained locks protecting large subsystems).
392.It Dv MTX_COLD
393This option is only used in
394.Fn mtx_init
395and is used in conjunction with mutexes declared with
396.Fn MUTEX_DECLARE
397to initialize mutexes that are needed before
398.Xr malloc 9
399is available for use.
400.El
401.Sh HISTORY
402These
403functions appeared in BSD/OS 4.1 and
404.Fx 5.0 .
405