Search code examples
clinuxmemory-managementlinux-kernelkernel-module

Use of alloc_page return value


I want to know the use of the return value of alloc_page, it allocates page and returns an instance of struct page to represent the start of the reserved block. However, I have no clue how to use that reserved page after allocation. I have trouble understanding that stuff, kmalloc is very simple, we just can allocate memory into a char *buf for example, but this kernel functions return a structure and I have no clue how to use it for my needs.

#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>

struct page *p;

static int __init sys_module_init(void)
{
    p = alloc_page(GFP_KERNEL);

    pr_info(KBUILD_MODNAME ": Hello, World!\n");
    return 0;
}

static void __exit sys_module_exit(void)
{
    __free_page(p);
    
    pr_info(KBUILD_MODNAME ": Bye, World!\n");
}

module_init(sys_module_init);
module_exit(sys_module_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("StackOverflow");

Solution

  • alloc_page() is lower level than kmalloc(). If the struct page were coming from a user space program, you'd need to first map it to kernel address space using kmap(). But since you're allocating kernel memory with GFP_KERNEL, then you can just take the page struct and then convert it to its virtual address using page_address(). Then you can use the address in a function like memcpy() to write data to it. I'm sure there are other ways to write/read from the page including things like casting the memory to different types, but then you probably need to do the memory management yourself. All depends what specifically you want to do with the page.