From 76680d10903416190497df7dc25d4469401c53bb Mon Sep 17 00:00:00 2001 From: Thadeu Lima de Souza Cascardo Date: Thu, 20 May 2010 09:35:22 -0400 Subject: [PATCH] Serialize access to global structure using semaphore. --- hellochar.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/hellochar.c b/hellochar.c index 71605f6..85510f7 100644 --- a/hellochar.c +++ b/hellochar.c @@ -20,6 +20,7 @@ #include #include #include +#include #include MODULE_LICENSE("GPL"); @@ -33,16 +34,19 @@ struct hello_buffer { size_t len; char buffer[0]; }; -struct hello_buffer *hello; +static struct hello_buffer *hello; +static DECLARE_MUTEX(hello_mtx); static int hello_open(struct inode *ino, struct file *fp) { + down(&hello_mtx); if (fp->f_flags & O_TRUNC) { memset(hello->buffer, 0, MAXLEN); hello->len = 0; } if (fp->f_flags & O_APPEND) fp->f_pos = hello->len; + up(&hello_mtx); return 0; } @@ -50,9 +54,11 @@ static ssize_t hello_read(struct file *fp, char __user *buf, size_t sz, loff_t *pos) { int r; + down(&hello_mtx); if (sz + *pos > hello->len) sz = hello->len - *pos; r = copy_to_user(buf, hello->buffer + *pos, sz); + up(&hello_mtx); if (r) return -EFAULT; *pos += sz; @@ -63,14 +69,18 @@ static ssize_t hello_write(struct file *fp, const char __user *buf, size_t sz, loff_t *pos) { int r; + down(&hello_mtx); if (sz + *pos > MAXLEN) sz = MAXLEN - *pos; r = copy_from_user(hello->buffer + *pos, buf, sz); - if (r) + if (r) { + up(&hello_mtx); return -EFAULT; + } *pos += sz; if (hello->len < *pos) hello->len = *pos; + up(&hello_mtx); return sz; } -- 2.20.1