1
#include <linux/init.h>
2
#include <linux/module.h>
3
#include <linux/device.h>
4
#include <linux/types.h>
5
#include <linux/cdev.h>
7
#include <linux/slab.h>
16
MODULE_LICENSE("GPL v2");
17
MODULE_AUTHOR("Suren A. Chilingaryan <csa@suren.me>");
18
MODULE_DESCRIPTION("Testing module");
19
MODULE_VERSION("0.0.1");
21
int test_minors = TEST_MINORS;
23
module_param(test_minors, int, S_IRUGO);
26
static dev_t test_devno; /**< major number */
27
static test_dev_t **test_devs = NULL; /**< per-device context */
28
static spinlock_t test_devs_lock; /**< lock protecting creation/destruction of devices */
29
static struct class *test_class; /**< device class */
31
static void test_module_destroy_cdev(test_dev_t *test)
34
test_sysfs_free(test);
35
device_destroy(test_class, test->devno);
37
cdev_del(&test->cdev);
41
static int test_module_setup_cdev(void)
48
test = kmalloc(sizeof(test_dev_t), GFP_KERNEL);
50
mod_info("Couldn't allocate memory. Device is not created.\n");
54
cdev_init(&test->cdev, test_get_fops());
55
test->cdev.owner = THIS_MODULE;
56
test->cdev.ops = test_get_fops();
58
spin_lock(&test_devs_lock);
59
for (i = 0; i < test_minors; i++) {
64
if (i == test_minors) {
65
mod_info("No free minor numbers left");
70
devno = MKDEV(MAJOR(test_devno), MINOR(test_devno) + i);
73
err = cdev_add(&test->cdev, devno, 1);
75
mod_info("Error %d adding device kmm%d", err, i);
79
test->dev = device_create(test_class, NULL, devno, test, TEST_NODE_FMT, MINOR(test_devno) + i);
81
mod_info("Error creating /dev/%s%d\n", TEST_NODE, MINOR(test_devno) + i);
84
dev_set_drvdata(test->dev, test);
87
spin_unlock(&test_devs_lock);
89
err = test_sysfs_init(test);
90
if (err) goto fail_sysfs;
92
mod_info("Device /dev/%s%d added\n", TEST_NODE, MINOR(test_devno) + i);
97
spin_unlock(&test_devs_lock);
99
test_module_destroy_cdev(test);
104
static void test_module_cleanup(void)
109
for (i = 0; i < test_minors; i++) {
111
test_module_destroy_cdev(test_devs[i]);
118
class_destroy(test_class);
120
unregister_chrdev_region(test_devno, test_minors);
123
static int __init test_module_init(void)
127
spin_lock_init(&test_devs_lock);
129
if ((err = alloc_chrdev_region(&test_devno, 0, test_minors, TEST_NODE))) {
130
mod_info("Couldn't allocate chrdev region. Module not loaded.\n");
131
goto alloc_chrdev_fail;
134
test_class = class_create(THIS_MODULE, TEST_NODE);
135
if (IS_ERR(test_class)) {
136
mod_info("No sysfs support. Module not loaded.\n");
140
test_devs = kmalloc(test_minors * sizeof(test_dev_t*), GFP_KERNEL);
142
mod_info("Couldn't allocate memory. Module not loaded.\n");
145
memset(test_devs, 0, test_minors * sizeof(test_dev_t*));
147
mod_info("Major %d allocated to node '%s'\n", MAJOR(test_devno), TEST_NODE);
149
err = test_module_setup_cdev();
156
test_module_cleanup();
162
static void __exit test_module_exit(void)
164
test_module_cleanup();
167
module_init(test_module_init);
168
module_exit(test_module_exit);