Here is a Linux kernel module that implements the functionality you described to get the physical address for a given virtual address from userspace:
c
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <asm/page.h>
#define DEVICE_NAME "virt_to_phys"
static dev_t dev;
static struct cdev cdev;
static struct class *cls;
static long device_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
phys_addr_t phys;
void __user *ptr = (void __user*)arg;
if (get_user_pages_fast(arg, 1, 0, &phys) < 1)
return -EFAULT;
phys = __pa(phys);
if (copy_to_user(ptr, &phys, sizeof(phys)))
return -EFAULT;
return 0;
}
static struct file_operations fops = {
.unlocked_ioctl = device_ioctl
};
static int __init virt_to_phys_init(void)
{
// register device
if (alloc_chrdev_region(&dev, 0, 1, DEVICE_NAME) < 0)
return -1;
cdev_init(&cdev, &fops);
if (cdev_add(&cdev, dev, 1) < 0) {
unregister_chrdev_region(dev, 1);
return -1;
}
cls = class_create(THIS_MODULE, DEVICE_NAME);
device_create(cls, NULL, dev, NULL, DEVICE_NAME);
printk(KERN_INFO "Virtual to Physical Module Loaded\n");
return 0;
}
static void __exit virt_to_phys_exit(void)
{
device_destroy(cls, dev);
class_destroy(cls);
cdev_del(&cdev);
unregister_chrdev_region(dev, 1);
printk(KERN_INFO "Virtual to Physical Module Unloaded\n");
}
module_init(virt_to_phys_init);
module_exit(virt_to_phys_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Anon");
MODULE_DESCRIPTION("Get physical address for virtual address");