用户空间获取物理地址的方法

2900阅读 0评论2018-01-16 wibnmo
分类:Android平台

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <inttypes.h>
  4. #include <stdint.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>

  8. #define page_map_file "/proc/self/pagemap"

  9. #define PFN_MASK ((((uint64_t)1)<<55)-1)

  10. #define PFN_PRESENT_FLAG (((uint64_t)1)<<63)

  11. int mem_addr_vir2phy(unsigned long vir, unsigned long *phy)
  12. {
  13.     int fd;
  14.     int page_size=getpagesize();
  15.     unsigned long vir_page_idx = vir/page_size;
  16.     unsigned long pfn_item_offset = vir_page_idx*sizeof(uint64_t);
  17.     uint64_t pfn_item;

  18.     fd = open(page_map_file, O_RDONLY);
  19.     if (fd<0)
  20.     {
  21.         printf("open %s failed", page_map_file);
  22.         return -1;
  23.     }
  24.     if ((off_t)-== lseek(fd, pfn_item_offset, SEEK_SET))
  25.     {
  26.         printf("lseek %s failed", page_map_file);
  27.         return -1;
  28.     }
  29.     if (sizeof(uint64_t) != read(fd, &pfn_item, sizeof(uint64_t)))
  30.     {
  31.         printf("read %s failed", page_map_file);
  32.         return -1;
  33.     }
  34.     if (0==(pfn_item & PFN_PRESENT_FLAG))
  35.     {
  36.         printf("page is not present");
  37.         return -1;
  38.     }
  39.     *phy = (pfn_item & PFN_MASK)*page_size + vir % page_size;
  40.     return 0;
  41. }

  42. void main()
  43. {
  44.     int a=0x12345678;
  45.     unsigned long phy;
  46.     mem_addr_vir2phy((unsigned long)&a, &phy);
  47.     printf("vaddr=%p,phy=0x%lx\n", &a, phy);
  48.     while(1)
  49.     {
  50.         sleep(100);
  51.     }
  52. }

http://blog.csdn.net/wangcong02345/article/details/52326083
上一篇:tmux配置
下一篇:没有了