25

我有 Linux,我有一个物理地址:(即 0x60000000)。
我想从用户空间 Linux 程序中读取这个地址。

该地址可能在内核空间中。

4

4 回答 4

6

您需要一个内核驱动程序来将物理地址导出到用户级。

看看这个驱动程序:https ://github.com/claudioscordino/mmap_alloc/blob/master/mmap_alloc.c

于 2013-10-21T12:46:35.617 回答
5

请注意,现在可以通过 /proc/[pid]/pagemap

于 2014-03-07T16:25:47.743 回答
3
Is there an easy way I can do that?

对于从用户空间访问,mmap()是一个不错的解决方案。

Is it possible to convert it by using some function like "phys_to_virt()"?

物理地址可以使用ioremap_nocache()映射到虚拟地址。但是从用户空间,你不能直接访问它。假设您的驱动程序或内核模块想要访问该物理地址,这是最好的方法。通常内存映射设备驱动程序使用此函数将寄存器映射到虚拟内存。

于 2013-10-22T06:58:51.397 回答
0

在 C 中类似这样的东西。如果您轮询硬件寄存器,请确保添加 volatile 声明,以便编译器不会优化您的变量。

#include <stdlib.h>

#include <stdio.h>
#include <errno.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <memory.h>

volatile int *hw_mmap = NULL; /*evil global variable method*/

int map_it() {
/* open /dev/mem and error checking */
int i;
int file_handle = open(memDevice, O_RDWR | O_SYNC);

if (file_handle < 0) {
    DBG_PRINT("Failed to open /dev/mem: %s !\n",strerror(errno));
    return errno;
}

/* mmap() the opened /dev/mem */
hw_mmap = (int *) (mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, file_handle, 0x60000000));
if(hw_mmap ==(void*) -1) {

    fprintf(stderr,"map_it: Cannot map memory into user space.\n");
    return errno;
}
return 0;
}

现在您可以读取写入到 hw_mmap 中。

于 2017-08-17T13:38:18.770 回答