virt_to_phys.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Also try on QEMU monitor:
  3. xp 0x<vaddr>
  4. Only works for kmalloc.
  5. static inline phys_addr_t virt_to_phys(volatile void *address)
  6. - https://stackoverflow.com/questions/5748492/is-there-any-api-for-determining-the-physical-address-from-virtual-address-in-li
  7. - https://stackoverflow.com/questions/43325205/can-we-use-virt-to-phys-for-user-space-memory-in-kernel-module
  8. - https://stackoverflow.com/questions/39134990/mmap-of-dev-mem-fails-with-invalid-argument-but-address-is-page-aligned
  9. */
  10. #include <asm/io.h> /* virt_to_phys */
  11. #include <linux/debugfs.h>
  12. #include <linux/delay.h> /* usleep_range */
  13. #include <linux/kernel.h>
  14. #include <linux/kthread.h>
  15. #include <linux/module.h>
  16. #include <linux/seq_file.h> /* single_open, single_release */
  17. #include <linux/slab.h> /* kmalloc, kfree */
  18. static volatile u32 *k;
  19. static volatile u32 i;
  20. static struct dentry *debugfs_file;
  21. static int show(struct seq_file *m, void *v)
  22. {
  23. seq_printf(m,
  24. "k 0x%llx\n"
  25. "addr_k %p\n"
  26. "virt_to_phys_k 0x%llx\n"
  27. "i 0x%llx\n"
  28. "addr_i %p\n"
  29. "virt_to_phys_i 0x%llx\n",
  30. (unsigned long long)*k,
  31. k,
  32. (unsigned long long)virt_to_phys((void *)k),
  33. (unsigned long long)i,
  34. &i,
  35. (unsigned long long)virt_to_phys((void *)&i)
  36. );
  37. return 0;
  38. }
  39. static int open(struct inode *inode, struct file *file)
  40. {
  41. return single_open(file, show, NULL);
  42. }
  43. static const struct file_operations fops = {
  44. .llseek = seq_lseek,
  45. .open = open,
  46. .owner = THIS_MODULE,
  47. .read = seq_read,
  48. .release = single_release,
  49. };
  50. static int myinit(void)
  51. {
  52. k = kmalloc(sizeof(k), GFP_KERNEL);
  53. *k = 0x12345678;
  54. i = 0x12345678;
  55. debugfs_file = debugfs_create_file(
  56. "lkmc_virt_to_phys", S_IRUSR, NULL, NULL, &fops);
  57. return 0;
  58. }
  59. static void myexit(void)
  60. {
  61. debugfs_remove(debugfs_file);
  62. kfree((void *)k);
  63. }
  64. module_init(myinit)
  65. module_exit(myexit)
  66. MODULE_LICENSE("GPL");