#include <linux/module.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#define DEVICE_NAME "sky"
#define DATAALIGN (sizeof(unsigned long) - 1)
struct char_device
{
struct cdev cdev;
dev_t devno;
};
struct data_list
{
struct list_head list;
unsigned int dlen;
char data[0];
};
static struct char_device dev;
static struct list_head head = LIST_HEAD_INIT(head);
static ssize_t char_read(struct file *filp, char __user *buf, size_t count, loff_t *pos)
{
struct data_list *node;
struct list_head *list;
for (list = head.next; list != &head; list = list->next)
{
node = container_of(list, struct data_list, list);
if (copy_to_user(buf, node->data, node->dlen))
{
goto copy_err;
}
else
{
return node->dlen;
}
}
return count;
copy_err:
return -EFAULT;
}
static ssize_t char_write(struct file *filp, const char __user *buf, size_t count, loff_t *pos)
{
struct data_list *new;
size_t size;
size = (sizeof(struct data_list) + count + DATAALIGN) & ~DATAALIGN;
new = kmalloc(size, GFP_KERNEL);
if (!new)
{
goto kmalloc_err;
}
memset(new, '\0', size);
if (copy_from_user(new->data, buf, count))
{
goto copy_err;
}
else
{
new->dlen = count;
list_add(&new->list, &head);
}
return count;
copy_err:
kfree(new);
kmalloc_err:
return -EFAULT;
}
static struct file_operations fops =
{
.read = char_read,
.write = char_write,
};
static int __init sky_init(void)
{
if (alloc_chrdev_region(&dev.devno, 0, 1, DEVICE_NAME) < 0)
{
goto alloc_err;
}
cdev_init(&dev.cdev, &fops);
dev.cdev.owner = THIS_MODULE;
dev.cdev.ops = &fops;
if (cdev_add(&dev.cdev, dev.devno, 1) < 0)
{
goto add_err;
}
return 0;
add_err:
unregister_chrdev_region(dev.devno, 1);
alloc_err:
return -1;
}
static void __exit sky_exit(void)
{
struct list_head *list;
struct data_list *node;
while ((list = head.next) != &head)
{
list_del(list);
node = container_of(list, struct data_list, list);
if (node)
{
kfree(node);
}
}
cdev_del(&dev.cdev);
unregister_chrdev_region(dev.devno, 1);
}
MODULE_LICENSE("GPL");
module_init(sky_init);
module_exit(sky_exit);
|