Linux如何从用户空间访问物理地址? [英] How to access physical addresses from user space in Linux?

查看:35
本文介绍了Linux如何从用户空间访问物理地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行 Linux 的基于 ARM 的系统上,我有一个将内存映射到物理地址的设备.从所有地址都是虚拟的用户空间程序中,如何从该地址读取内容?

On a ARM based system running Linux, I have a device that's memory mapped to a physical address. From a user space program where all addresses are virtual, how can I read content from this address?

推荐答案

您可以使用 mmap(2) 系统调用将设备文件映射到用户进程内存.通常,设备文件是物理内存到文件系统的映射.否则,您必须编写一个内核模块来创建这样的文件或提供一种将所需内存映射到用户进程的方法.

You can map a device file to a user process memory using mmap(2) system call. Usually, device files are mappings of physical memory to the file system. Otherwise, you have to write a kernel module which creates such a file or provides a way to map the needed memory to a user process.

另一种方法是将/dev/mem 的部分重新映射到用户内存.

Another way is remapping parts of /dev/mem to a user memory.

mmaping/dev/mem 的示例(此程序必须有权访问/dev/mem,例如具有 root 权限):

Example of mmaping /dev/mem (this program must have access to /dev/mem, e.g. have root rights):

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("Usage: %s <phys_addr> <offset>\n", argv[0]);
        return 0;
    }

    off_t offset = strtoul(argv[1], NULL, 0);
    size_t len = strtoul(argv[2], NULL, 0);

    // Truncate offset to a multiple of the page size, or mmap will fail.
    size_t pagesize = sysconf(_SC_PAGE_SIZE);
    off_t page_base = (offset / pagesize) * pagesize;
    off_t page_offset = offset - page_base;

    int fd = open("/dev/mem", O_SYNC);
    unsigned char *mem = mmap(NULL, page_offset + len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, page_base);
    if (mem == MAP_FAILED) {
        perror("Can't map memory");
        return -1;
    }

    size_t i;
    for (i = 0; i < len; ++i)
        printf("%02x ", (int)mem[page_offset + i]);

    return 0;
}

这篇关于Linux如何从用户空间访问物理地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆