kmalloc分配实际上不是连续的吗

kmalloc分配实际上不是连续的吗

本文介绍了kmalloc分配实际上不是连续的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 kmalloc 返回物理上和虚拟上连续的内存.

I found that kmalloc returns physically and virtually contiguous memory.

我写了一些代码来观察这种行为,但是似乎只有物理内存是连续的,而不是虚拟内存.我有什么错误吗?

I wrote some code to observe the behavior, but only the physical memory seems to be contiguous and not the virtual. Am I making any mistake?

#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

推荐答案

打印内核指针通常不是一个好主意,因为它基本上意味着将内核地址泄漏到用户空间,因此在使用%p 时在 printk()(或类似的宏,例如 pr_info()等)中,内核会尝试保护自己而不打印实际地址.而是为该地址打印一个不同的哈希唯一标识符.

Printing kernel pointers is in general a bad idea, because it basically means leaking kernel addresses to user space, so when using %p in printk() (or similar macros like pr_info() etc.), the kernel tries to protect itself and does not print the real address. Instead, it prints a different hashed unique identifier for that address.

如果您真的要打印该地址,则可以使用%px .

If you really want to print that address, you can use %px.

如何获取printk格式正确的说明符(网络) 文档/core-api/printk-formats.rst (git):

From How to get printk format specifiers right (web) or Documentation/core-api/printk-formats.rst (git):

%p    abcdef12 or 00000000abcdef12

然后,在下面的内容中

%px   01234567 or 0123456789abcdef

用于当您确实要打印地址时打印指针.请考虑您是否泄漏了有关在使用%px 打印指针之前,先在内存中进行内核布局.%px 是在功能上等同于%lx .与%lx 相比,%px 更受青睐独一无二.如果将来我们需要修改 Kernel 的方式处理打印指针,很高兴能够找到呼叫网站.

For printing pointers when you really want to print the address. Pleaseconsider whether or not you are leaking sensitive information about theKernel layout in memory before printing pointers with %px. %px isfunctionally equivalent to %lx. %px is preferred to %lx because it is moreuniquely grep'able. If, in the future, we need to modify the way the Kernelhandles printing pointers it will be nice to be able to find the callsites.

这篇关于kmalloc分配实际上不是连续的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:01