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