Splaty
Splaty

Reputation: 634

Linux's i2c dev interface with multiple processes

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:

  1. 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?
  2. 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.

Upvotes: 3

Views: 4765

Answers (1)

Thomas Petazzoni
Thomas Petazzoni

Reputation: 5966

The I2C slave address set by the I2C_SLAVE ioctl() is stored in an i2c_client that is allocated everytime /dev/i2c-X is opened. So this information is local to each "opening" of /dev/i2c-X.

Regarding setting the page register in your I2C device, it's OK as long as no other processes talk to the same I2C device.

Generally speaking, if you're concerned about access to one device by multiple processes, you should rather write a Linux kernel driver for that device.

Upvotes: 4

Related Questions