码迷,mamicode.com
首页 > 其他好文 > 详细

通过/dev/mem操作物理内存

时间:2020-02-23 16:31:38      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:代码   syn   ddr   ==   err   led   share   style   空间   

  /dev/mem设备可以用来访问物理内存。下面一段应用程序的代码,实现了通过/dev/mem对物理内存空间中SRAM1的访问。

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

#define SRAM1_ADDR  0x10000000

struct test_data {
        int32_t val;
};

int main(void)
{
        struct test_data *data;
        int ret = 0;
        void *base;
        int fd;

        fd = open("/dev/mem", O_RDWR | O_SYNC);
        if (fd == -1) {
                printf("failed to open /dev/mem!");
                return -1;
        }

        base = mmap(NULL, sizeof(struct test_data), PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, SRAM1_ADDR);
        if (base == MAP_FAILED) {
                printf("failed to mmap /dev/mem!");
                ret = -1;
                goto err_mmap;
        }

        data = (struct test_data *)base;

        printf("data value: %x\n", data->val);
        data->val = 0x12345678;
        printf("write: %x\n", data->val);

        if (munmap(base, sizeof(struct test_data)) == -1) {
                printf("failed to munmap /dev/mem!");
                ret = -1;
        }

err_mmap:
        close(fd);
        return ret;
}

  可以通过devmem命令验证该程序。通过devmem预先把data设置成0xffffffff,然后用该程序把0x12345678写入data,最后用devmem再读取验证。

# devmem2 0x10000000 w 0xffffffff
/dev/mem opened.
Memory mapped at address 0xb6f36000.
Value at address 0x10000000 (0xb6f36000): 0x11111111
Written 0xFFFFFFFF; readback 0xFFFFFFFF

# ./a.out
data value: ffffffff
write: 12345678

# devmem2 0x10000000
/dev/mem opened.
Memory mapped at address 0xb6f15000.
Value at address 0x10000000 (0xb6f15000): 0x12345678

 

通过/dev/mem操作物理内存

标签:代码   syn   ddr   ==   err   led   share   style   空间   

原文地址:https://www.cnblogs.com/yanceylu/p/12350161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!