epoch_drain_cb() decrements e_drain_count with an atomic and only then
takes e_drain_mtx to wake the drainer. epoch_drain_callbacks() holds
that mutex while it schedules the drain callbacks and checks the count
before it sleeps. If the last callback of the final pass runs in that
window, the drainer sees zero, does not sleep, and returns before the
callback has locked and unlocked the mutex. epoch_free() then destroys
the mutex and zeroes the epoch under it. Its epoch_wait(global_epoch)
does not help, since epoch_call_task() runs the callbacks after leaving
the global epoch.
Each CPU's drain callback drops the count once, so the one that finds
it at one is the last. Have that callback take the mutex before it
drops the count to zero. The drainer reads the count only with the
mutex held, so it cannot see zero until that callback has dropped the
mutex, and the callback does not touch the epoch after that.
Use refcount(9) for the count, so that the other callbacks still drop
it without the mutex, now with release semantics that the plain atomic
lacked. Taking the mutex for every decrement instead made each drain
30-50 us slower on an idle 8-CPU VM.
Only epoch_free() is affected, and its only in-tree caller is the
epoch_test module. For other callers of epoch_drain_callbacks() the
epoch stays valid, and a late wakeup is harmless.
Fixes: 131b2b7658d7 ("Implement API for draining EPOCH(9) callbacks.")
MFC after: 1 week
Sponsored by: Rubicon Communications, LLC ("Netgate")