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