gpt4 book ai didi

c - 我应该在平台设备上的什么地方存储动态分配的内存(不使用全局变量)?

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:47 26 4
gpt4 key购买 nike

我想让我正在编写的平台驱动程序可重入:我在哪里存储在探测和/或打开调用期间动态分配的内存 (int probe(struct platform_device*)/ int open(struct inode *inode, struct file *))

驱动程序可以在多个系统内硬件上实例化,每个硬件都可以从用户空间同时访问。

我可以使用 struct file 中的 private_data 字段吗?和来自 struct deviceplatform_data作为指向已分配内存的任意指针?

最佳答案

如果您正在编写平台驱动程序,则应使用dev_set_drvdata() 函数,which sets the driver_data field in struct device , .

有一个例子。

struct blink_local {
int irq;
unsigned long mem_start;
unsigned long mem_end;
void __iomem *base_addr;
};

static int blink_probe(struct platform_device *pdev)
{
struct resource *r_irq; /* Interrupt resources */
struct resource *r_mem; /* IO mem resources */
struct device *dev = &pdev->dev;
struct blink_local *lp = NULL;

int rc = 0;
dev_info(dev, "Device Tree Probing\n");
/* Get iospace for the device */
r_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r_mem) {
dev_err(dev, "invalid address\n");
return -ENODEV;
}

lp = (struct blink_local *) kmalloc(sizeof(struct blink_local), GFP_KERNEL);
if (!lp) {
dev_err(dev, "Cound not allocate blink device\n");
return -ENOMEM;
}

dev_set_drvdata(dev, lp);
lp->mem_start = r_mem->start;
lp->mem_end = r_mem->end;

if (!request_mem_region(lp->mem_start,
lp->mem_end - lp->mem_start + 1,
DRIVER_NAME)) {
dev_err(dev, "Couldn't lock memory region at %p\n",
(void *)lp->mem_start);
rc = -EBUSY;
goto error1;
}

lp->base_addr = ioremap(lp->mem_start, lp->mem_end - lp->mem_start + 1);
if (!lp->base_addr) {
dev_err(dev, "blink: Could not allocate iomem\n");
rc = -EIO;
goto error2;
}

/* Get IRQ for the device */
r_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!r_irq) {
dev_info(dev, "no IRQ found\n");
dev_info(dev, "blink at 0x%08x mapped to 0x%08x\n",
(unsigned int __force)lp->mem_start,
(unsigned int __force)lp->base_addr);
return 0;
}
lp->irq = r_irq->start;
rc = request_irq(lp->irq, &blink_irq, 0, DRIVER_NAME, lp);
if (rc) {
dev_err(dev, "testmodule: Could not allocate interrupt %d.\n",
lp->irq);
goto error3;
}

return 0;
error3:
free_irq(lp->irq, lp);
error2:
release_mem_region(lp->mem_start, lp->mem_end - lp->mem_start + 1);
error1:
kfree(lp);
dev_set_drvdata(dev, NULL);
return rc;
}

关于c - 我应该在平台设备上的什么地方存储动态分配的内存(不使用全局变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com