1 #include <linux/module.h>
2 /* Needed for struct file_operations and others */
4 /* Needed for struct cdev */
5 #include <linux/cdev.h>
6 /* Needed for copying to/from user space */
7 #include <asm/uaccess.h>
8 #include <linux/slab.h>
10 MODULE_LICENSE("GPL");
11 MODULE_AUTHOR("Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>");
12 MODULE_DESCRIPTION("A hello world char device");
13 MODULE_VERSION("1.0.0");
15 /* Message buffer we send to upstream */
16 static char hello_message[] = "hello, world\n";
17 static char goodbye_message[] = "goodbye, world\n";
24 static int helloc_open(struct inode *ino, struct file *filp)
27 printk(KERN_INFO "Opened file with minor %d\n", iminor(ino));
28 msg = kmalloc(sizeof(struct message), GFP_KERNEL);
31 if (iminor(ino) == 0) {
32 msg->text = hello_message;
33 msg->len = sizeof(hello_message);
35 msg->text = goodbye_message;
36 msg->len = sizeof(goodbye_message);
38 filp->private_data = msg;
42 static int helloc_release(struct inode *ino, struct file *filp)
44 kfree(filp->private_data);
48 /* our read function writes our message to the user buffer */
49 static ssize_t helloc_read(struct file *filp, char __user *buf, size_t len,
53 struct message *msg = filp->private_data;
54 /* do not read pass through the size of the message */
56 /* return end of file */
58 /* if len is bigger than the rest of the message, clamp it */
59 if (len > msg->len - *pos)
60 len = msg->len - *pos;
61 /* copy message to user space and return error if it fails */
62 r = copy_to_user(buf, msg->text + *pos, len);
65 /* update the file position */
70 /* we only implement read */
71 static struct file_operations helloc_fops = {
74 .release = helloc_release,
78 /* the device number and the char device struct */
80 static struct cdev *cdev;
82 static int __init helloc_init(void)
85 /* allocate any major number with only one minor */
86 r = alloc_chrdev_region(&dev, 0, 2, "helloc");
90 /* print the major number allocated so we can create our device node */
91 printk(KERN_INFO "Allocated major number %d\n", MAJOR(dev));
92 /* allocate the character device struct */
96 /* set the module owner and the file operations of our chardev */
97 cdev->owner = THIS_MODULE;
98 cdev->ops = &helloc_fops;
99 /* register the chardev to the system */
100 r = cdev_add(cdev, dev, 2);
105 /* release memory allocated to the cdev device */
108 /* release the device number allocated */
109 unregister_chrdev_region(dev, 2);
114 static void __exit helloc_exit(void)
116 /* remove the chardev from the system */
118 /* release the device number allocated */
119 unregister_chrdev_region(dev, 2);
122 module_init(helloc_init);
123 module_exit(helloc_exit);