1.\" $OpenBSD: mutex.9,v 1.12 2009/09/08 13:36:20 jmc Exp $ 2.\" 3.\" Copyright (c) 2005 Pedro Martelletto <pedro@ambientworks.net> 4.\" All rights reserved. 5.\" 6.\" Permission to use, copy, modify, and distribute this software for any 7.\" purpose with or without fee is hereby granted, provided that the above 8.\" copyright notice and this permission notice appear in all copies. 9.\" 10.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17.\" 18.Dd $Mdocdate: September 8 2009 $ 19.Dt MUTEX 9 20.Os 21.Sh NAME 22.Nm mutex , 23.Nm mtx_init , 24.Nm mtx_enter , 25.Nm mtx_enter_try , 26.Nm mtx_leave 27.Nd interface to CPU mutexes 28.Sh SYNOPSIS 29.Fd #include <sys/mutex.h> 30.Ft void 31.Fn mtx_init "struct mutex *mtxp" "int wantipl" 32.Ft void 33.Fn mtx_enter "struct mutex *mtxp" 34.Ft int 35.Fn mtx_enter_try "struct mutex *mtxp" 36.Ft void 37.Fn mtx_leave "struct mutex *mtxp" 38.Sh DESCRIPTION 39The 40.Nm 41set of functions provides a non-recursive, interrupt-aware spinning mechanism 42to ensure mutual exclusion between different CPUs. 43.Pp 44The 45.Fn mtx_init 46function is used to initiate the mutex pointed to by 47.Fa mtxp . 48When acquired, the mutex will cause the processor interrupt level to be raised 49to 50.Fa wantipl 51if necessary. 52.Pp 53The 54.Fn mtx_enter 55function acquires a mutex, spinning if necessary. 56.Pp 57The 58.Fn mtx_enter_try 59function attempts to acquire a mutex. 60If it succeeds in acquiring the mutex it will return non-zero, otherwise 61it will return 0. 62.Pp 63The 64.Fn mtx_leave 65function releases a mutex. 66In case the acquisition of the mutex caused the interrupt level to be changed, 67it is then restored. 68.Sh SEE ALSO 69.Xr lockmgr 9 , 70.Xr rwlock 9 , 71.Xr spl 9 72.Sh HISTORY 73The 74.Nm 75functions first appeared in 76.Ox 3.6 . 77.Sh AUTHORS 78The 79.Nm 80functions were written by 81.An Artur Grabowski 82.Aq art@openbsd.org . 83.Sh CAVEATS 84As these are spinning locks, don't sleep while holding one. 85.Pp 86If using a mutex in an interrupt handler, locks must be initialised 87with the correct IPL or deadlock will occur. 88.Pp 89Multiple mutexes may be nested, but not interleaved. 90This is okay: 91.Bd -literal -offset indent 92mtx_enter(foo); 93mtx_enter(bar); 94mtx_leave(bar); 95mtx_leave(foo); 96.Ed 97.Pp 98While this is 99.Fa not : 100.Bd -literal -offset indent 101mtx_enter(foo); 102mtx_enter(bar); 103mtx_leave(foo); 104mtx_leave(bar); 105.Ed 106