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