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