作者b0920075 (Void)
看板LinuxDev
标题[问题] LKMPG chardev 为什麽要用 module_put ?
时间Mon Jun 13 12:21:51 2022
我自己解决了 ^^
================
我昨天在阅读现在新版的 lkmpg ,在其中一个章节有 character device 的 example
code :
https://sysprog21.github.io/lkmpg/#chardevc
前面 6.4 有提过:
Note that you don't have to check the counter within cleanup_module because
the check will be performed for you by the system call sys_delete_module,
defined in include/linux/syscall.h .
You should not use this counter
directly but there are functions defined in include/linux/module.h which
that you increase, decrease and display the counter:
try_module_get(THIS_MODULE) : .........
module_put(THIS_MODULE) : .........
module_refcount(THIS_MODULE): .........
但是在 chardev.c 里面却在 device_open 里面用 try_module_get(THIS_MODULE) 去增
加 refcount ,在 device_release 里面用 module_put(THIS_MODULE)
说好的不推荐直接使用呢???
目前看过的 kernel module 的 code 好像也没有人呼叫过这些 function , kernel 应
该会帮忙 handle 这些 lkm 的 refcount ,不明白加这些的用意在干嘛....
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 36.229.149.207 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/LinuxDev/M.1655094115.A.C5B.html
※ 编辑: b0920075 (36.229.149.207 台湾), 06/13/2022 12:24:01
1F:→ admon: 黄字说不要用变数,要用函式。你英文不好。 06/13 12:40
他意思不是说不要去改 refcount 但真的手贱想改的话仍然有些 function 可以更改 re
fcoutn 的意思吗?
就算不要用变数好了,那他用这些函数意义在哪? kernel 不是应该要帮忙管理 refcount
吗
然後我有找到一篇 stackoverflow 也说不要用 try_module_get 这种 函数
https://stackoverflow.com/questions/1741415/linux-kernel-modules-when-to-use-try-module-get-module-put
看起来跟直接用变数还是函数控制没关系啊?
※ 编辑: b0920075 (36.229.149.207 台湾), 06/13/2022 16:37:59
我刚刚自己做了一下实验看移除 try_module_get 和 module_put 会怎样
移除後 lsmod 看到的 used by 都会是 0 ,看起来 kernel 没有因为我开启 /
dev/chardev 就帮我增加 refcount ,如果此时我直接 mmod 後关闭 /dev/chardev 会
发生 kernel panic unhandle page fault ,但是这跟我之前接触到的 kernel module
行为有些出入....
於是我又尝试加载另一份 lkm 取自
https://github.com/yuawn/Linux-Kernel-Exploitation
简单的在 msg_msg.c 开启 /dev/demo 後印出 lsmod 发现他的 Used 真的有加 1 但是
demo 里面却没看到 try_module_get 或是 module_put ,不确定是差在哪 QQ
※ 编辑: b0920075 (36.229.149.207 台湾), 06/13/2022 17:35:14
※ 编辑: b0920075 (36.229.149.207 台湾), 06/13/2022 17:36:03
刚刚尝试对 file_operations 的 owner 给 THIS_MODULE 後 Used 的数字就正常了,
应该是 .owner = THIS_MODULE 对 refcount 生效了!?
根据这篇 stackoverflow 也说如果有设定 .owner 的话在 device_open 前就会
try_module_get
https://stackoverflow.com/questions/48478978/regarding-owner-field-of-struct-file-operations
因为我的 device 是 chardev ,猜测应该是在 char_dev.c 中的 cdev_get 里面的:
static struct kobject *cdev_get(
struct cdev *p)
{
struct module *owner = p->owner;
struct kobject *kobj;
if (owner && !try_module_get(owner))
return NULL;
kobj = kobject_get(&p->kobj);
if (!kobj)
module_put(owner);
return kobj;
}
如果有 owner 就尝试去 try_module_get 帮忙 handle
※ 编辑: b0920075 (36.229.149.207 台湾), 06/13/2022 17:50:37
※ 编辑: b0920075 (36.229.149.207 台湾), 06/13/2022 17:51:01
2F:推 dragon121985: softdep可能是更好的选择? 06/16 20:58