I've written a quick userspace program to access i2c devices using the i2c dev interface described here: https://www.kernel.org/doc/Documentation/i2c/dev-interface
The problem is that I'm not sure how to make this multi-process and multi-thread safe, or if Linux already handles this.
Here's the barebones of the code:
#include <linux/i2c-dev.h>
void read_from_device(void)
{
int result;
file_desc = open(/dev/i2c-2, O_RDWR);
/* Possible critical section #1 starting here? */
ioctl(file_desc, I2C_SLAVE, device_address);
/* Possible critical section #2 starting here
* This device requires writing to a page register first
* before accessing the wanted register */
i2c_smbus_write_byte_data(file_desc, DEVICE_PAGE_ADDRESS, page_number);
/* I don't want another process in come in between here and
* setting a different page address before accessing the register*/
result = i2c_smbus_read_byte_data(file_desc, device_register_address);
/* Critical section end for both possibilities */
close(file_desc);
}
So the 2 possible critical sections:
- Does Linux's i2c dev interface handle multiple processes setting the I2C_SLAVE? Meaning: once I set the I2C_SLAVE for this adapter /dev/i2c-2, can another process come in and change it to another device on the bus?
- I don't want another process to come in after setting the page register on the device and then setting it's own page_number, then my read would be incorrect. Would a process-shared mutex as described here be appropriate?
Someone else posed a similar problem here and the response was that Linux handles multiple process access to the same adapter very well. I wanted to confirm what that means and what parts of thread-safe access I need to worry about from userspace.