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>
10 MODULE_AUTHOR("Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>");
11 MODULE_DESCRIPTION("A hello world char device");
12 MODULE_VERSION("1.0.0");
14 /* Message buffer we send to upstream */
15 static char helloc_message[] = "hello, world\n";
17 /* our read function writes our message to the user buffer */
18 static ssize_t helloc_read(struct file *filp, char __user *buf, size_t len,
22 /* do not read pass through the size of the message */
23 if (*pos >= sizeof(helloc_message))
24 /* return end of file */
26 /* if len is bigger than the rest of the message, clamp it */
27 if (len > sizeof(helloc_message) - *pos)
28 len = sizeof(helloc_message) - *pos;
29 /* copy message to user space and return error if it fails */
30 r = copy_to_user(buf, helloc_message + *pos, len);
33 /* update the file position */
38 /* we only implement read */
39 static struct file_operations helloc_fops = {
44 /* the device number and the char device struct */
46 static struct cdev *cdev;
48 static int __init helloc_init(void)
51 /* allocate any major number with only one minor */
52 r = alloc_chrdev_region(&dev, 0, 1, "helloc");
56 /* print the major number allocated so we can create our device node */
57 printk(KERN_INFO "Allocated major number %d\n", MAJOR(dev));
58 /* allocate the character device struct */
62 /* set the module owner and the file operations of our chardev */
63 cdev->owner = THIS_MODULE;
64 cdev->ops = &helloc_fops;
65 /* register the chardev to the system */
66 r = cdev_add(cdev, dev, 1);
71 /* release memory allocated to the cdev device */
74 /* release the device number allocated */
75 unregister_chrdev_region(dev, 1);
80 static void __exit helloc_exit(void)
82 /* remove the chardev from the system */
84 /* release the device number allocated */
85 unregister_chrdev_region(dev, 1);
88 module_init(helloc_init);
89 module_exit(helloc_exit);