【发布时间】:2020-01-05 13:06:15
【问题描述】:
我发现kmalloc 返回物理上和虚拟上连续的内存。
我写了一些代码来观察行为,但似乎只有物理内存是连续的,而不是虚拟的。我有什么错误吗?
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/moduleparam.h>
MODULE_LICENSE("GPL");
static char *ptr;
int alloc_size = 1024;
module_param(alloc_size, int, 0);
static int test_hello_init(void)
{
ptr = kmalloc(alloc_size,GFP_ATOMIC);
if(!ptr) {
/* handle error */
pr_err("memory allocation failed\n");
return -ENOMEM;
} else {
pr_info("Memory allocated successfully:%p\t%p\n", ptr, ptr+100);
pr_info("Physical address:%llx\t %llx\n", virt_to_phys(ptr), virt_to_phys(ptr+100));
}
return 0;
}
static void test_hello_exit(void)
{
kfree(ptr);
pr_info("Memory freed\n");
}
module_init(test_hello_init);
module_exit(test_hello_exit);
dmesg 输出:
Memory allocated successfully:0000000083318b28 000000001fba1614
Physical address:1d5d09c00 1d5d09c64
【问题讨论】:
-
我不完全确定这是否是你的问题,但在我探索 linux 内核的过程中,我发现使用 printk 方法的格式说明符 %p 返回了错误的地址。您确定带有 %p 说明符的 pr_info 返回有效的指针地址吗?我的解决方法是将地址转换为 unsigned long long 并使用 %llx。也许试试看?
标签: c linux memory-management linux-kernel linux-device-driver