Browse Source

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.
linD026 3 years ago
parent
commit
06b75942cc
1 changed files with 3 additions and 7 deletions
  1. 3 7
      examples/chardev2.c

+ 3 - 7
examples/chardev2.c

@@ -30,8 +30,6 @@ static char Message[BUF_LEN];
  */
  */
 static char *Message_Ptr;
 static char *Message_Ptr;
 
 
-/* Major number assigned to our device driver */
-static int Major;
 static struct class *cls;
 static struct class *cls;
 
 
 /* This is called whenever a process attempts to open the device file */
 /* 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;
         return ret_val;
     }
     }
 
 
-    Major = ret_val;
-
     cls = class_create(THIS_MODULE, DEVICE_FILE_NAME);
     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);
     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 */
 /* Cleanup - unregister the appropriate file from /proc */
 static void __exit chardev2_exit(void)
 static void __exit chardev2_exit(void)
 {
 {
-    device_destroy(cls, MKDEV(Major, 0));
+    device_destroy(cls, MKDEV(MAJOR_NUM, 0));
     class_destroy(cls);
     class_destroy(cls);
 
 
     /* Unregister the device */
     /* Unregister the device */
-    unregister_chrdev(Major, DEVICE_NAME);
+    unregister_chrdev(MAJOR_NUM, DEVICE_NAME);
 }
 }
 
 
 module_init(chardev2_init);
 module_init(chardev2_init);