From a35880eecd2bf2bdb2646eda3fdc98d04e0efe54 Mon Sep 17 00:00:00 2001 From: Adrian Szyndela Date: Fri, 11 Jun 2021 10:56:57 +0200 Subject: [PATCH] i2c: implement SHARED/PRIVATE with flock() --- src/peripheral_i2c.c | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/peripheral_i2c.c b/src/peripheral_i2c.c index f27b747..329dfb2 100644 --- a/src/peripheral_i2c.c +++ b/src/peripheral_i2c.c @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include +#include #include #include "peripheral_io.h" @@ -59,10 +61,13 @@ int peripheral_i2c_open_flags(int bus, int address, peripheral_open_flags_e flag { peripheral_i2c_h handle; int ret = PERIPHERAL_ERROR_NONE; + int lock_type = LOCK_EX; RETVM_IF(__is_feature_supported() == false, PERIPHERAL_ERROR_NOT_SUPPORTED, "I2C feature is not supported"); RETVM_IF(i2c == NULL, PERIPHERAL_ERROR_INVALID_PARAMETER, "Invalid i2c handle"); RETVM_IF(bus < 0 || address < 0, PERIPHERAL_ERROR_INVALID_PARAMETER, "Invalid parameter"); + RETVM_IF(flags != PERIPHERAL_OPEN_FLAGS_PRIVATE && flags != PERIPHERAL_OPEN_FLAGS_SHARED, + PERIPHERAL_ERROR_INVALID_PARAMETER, "Invalid flags"); handle = (peripheral_i2c_h)malloc(sizeof(struct _peripheral_i2c_s)); if (handle == NULL) { @@ -74,7 +79,23 @@ int peripheral_i2c_open_flags(int bus, int address, peripheral_open_flags_e flag if (ret != PERIPHERAL_ERROR_NONE) { _E("Failed to open i2c communication, ret : %d", ret); free(handle); - handle = NULL; + return ret; + } + + if (flags == PERIPHERAL_OPEN_FLAGS_SHARED) + lock_type = LOCK_SH; + + if (flock(handle->fd, lock_type | LOCK_NB)) { + if (errno == EWOULDBLOCK) { + _E("bus : %d, address : 0x%x is not available", bus, address); + ret = PERIPHERAL_ERROR_RESOURCE_BUSY; + } else { + _E("bus : %d, address : 0x%x flock() error: %d", bus, address, errno); + ret = PERIPHERAL_ERROR_IO_ERROR; + } + close(handle->fd); + free(handle); + return ret; } *i2c = handle; -- 2.7.4