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.
This commit is contained in:
linD026 2021-08-26 03:16:17 +08:00 committed by GitHub
parent c97348d2d5
commit 06b75942cc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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);