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

标签 c linux memory-management linux-kernel linux-device-driver

我发现 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

最佳答案

打印内核指针通常是一个坏主意,因为它基本上意味着将内核地址泄漏到用户空间,所以当在 printk() (或类似的)中使用 %p pr_info() 等宏),内核试图保护自己并且不打印真实地址。相反,它会为该地址打印一个不同的散列唯一标识符。

如果您真的想要打印那个地址,您可以使用%px


来自Documentation/core-api/printk-formats.rst(web versiongit):

Pointer Types

Pointers printed without a specifier extension (i.e unadorned %p) are hashed to give a unique identifier without leaking kernel addresses to user space. On 64 bit machines the first 32 bits are zeroed. If you really want the address see %px below.

%p    abcdef12 or 00000000abcdef12

然后,下面是:

Unmodified Addresses

%px   01234567 or 0123456789abcdef

For printing pointers when you really want to print the address. Please consider whether or not you are leaking sensitive information about the Kernel layout in memory before printing pointers with %px. %px is functionally equivalent to %lx. %px is preferred to %lx because it is more uniquely grep'able. If, in the future, we need to modify the way the Kernel handles printing pointers it will be nice to be able to find the call sites.

关于c - kmalloc 分配实际上不是连续的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57757876/

相关文章:

vue.js - Vuex 分析 : How to know a vuex state or a component size in memory

objective-c - 从 Objective-C 中的方法返回对象

c - 模拟 getchar() 的 UART 驱动程序

c++ - 用于动态重新加载/usr/share/zoneinfo 数据库的库/代码?

c - 使用指针数组时出现段错误

linux - bash 中的特殊管道/重定向

c - 两个 printfs 以不同的方式打印相同的字符串

c - 段错误错误: While reversing a string

linux - linux同步串口读取功能

c++ - 套接字内存泄漏