contributed by < mesohandsome
>
編譯用命令
什麼是 Character / Block Device Driver?
A character device typically transfers data to and from a user application — they behave like pipes or serial ports, instantly reading or writing the byte data in a character-by-character stream. They provide the framework for many typical drivers, such as those that are required for interfacing to serial communications, video capture, and audio devices.
The main alternative to a character device is a block device. Block devices behave in a similar fashion to regular files, allowing a buffered array of cached data to be viewed or manipulated with operations such as reads, writes, and seeks. Both device types can be accessed through device files that are attached to the file system tree.
insmod
使用 man
在 Manual page 中可以看到關於 insmod
的簡述。
insmod - Simple program to insert a module into the Linux Kernel
在撰寫核心模組時,會使用巨集 module_init(init_function_name)
,讓核心找到寫好的 init 函式,以 int init_module(void) __attribute__((alias(#initfn)));
將init_module
取一個別名,也就是我們的 init 函式名稱,因此呼叫 init_module
等同於呼叫自己寫的函式。
而後透過 sudo strace insmod hello.ko
觀察發現,一開始 insmod
會開啟 fibdrv.ko
,並得到該檔案的 fd,最後會執行 finit_module(3, "", 0)
,當中會透過 load_module()
呼叫我們的 init 函式並初始化。
在 /kernel/module.c 中:
如果模組使用了 MODULE_LICENSE("GPL")
或類似的 GPL 授權,這樣的模組可以無限制的訪問核心中所有標記為 EXPORT_SYMBOL_GPL 的符號。
使用 Proprietary
的 non-GPL 的話,就不能用標記為 EXPORT_SYMBOL_GPL 的符號了。
open()
, read()
, write()
, mmap()
kernel 會自動分配 major number 給 device driver,那 device driver 要怎麼用 minor number 判斷目前的裝置為何?