# About locks on hardwares. MTX_DEF or MTX_SPIN?



## coopci (Mar 30, 2009)

In ata_attach, the channels' locks are initialized by: 
mtx_init(&ch->state_mtx, "ATA state lock", NULL, MTX_DEF); 

As I know, MTX_DEF is more costly than MTX_SPIN. Does FreeBSD use MTX_DEF on hardwares widely? If yes, what makes it necessary to use MTX_DEF other than MTX_SPIN.


----------



## coopci (Mar 30, 2009)

Sorry, I did read the man text about mutex carefully enough ......


----------



## Maledictus (Mar 31, 2009)

For the record: One can't generally say the MTX_DEF is better or worse than MTX_SPIN.


----------



## coopci (Apr 1, 2009)

coopci said:
			
		

> Sorry, I did read the man text about mutex carefully enough ......


err... I mean "I did NOT read the man text about mutex carefully enough ......"

MTX_DEF spins for a while if the mutext is held by another thread which is running on a processor. So the anwser is obvious......


----------



## rwatson@ (May 16, 2009)

In fact, MTX_DEF is cheaper to acquire than MTX_SPIN on most hardware, because spin locks disable interrupts as well as use an atomic operation, whereas default mutexes only use an atomic operation.

FreeBSD default mutexes are "adaptive" meaning that they will also spin when contending a lock if the thread holding the lock is currently in execution on another CPU. If the thread holding the lock yields or is preempted, then another thread trying to acquire the lock will also yield, rather than spinning waiting for a non-running thread. As a result, default mutexes (and similar lock classes, such as rwlocks or rmlocks) are almost always preferred to spin mutexes.

The only exceptions are in the scheduler, and when in or synchronizing with "fast" interrupt handlers, which borrow the execution context of an existing kernel thread, and require interrupts to be disabled to avoid deadlock.


----------



## trasz@ (Feb 5, 2010)

This is mostly summed up in locking(9) manual page.  Make sure you have a current version.


----------

