Hot-unplugging a sound device, such as a USB sound card, whilst being
consumed by an application, results in an infinite loop until either the
application closes the device's file descriptor, or the channel
automatically times out after hw.snd.timeout seconds. In the case of a
detach however, the timeout approach is still not ideal, since we want
all resources to be released immediatelly, without waiting for N seconds
until we can use the bus again.
The timeout mechanism works by calling chn_sleep() in chn_read() and
chn_write() (see pcm/channel.c) in order to send the thread to sleep,
using cv_timedwait_sig(). Since chn_sleep() sets the CHN_F_SLEEPING flag
while waiting for cv_timedwait_sig() to return, we can test this flag in
pcm_unregister() (called during detach) and wakeup the sleeping
thread(s) to immediately kill the channel(s) being consumed.
To avoid sleeping until all clones and/or the mixer have been unref'd,
in case an application refuses to close the descriptor, we use
destroy_dev_sched_cb() instead of destroy_dev(). This way the device can
detach (and re-attach) asynchronously, leaving the devfs node(s) in an
orphan state waiting for clean up when the application releases the
descriptor.
Sponsored by: The FreeBSD Foundation
MFC after: 3 weeks
PR: 194727