差異處
這裏顯示兩個版本的差異處。
Both sides previous revision 前次修改 下次修改 | 前次修改 | ||
cpp:linux_kernel:show_physical_address [2017/10/14 16:27] tony [Reference] |
cpp:linux_kernel:show_physical_address [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | {{tag>Linux Linux-kernel}} | ||
====== Show Physical Memory Address of the kernel module ====== | ====== Show Physical Memory Address of the kernel module ====== | ||
===== Introduction ===== | ===== Introduction ===== | ||
- | 我希望透過寫一個kernel module,做以下事情: | + | 我希望透過寫一個kernel module,讓user在user space去顯示kernel space某個變數值的實體記憶體位置與數值。 |
- | - 宣告一個global variable。 | + | \\ |
- | - init時,初始此variable。 | + | \\ |
- | - 執行file_operations: open時,會打印出此變數的實體記憶體位置。 | + | Note: 由於這程式僅用於測試,因此不會特別去考慮更好的寫法;會補充這點是由於看書有看到更好的寫法。 |
- | - exit時,釋放此variable。 | + | |
===== How to? ===== | ===== How to? ===== | ||
- | <code> | + | ==== Source Code ==== |
- | # | + | 包含以下內容: |
- | ## Makefile for kernel test | + | - 在init時,我建立一個字元裝置用以接受user space的操作,並初始hello_buf。 |
- | # | + | - 當使用者執行cat /dev/hello時,會觸發file_operations的open與release,這裡我只實做open的對應行為: dump_physical_address。 |
- | #PWD := $(shell pwd) | + | - dump_physical_address則是取得hello_buf的實體記憶體位置並dump出來。 |
- | KVERSION := $(shell uname -r) | + | - exit就是釋放所有用到的資源。 |
- | KERNEL_DIR = /usr/src/kernels/$(KVERSION)/ | + | |
- | MODULE_NAME = hello | + | |
- | obj-m := $(MODULE_NAME).o | + | |
- | all: | + | |
- | make -C $(KERNEL_DIR) M=$(PWD) modules | + | |
- | clean: | + | |
- | make -C $(KERNEL_DIR) M=$(PWD) clean | + | |
- | </code> | + | |
<code cpp> | <code cpp> | ||
#include <linux/init.h> | #include <linux/init.h> | ||
行 78: | 行 69: | ||
module_exit(hello_exit); | module_exit(hello_exit); | ||
</code> | </code> | ||
+ | ==== Makefile ==== | ||
+ | <code> | ||
+ | # | ||
+ | ## Makefile for kernel test | ||
+ | # | ||
+ | #PWD := $(shell pwd) | ||
+ | KVERSION := $(shell uname -r) | ||
+ | KERNEL_DIR = /usr/src/kernels/$(KVERSION)/ | ||
+ | MODULE_NAME = hello | ||
+ | obj-m := $(MODULE_NAME).o | ||
+ | all: | ||
+ | make -C $(KERNEL_DIR) M=$(PWD) modules | ||
+ | clean: | ||
+ | make -C $(KERNEL_DIR) M=$(PWD) clean | ||
+ | </code> | ||
+ | 起初我是在centos 7.3上寫,安裝了7.4的kernel header;編譯正常,但載入模組時,會出現Unkown symbol page offset base。最後裝7.3的kernel header就可以正常載入。 | ||
+ | ==== Test Script ==== | ||
+ | 請記得先執行mknod /dev/hello c 187 0去建立裝置檔案,接著就可以透過cat去操作,然後使用demsg看到結果: | ||
<code bash> | <code bash> | ||
#!/bin/bash | #!/bin/bash | ||
行 94: | 行 102: | ||
* [[http://blog.csdn.net/freenaut/article/details/4298174|字符设备 register_chrdev_region()、alloc_chrdev_region() 和 register_chrdev()]] | * [[http://blog.csdn.net/freenaut/article/details/4298174|字符设备 register_chrdev_region()、alloc_chrdev_region() 和 register_chrdev()]] | ||
+ | ===== ===== | ||
+ | ---- | ||
+ | \\ | ||
+ | ~~DISQUS~~ |