mutex locking on file descriptors?

Wall, Stephen stephen.wall at redcom.com
Mon Jul 13 16:31:17 UTC 2020


> This heavily depends on exact "issues" you are try to avoid, amount of data wrote or read,
> used protocol and driver.

>

> In some cases, for some types of descriptors there is atomicy for small writes.
> But in general you need some kind of locking. Else you may get unexpected results,
> f.e. some part of data read by one thread and another part by another thread.

OK, more details.  The device driver is providing unfiltered access to a bulk endpoint on a Silicon Labs device, which speaks a protocol defined by SILabs supporting packets of up to 64 bytes in length.  Most are much shorter that that, 10-20 bytes.  The device's datasheet doesn't state it, but in testing I've never seen one of these packets fragmented.

I will have a thread that writes queries on a timed basis, and reads replies to those queries, as well as hardware-triggered messages, using kqueue to receive notification that data is available.  It will process the messages and store relevant data in class variables for consumption as needed.

Where I have a concern is that I'm also providing functions to bypass this mechanism, and give consumers a way to send custom messages to the device, which means a write can also happen outside the thread discussed above.  I thought that I needed a mutex to protect against a context switch happening in the middle of one or the other of the accesses, until my co-worker's comments.    This comment from usbdi.h seems to support that read and write are already protected:

/*
 * Locking note for the following functions.  All the
 * "usb_fifo_cmd_t" and "usb_fifo_filter_t" functions are called
 * locked. The others are called unlocked.
 */

I guess I will assume the mutex is needed, unless someone can definitively say it's not.

Thank you, Eugene.

- Steve Wall

________________________________



More information about the freebsd-hackers mailing list