Is kmalloc allocation not virtually contiguous?

拜拜、爱过 提交于 2021-02-04 06:08:26

问题


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 output:

Memory allocated successfully:0000000083318b28  000000001fba1614
Physical address:1d5d09c00   1d5d09c64

回答1:


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.

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


From Documentation/kprintf-formats.txt (web) or Documentation/core-api/printk-formats.rst (git):

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

Then, later below:

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.



来源:https://stackoverflow.com/questions/57757876/is-kmalloc-allocation-not-virtually-contiguous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!