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:
Output:
phys_to_virt: Function converts physical address to kernel virtual address.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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"); |
Output:
Is there any function which gives direct physical address ?
ReplyDeleteAs per my knowledge, i don't think there is such function
Delete