Introduce pet-projects dir
[lcapit-junk-code.git] / linux-kernel / debugfs / debugfs-example.c
blob9a598c16bb380fc70be4eaed3804aeceae11411f
1 /*
2 * Debugfs example module.
3 *
4 * Mount debugfs with:
5 *
6 * # mount -t debugfs debugfs /proc/sys/debugfs
7 *
8 * After loading this module, a directory called 'debugfs-example'
9 * will be created under debugfs root dir and it will have two
10 * files in it.
12 * One file is called 'stats_file' and it's an example of file
13 * handling with debugfs. The other file is called 'statfs_u32'
14 * and its an example of integer handling.
16 * Both files shows the contents of the stats_counter variable.
18 * Luiz Fernando N. Capitulino
19 * <lcapitulino@gmail.com>
21 #include <linux/init.h>
22 #include <linux/module.h>
23 #include <linux/debugfs.h>
25 static struct dentry *root_dir, *dentry_stats, *dentry_u32;
26 static u32 stats_counter;
28 static int stats_open(struct inode *inode, struct file *file)
30 ++stats_counter;
31 return 0;
34 #define TMPBUFSIZE 12 // random value
36 static ssize_t stats_read(struct file *file, char __user *buf, size_t nbytes,
37 loff_t *ppos)
39 size_t maxlen;
40 char tmpbuf[TMPBUFSIZE];
42 maxlen = snprintf(tmpbuf, TMPBUFSIZE, "stats: %u\n", stats_counter);
43 if (maxlen > TMPBUFSIZE)
44 maxlen = TMPBUFSIZE;
46 return simple_read_from_buffer(buf, nbytes, ppos, tmpbuf, maxlen);
49 static const struct file_operations stats_operations = {
50 .owner = THIS_MODULE,
51 .open = stats_open,
52 .read = stats_read,
55 static int __init debugfs_example_init(void)
57 root_dir = debugfs_create_dir("debugfs-example", NULL);
58 if (!root_dir) {
59 printk(KERN_ERR "Could not create main directory\n");
60 return -ENOMEM;
63 dentry_stats = debugfs_create_file("stats_file",
64 S_IFREG|S_IRUGO|S_IWUSR,
65 root_dir, NULL, &stats_operations);
66 if (!dentry_stats) {
67 printk(KERN_ERR "ERROR: could not create stats_file\n");
68 debugfs_remove(root_dir);
69 return -ENOMEM;
72 dentry_u32 = debugfs_create_u32("stats_u32",
73 S_IFREG|S_IRUGO|S_IWUSR,
74 root_dir, &stats_counter);
75 if (!dentry_u32) {
76 printk(KERN_ERR "ERROR: could not create stats_u32");
77 debugfs_remove(dentry_stats);
78 debugfs_remove(root_dir);
79 return -ENOMEM;
82 return 0;
85 static void __exit debugfs_example_exit(void)
87 debugfs_remove(dentry_stats);
88 debugfs_remove(dentry_u32);
89 debugfs_remove(root_dir);
92 module_init(debugfs_example_init);
93 module_exit(debugfs_example_exit);
95 MODULE_LICENSE("GPL");
96 MODULE_DESCRIPTION("A debugfs example module");
97 MODULE_AUTHOR("Luiz Capitulino <lcapitulino@gmail.com>");