Use waitqueue instead of completion.
[cascardo/kernel/samples/waitqueue/.git] / test_waitqueue.c
1 /*
2  *  Copyright (C) 2009  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
20 #include <linux/module.h>
21 #include <linux/sched.h>
22 #include <linux/wait.h>
23 #include <linux/mutex.h>
24 #include <linux/proc_fs.h>
25 #include <linux/uaccess.h>
26
27 MODULE_LICENSE("GPL");
28
29 DECLARE_MUTEX(test_mutex);
30 DECLARE_WAIT_QUEUE_HEAD(test_wait);
31
32 static char test_buffer[16];
33 static size_t test_len;
34
35 static int test_open(struct inode* i, struct file *f)
36 {
37         return 0;
38 }
39
40 static ssize_t test_read(struct file *f, char * __user buf,
41                          size_t s, loff_t *o)
42 {
43         int r;
44         if (wait_event_interruptible(test_wait, test_len > 0))
45                 return -ERESTARTSYS;
46         if (down_interruptible(&test_mutex))
47                 return -ERESTARTSYS;
48         if (s > test_len)
49                 s = test_len;
50         test_len = 0;
51         r = copy_to_user(buf, test_buffer, s);
52         up(&test_mutex);
53         if (r)
54                 return -EFAULT;
55         *o += s;
56         return s;
57 }
58
59 static ssize_t test_write(struct file *f, const char * __user buf,
60                           size_t s, loff_t *o)
61 {
62         int r;
63         if (s > sizeof(test_buffer))
64                 s = sizeof(test_buffer);
65         if (down_interruptible(&test_mutex))
66                 return -ERESTARTSYS;
67         r = copy_from_user(test_buffer, buf, s);
68         test_len = s;
69         up(&test_mutex);
70         if (r)
71                 return -EFAULT;
72         wake_up(&test_wait);
73         *o += s;
74         return s;
75 }
76
77 static const struct file_operations test_fops =
78 {
79         .open = test_open,
80         .read = test_read,
81         .write = test_write,
82 };
83
84 static int test_wait_init(void)
85 {
86         proc_create("test_wait", 0666, NULL, &test_fops);
87         return 0;
88 }
89
90 static void test_wait_exit(void)
91 {
92         remove_proc_entry("test_wait", NULL);
93 }
94
95 module_init(test_wait_init);
96 module_exit(test_wait_exit);