virt_to_phys.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#virt-to-phys */
  2. #include <asm/io.h> /* virt_to_phys */
  3. #include <linux/debugfs.h>
  4. #include <linux/delay.h> /* usleep_range */
  5. #include <linux/kernel.h>
  6. #include <linux/kthread.h>
  7. #include <linux/module.h>
  8. #include <linux/seq_file.h> /* single_open, single_release */
  9. #include <linux/slab.h> /* kmalloc, kfree */
  10. static volatile u32 *kmalloc_ptr;
  11. static volatile u32 static_var;
  12. static struct dentry *debugfs_file;
  13. static int show(struct seq_file *m, void *v)
  14. {
  15. seq_printf(m,
  16. "*kmalloc_ptr = 0x%llx\n"
  17. "kmalloc_ptr = %px\n"
  18. "virt_to_phys(kmalloc_ptr) = 0x%llx\n"
  19. "static_var = 0x%llx\n"
  20. "&static_var = %px\n"
  21. "virt_to_phys(&static_var) = 0x%llx\n",
  22. (unsigned long long)*kmalloc_ptr,
  23. kmalloc_ptr,
  24. (unsigned long long)virt_to_phys((void *)kmalloc_ptr),
  25. (unsigned long long)static_var,
  26. &static_var,
  27. (unsigned long long)virt_to_phys((void *)&static_var)
  28. );
  29. return 0;
  30. }
  31. static int open(struct inode *inode, struct file *file)
  32. {
  33. return single_open(file, show, NULL);
  34. }
  35. static const struct file_operations fops = {
  36. .llseek = seq_lseek,
  37. .open = open,
  38. .owner = THIS_MODULE,
  39. .read = seq_read,
  40. .release = single_release,
  41. };
  42. static int myinit(void)
  43. {
  44. kmalloc_ptr = kmalloc(sizeof(kmalloc_ptr), GFP_KERNEL);
  45. *kmalloc_ptr = 0x12345678;
  46. static_var = 0x12345678;
  47. debugfs_file = debugfs_create_file("lkmc_virt_to_phys", S_IRUSR, NULL, NULL, &fops);
  48. return 0;
  49. }
  50. static void myexit(void)
  51. {
  52. debugfs_remove(debugfs_file);
  53. kfree((void *)kmalloc_ptr);
  54. }
  55. module_init(myinit)
  56. module_exit(myexit)
  57. MODULE_LICENSE("GPL");