Use spinlock to busy wait.
[cascardo/kernel/samples/char2/.git] / hellochar.c
1 /*
2  *  Copyright (C) 2010  Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <linux/module.h>
20 #include <linux/fs.h>
21 #include <linux/cdev.h>
22 #include <linux/slab.h>
23 #include <linux/spinlock.h>
24
25 MODULE_LICENSE("GPL");
26
27 static dev_t devnum;
28 static struct cdev *dev;
29 static const char default_greeting[] = "Hello, World!\n";
30
31 static DEFINE_SPINLOCK(hello_lock);
32
33 static int hello_open(struct inode *ino, struct file *fp)
34 {
35         return 0;
36 }
37
38 static ssize_t hello_read(struct file *fp, char __user *buf, size_t sz,
39         loff_t *pos)
40 {
41         int i = 1 << 28;
42         spin_lock(&hello_lock);
43         while (i--)
44                 cpu_relax();
45         spin_unlock(&hello_lock);
46         return 0;
47 }
48
49 static ssize_t hello_write(struct file *fp, const char __user *buf, size_t sz,
50         loff_t *pos)
51 {
52         return 0;
53 }
54
55 static int hello_release(struct inode *ino, struct file *fp)
56 {
57         return 0;
58 }
59
60 static const struct file_operations hello_fops = {
61         .owner = THIS_MODULE,
62         .open = hello_open,
63         .release = hello_release,
64         .read = hello_read,
65         .write = hello_write,
66 };
67
68 static int __init ch_init(void)
69 {
70         int r = 0;
71         r = alloc_chrdev_region(&devnum, 0, 256, "hello");
72         if (r)
73                 goto reg_out;
74         dev = cdev_alloc();
75         if (!dev) {
76                 r = -ENOMEM;
77                 goto cdev_out;
78         }
79         dev->ops = &hello_fops;
80         r = cdev_add(dev, devnum, 256);
81         if (r)
82                 goto add_out;
83         printk(KERN_DEBUG "Allocate major %d\n", MAJOR(devnum));
84         return 0;
85 add_out:
86         kfree(dev);
87 cdev_out:
88         unregister_chrdev_region(devnum, 256);
89 reg_out:
90         return r;
91 }
92
93 static void __exit ch_exit(void)
94 {
95         cdev_del(dev);
96         unregister_chrdev_region(devnum, 256);
97 }
98
99 module_init(ch_init);
100 module_exit(ch_exit);