Linux module to convert virtual to physical and vice versa

virt_to_phys: Function converts kernel virtual address to physical address.
phys_to_virt: Function converts physical address to kernel virtual address.

Code:


#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/moduleparam.h>
#include <asm/io.h>
static void *virtual_addr;
static phys_addr_t physical_addr;
int size = 1024; /* allocate 1024 bytes */
static int alloc_init(void)
{
virtual_addr = kmalloc(size,GFP_ATOMIC);
if(!virtual_addr) {
/* handle error */
pr_err("memory allocation failed\n");
return -ENOMEM;
} else {
pr_info("Memory allocated successfully Virtual address:%p\n", virtual_addr);
physical_addr = virt_to_phys(virtual_addr);
pr_info("Physical address:%llx\n", physical_addr);
pr_info("Virtual address:%p\n", phys_to_virt(physical_addr));
}
return 0;
}
static void alloc_exit(void)
{
kfree(virtual_addr);
pr_info("Memory freed\n");
}
module_init(alloc_init);
module_exit(alloc_exit);
MODULE_LICENSE("GPL");
view raw kmalloc_test.c hosted with ❤ by GitHub

Output:






Comments

  1. Is there any function which gives direct physical address ?

    ReplyDelete
    Replies
    1. As per my knowledge, i don't think there is such function

      Delete

Post a Comment

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto