mtx_trylock() on a spin mutex

dmitry.krivenok at dmitry.krivenok at
Tue Jan 31 11:50:10 UTC 2012

Could someone please explain why mtx_trylock() must not be called on a spin mutex?
Is it conceptually wrong or is it a restriction of FreeBSD kernel implementation?

I've written slightly modified version of mtx_trylock (mtx_trylock_spin) which calls 
spinlock_enter/spinlock_exit and doesn't have KASSERT checking for lock class:

KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
 	  	             ("mtx_trylock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
 	  	             file, line));

but, to my surprise, all my tests passed w/o any errors/warnings on FreeBSD-8 with WITNESS/INVARIANTS/etc enabled.
I admit that my tests may not cover all possible use cases or scenarios though.

I did a quick google search but didn't find anything useful, so your help is greatly appreciated.
Thanks in advance!

The assertion was added in the following revision:

Revision 149737 - (view) (annotate) - [select for diffs] 
Modified Fri Sep 2 20:21:49 2005 UTC (6 years, 4 months ago) by jhb 
File length: 24623 byte(s) 
Diff to previous 148557 
- Add an assertion to panic if one tries to call mtx_trylock() on a spin
- Don't panic if a spin lock is held too long inside _mtx_lock_spin() if
  panicstr is set (meaning that we are already in a panic).  Just keep
  spinning forever instead.

More information about the freebsd-hackers mailing list