From 06b75942ccd03d61e150dfc9e57dc12757a5b777 Mon Sep 17 00:00:00 2001 From: linD026 <66012716+linD026@users.noreply.github.com> Date: Thu, 26 Aug 2021 03:16:17 +0800 Subject: [PATCH] Fix incorrect major number registration in chardev (#77) chardev2.c demonstrates the ioctl operation with static major number MAJOR_NUM, but there also exists "Major," the dynamic one, which results in registration and deregistration on different device. Once the module remove, it cannot insert again: $ sudo insmod chardev2.ko $ sudo rmmod chardev2 $ cat /proc/devices Character devices: ... 100 char_dev $ sudo insmod chardev2.ko insmod: ERROR: could not insert module chardev2.ko: Device or resource busy This patch removed the use of dynamic major number. --- examples/chardev2.c | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/examples/chardev2.c b/examples/chardev2.c index 8916901..370f772 100644 --- a/examples/chardev2.c +++ b/examples/chardev2.c @@ -30,8 +30,6 @@ static char Message[BUF_LEN]; */ static char *Message_Ptr; -/* Major number assigned to our device driver */ -static int Major; static struct class *cls; /* This is called whenever a process attempts to open the device file */ @@ -201,10 +199,8 @@ static int __init chardev2_init(void) return ret_val; } - Major = ret_val; - cls = class_create(THIS_MODULE, DEVICE_FILE_NAME); - device_create(cls, NULL, MKDEV(Major, MAJOR_NUM), NULL, DEVICE_FILE_NAME); + device_create(cls, NULL, MKDEV(MAJOR_NUM, 0), NULL, DEVICE_FILE_NAME); pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); @@ -214,11 +210,11 @@ static int __init chardev2_init(void) /* Cleanup - unregister the appropriate file from /proc */ static void __exit chardev2_exit(void) { - device_destroy(cls, MKDEV(Major, 0)); + device_destroy(cls, MKDEV(MAJOR_NUM, 0)); class_destroy(cls); /* Unregister the device */ - unregister_chrdev(Major, DEVICE_NAME); + unregister_chrdev(MAJOR_NUM, DEVICE_NAME); } module_init(chardev2_init);