在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 @ 2022-04-12 15:32  HankFu  阅读(211)  评论(0编辑  收藏  举报