#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/slab.h>
+#include <linux/mutex.h>
#include <asm/uaccess.h>
MODULE_LICENSE("GPL");
size_t len;
char buffer[0];
};
+static struct hello_buffer *hello;
+static DEFINE_MUTEX(hello_mtx);
static int hello_open(struct inode *ino, struct file *fp)
{
- struct hello_buffer *hello = kzalloc(sizeof(*hello) + MAXLEN, GFP_KERNEL);
- if (!hello)
- return -ENOMEM;
- memcpy(hello->buffer, default_greeting, sizeof(default_greeting));
- hello->len = sizeof(default_greeting);
- fp->private_data = hello;
+ if (mutex_lock_interruptible(&hello_mtx))
+ return -ERESTARTSYS;
+ 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;
+ mutex_unlock(&hello_mtx);
return 0;
}
static ssize_t hello_read(struct file *fp, char __user *buf, size_t sz,
loff_t *pos)
{
- struct hello_buffer *hello = fp->private_data;
int r;
+ if (mutex_lock_interruptible(&hello_mtx))
+ return -ERESTARTSYS;
if (sz + *pos > hello->len)
sz = hello->len - *pos;
r = copy_to_user(buf, hello->buffer + *pos, sz);
+ mutex_unlock(&hello_mtx);
if (r)
return -EFAULT;
*pos += sz;
static ssize_t hello_write(struct file *fp, const char __user *buf, size_t sz,
loff_t *pos)
{
- struct hello_buffer *hello = fp->private_data;
int r;
+ if (mutex_lock_interruptible(&hello_mtx))
+ return -ERESTARTSYS;
if (sz + *pos > MAXLEN)
sz = MAXLEN - *pos;
r = copy_from_user(hello->buffer + *pos, buf, sz);
- if (r)
+ if (r) {
+ mutex_unlock(&hello_mtx);
return -EFAULT;
+ }
*pos += sz;
if (hello->len < *pos)
hello->len = *pos;
+ mutex_unlock(&hello_mtx);
return sz;
}
static int hello_release(struct inode *ino, struct file *fp)
{
- kfree(fp->private_data);
return 0;
}
static int __init ch_init(void)
{
int r = 0;
+ hello = kzalloc(sizeof(*hello) + MAXLEN, GFP_KERNEL);
+ if (!hello) {
+ r = -ENOMEM;
+ goto out;
+ }
+ memcpy(hello->buffer, default_greeting, sizeof(default_greeting));
+ hello->len = sizeof(default_greeting);
r = alloc_chrdev_region(&devnum, 0, 256, "hello");
if (r)
- goto out;
+ goto reg_out;
dev = cdev_alloc();
if (!dev) {
r = -ENOMEM;
kfree(dev);
cdev_out:
unregister_chrdev_region(devnum, 256);
+reg_out:
+ kfree(hello);
out:
return r;
}
{
cdev_del(dev);
unregister_chrdev_region(devnum, 256);
+ kfree(hello);
}
module_init(ch_init);