Skip to content

Commit 1ed317d

Browse files
veidongrayyivies
and
yivies
authored
Simplify character device registration (#9)
Co-authored-by: yivies <[email protected]>
1 parent ce1ed33 commit 1ed317d

File tree

1 file changed

+5
-24
lines changed

1 file changed

+5
-24
lines changed

fibdrv.c

Lines changed: 5 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ MODULE_VERSION("0.1");
2020
#define MAX_LENGTH 92
2121

2222
static dev_t fib_dev = 0;
23-
static struct cdev *fib_cdev;
2423
static struct class *fib_class;
2524
static DEFINE_MUTEX(fib_mutex);
25+
static int major = 0, minor = 0;
2626

2727
static long long fib_sequence(long long k)
2828
{
@@ -107,34 +107,17 @@ const struct file_operations fib_fops = {
107107
static int __init init_fib_dev(void)
108108
{
109109
int rc = 0;
110-
111110
mutex_init(&fib_mutex);
112111

113112
// Let's register the device
114113
// This will dynamically allocate the major number
115-
rc = alloc_chrdev_region(&fib_dev, 0, 1, DEV_FIBONACCI_NAME);
116-
117-
if (rc < 0) {
118-
printk(KERN_ALERT
119-
"Failed to register the fibonacci char device. rc = %i",
120-
rc);
121-
return rc;
122-
}
123-
124-
fib_cdev = cdev_alloc();
125-
if (fib_cdev == NULL) {
126-
printk(KERN_ALERT "Failed to alloc cdev");
127-
rc = -1;
128-
goto failed_cdev;
129-
}
130-
fib_cdev->ops = &fib_fops;
131-
rc = cdev_add(fib_cdev, fib_dev, 1);
132-
114+
rc = major = register_chrdev(major, DEV_FIBONACCI_NAME, &fib_fops);
133115
if (rc < 0) {
134116
printk(KERN_ALERT "Failed to add cdev");
135117
rc = -2;
136118
goto failed_cdev;
137119
}
120+
fib_dev = MKDEV(major, minor);
138121

139122
fib_class = class_create(THIS_MODULE, DEV_FIBONACCI_NAME);
140123

@@ -153,9 +136,8 @@ static int __init init_fib_dev(void)
153136
failed_device_create:
154137
class_destroy(fib_class);
155138
failed_class_create:
156-
cdev_del(fib_cdev);
157139
failed_cdev:
158-
unregister_chrdev_region(fib_dev, 1);
140+
unregister_chrdev(major, DEV_FIBONACCI_NAME);
159141
return rc;
160142
}
161143

@@ -164,8 +146,7 @@ static void __exit exit_fib_dev(void)
164146
mutex_destroy(&fib_mutex);
165147
device_destroy(fib_class, fib_dev);
166148
class_destroy(fib_class);
167-
cdev_del(fib_cdev);
168-
unregister_chrdev_region(fib_dev, 1);
149+
unregister_chrdev(major, DEV_FIBONACCI_NAME);
169150
}
170151

171152
module_init(init_fib_dev);

0 commit comments

Comments
 (0)