[ACCEPTED]-Linux Kernel Modules: When to use try_module_get / module_put-kernel-module

Accepted answer
Score: 24

You should essentially never have to use 39 try_module_get(THIS_MODULE); pretty much 38 all such uses are unsafe since if you are 37 already in your module, it's too late to 36 bump the reference count -- there will always 35 be a (small) window where you are executing 34 code in your module but haven't incremented 33 the reference count. If someone removes 32 the module exactly in that window, then 31 you're in the bad situation of running code 30 in an unloaded module.

The particular example 29 you linked in LKMPG where the code does 28 try_module_get() in the open() method would 27 be handled in the modern kernel by setting 26 the .owner field in struct file_operations:

struct file_operations fops = {
        .owner = THIS_MODULE,
        .open = device_open,

this 25 will make the VFS code take a reference 24 to the module before calling into it, which eliminates 23 the unsafe window -- either the try_module_get() will 22 succeed before the call to .open(), or the 21 try_module_get() will fail and the VFS will 20 never call into the module. In either case, we 19 never run code from a module that has already 18 been unloaded.

The only good time to use 17 try_module_get() is when you want to take 16 a reference on a different module before calling 15 into it or using it in some way (eg as the 14 file open code does in the example I explained 13 above). There are a number of uses of try_module_get(THIS_MODULE) in 12 the kernel source but most if not all of 11 them are latent bugs that should be cleaned 10 up.

The reason you were not able to unload 9 the sched example is that your

$ tail /proc/sched -f &

command keeps 8 /proc/sched open, and because of

        Our_Proc_File->owner = THIS_MODULE;

in the sched.c 7 code, opening /proc/sched increments the 6 reference count of the sched module, which 5 accounts for the 1 reference that your lsmod 4 shows. From a quick skim of the rest of 3 the code, I think if you release /proc/sched 2 by killing your tail command, you would 1 be able to remove the sched module.

More Related questions