在linux内核映射物理地址的简单代码。

在linux内核映射物理地址的简单代码。
使用request_mem_region和ioremap映射物理地址。
映射之后,可通过虚拟地址读写对应的寄存器。

/** Claim the memory region
 * @p_device_info: Handle to the device structure
 *
 * Return: 0 on success, negative errno otherwise.
 */
static int xxx_map_mem(struct xxx_device *p_device_info)
{
	if (!request_mem_region(p_device_info->phy_base, XXX_REG_SPACE, XXX_NAME)) {
        dev_err(p_device_info->dev, "xxx_map_mem request_mem_region failed\n");
		return -ENOMEM;
	}
    dev_err(p_device_info->dev, "xxx_map_mem request_mem_region successed\n");

	p_device_info->map_virt_base = ioremap(p_device_info->phy_base, XXX_REG_SPACE);
	if (!p_device_info->map_virt_base) {
		dev_err(p_device_info->dev, "Unable to map registers\n");
		release_mem_region(p_device_info->phy_base, XXX_REG_SPACE);
		return -ENOMEM;
	}
    dev_err(p_device_info->dev, "xxx_map_mem ioremap successed, virt address: %px\n", p_device_info->map_virt_base);
    
	dev_err(p_device_info->dev, "Set trigger registers to 0x4 during initialization.\n");
    msleep(1);
    p_device_info->map_virt_base[0]=0x4;

	return 0;
}

/**
 * @p_device_info: Handle to the device structure
 *
 * Release the memory region. 
 */
static void xxx_unmap_mem(struct xxx_device *p_device_info)
{
	if (p_device_info->map_virt_base) {
        iounmap(p_device_info->map_virt_base);
        p_device_info->map_virt_base = NULL;
        dev_err(p_device_info->dev, "xxx_unmap_mem iounmap successed\n");
	}

	release_mem_region(p_device_info->phy_base, XXX_REG_SPACE);
    dev_err(p_device_info->dev, "xxx_unmap_mem release_mem_region successed\n");
}
posted @   HankFu  阅读(218)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示