mutex: return -EAGAIN if trylock fails

This commit is contained in:
anna 2021-08-03 00:07:39 +02:00
parent 33439b2e37
commit 7fa55c8dab
Signed by: fef
GPG key ID: EC22E476DC2D3D84
3 changed files with 33 additions and 21 deletions

View file

@ -4,6 +4,7 @@
#include <ardix/types.h>
#include <errno.h>
#include <toolchain.h>
/**
@ -73,14 +74,17 @@ __always_inline void mutex_unlock(struct mutex *mutex)
/**
* @brief Attempt to acquire an exclusive lock on a mutex.
* The return value is zero if the claim succeeds, and nonzero otherwise.
* The return value is zero if the claim succeeds.
*
* @param mutex Mutex to attempt to lock
* @returns 0 if the lock was acquired, a nonzero value otherwise
* @returns 0 if the lock was acquired, `-EAGAIN` otherwise
*/
__always_inline int mutex_trylock(struct mutex *mutex)
{
return _mutex_trylock(&mutex->lock);
if (_mutex_trylock(&mutex->lock) == 0)
return 0;
else
return -EAGAIN;
}
/**

View file

@ -84,27 +84,31 @@ void file_put(struct file *f)
ssize_t file_read(void *buf, struct file *file, size_t len)
{
ssize_t ret;
mutex_lock(&file->lock);
ssize_t ret = mutex_trylock(&file->lock);
ret = file->device->read(buf, file->device, len, file->pos);
if (file->type == FILE_TYPE_REGULAR && ret > 0)
file->pos += ret;
if (ret == 0) {
ret = file->device->read(buf, file->device, len, file->pos);
if (file->type == FILE_TYPE_REGULAR && ret > 0)
file->pos += ret;
mutex_unlock(&file->lock);
}
mutex_unlock(&file->lock);
return ret;
}
ssize_t file_write(struct file *file, const void *buf, size_t len)
{
ssize_t ret;
mutex_lock(&file->lock);
ssize_t ret = mutex_trylock(&file->lock);
ret = file->device->write(file->device, buf, len, file->pos);
if (file->type == FILE_TYPE_REGULAR && ret > 0)
file->pos += ret;
if (ret == 0) {
ret = file->device->write(file->device, buf, len, file->pos);
if (file->type == FILE_TYPE_REGULAR && ret > 0)
file->pos += ret;
mutex_unlock(&file->lock);
}
mutex_unlock(&file->lock);
return ret;
}

View file

@ -16,11 +16,13 @@ static ssize_t serial_device_read(void *dest, struct device *dev, size_t len, of
{
ssize_t ret;
struct serial_device *serial_dev = container_of(dev, struct serial_device, device);
mutex_lock(&dev->lock);
ret = serial_read(dest, serial_dev, len);
ret = mutex_trylock(&dev->lock);
if (ret == 0) {
ret = serial_read(dest, serial_dev, len);
mutex_unlock(&dev->lock);
}
mutex_unlock(&dev->lock);
return ret;
}
@ -28,11 +30,13 @@ static ssize_t serial_device_write(struct device *dev, const void *src, size_t l
{
ssize_t ret;
struct serial_device *serial_dev = container_of(dev, struct serial_device, device);
mutex_lock(&dev->lock);
ret = serial_write(serial_dev, src, len);
ret = mutex_trylock(&dev->lock);
if (ret == 0) {
ret = serial_write(serial_dev, src, len);
mutex_unlock(&dev->lock);
}
mutex_unlock(&dev->lock);
return ret;
}