2 * Sample dynamic sized record fifo implementation
4 * Copyright (C) 2010 Stefani Seibold <stefani@seibold.net>
6 * Released under the GPL version 2 only.
10 #include <linux/init.h>
11 #include <linux/module.h>
12 #include <linux/proc_fs.h>
13 #include <linux/mutex.h>
14 #include <linux/kfifo.h>
17 * This module shows how to create a variable sized record fifo.
20 /* fifo size in elements (bytes) */
23 /* name of the proc entry */
24 #define PROC_FIFO "record-fifo"
26 /* lock for procfs read access */
27 static DEFINE_MUTEX(read_lock
);
29 /* lock for procfs write access */
30 static DEFINE_MUTEX(write_lock
);
33 * define DYNAMIC in this example for a dynamically allocated fifo.
35 * Otherwise the fifo storage will be a part of the fifo structure.
42 * struct kfifo_rec_ptr_1 and STRUCT_KFIFO_REC_1 can handle records of a
43 * length between 0 and 255 bytes.
45 * struct kfifo_rec_ptr_2 and STRUCT_KFIFO_REC_2 can handle records of a
46 * length between 0 and 65535 bytes.
50 struct kfifo_rec_ptr_1 test
;
53 typedef STRUCT_KFIFO_REC_1(FIFO_SIZE
) mytest
;
58 static int __init
testfunc(void)
63 struct { unsigned char buf
[6]; } hello
= { "hello" };
65 printk(KERN_INFO
"record fifo test start\n");
67 kfifo_in(&test
, &hello
, sizeof(hello
));
69 /* show the size of the next record in the fifo */
70 printk(KERN_INFO
"fifo peek len: %u\n", kfifo_peek_len(&test
));
72 /* put in variable length data */
73 for (i
= 0; i
< 10; i
++) {
74 memset(buf
, 'a' + i
, i
+ 1);
75 kfifo_in(&test
, buf
, i
+ 1);
78 printk(KERN_INFO
"fifo len: %u\n", kfifo_len(&test
));
80 /* show the first record without removing from the fifo */
81 ret
= kfifo_out_peek(&test
, buf
, sizeof(buf
));
83 printk(KERN_INFO
"%.*s\n", ret
, buf
);
85 /* print out all records in the fifo */
86 while (!kfifo_is_empty(&test
)) {
87 ret
= kfifo_out(&test
, buf
, sizeof(buf
));
88 printk(KERN_INFO
"%.*s\n", ret
, buf
);
94 static ssize_t
fifo_write(struct file
*file
, const char __user
*buf
,
95 size_t count
, loff_t
*ppos
)
100 if (mutex_lock_interruptible(&write_lock
))
103 ret
= kfifo_from_user(&test
, buf
, count
, &copied
);
105 mutex_unlock(&write_lock
);
107 return ret
? ret
: copied
;
110 static ssize_t
fifo_read(struct file
*file
, char __user
*buf
,
111 size_t count
, loff_t
*ppos
)
116 if (mutex_lock_interruptible(&read_lock
))
119 ret
= kfifo_to_user(&test
, buf
, count
, &copied
);
121 mutex_unlock(&read_lock
);
123 return ret
? ret
: copied
;
126 static const struct file_operations fifo_fops
= {
127 .owner
= THIS_MODULE
,
132 static int __init
example_init(void)
137 ret
= kfifo_alloc(&test
, FIFO_SIZE
, GFP_KERNEL
);
139 printk(KERN_ERR
"error kfifo_alloc\n");
147 if (proc_create(PROC_FIFO
, 0, NULL
, &fifo_fops
) == NULL
) {
156 static void __exit
example_exit(void)
158 remove_proc_entry(PROC_FIFO
, NULL
);
164 module_init(example_init
);
165 module_exit(example_exit
);
166 MODULE_LICENSE("GPL");
167 MODULE_AUTHOR("Stefani Seibold <stefani@seibold.net>");