Linux 6.13-rc4
[linux.git] / drivers / nvmem / rmem.c
blob7f907c5a445e7865c8626e00362df0040fe52241
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Copyright (C) 2020 Nicolas Saenz Julienne <nsaenzjulienne@suse.de>
4 */
6 #include <linux/io.h>
7 #include <linux/module.h>
8 #include <linux/nvmem-provider.h>
9 #include <linux/of_reserved_mem.h>
10 #include <linux/platform_device.h>
12 struct rmem {
13 struct device *dev;
14 struct nvmem_device *nvmem;
15 struct reserved_mem *mem;
17 phys_addr_t size;
20 static int rmem_read(void *context, unsigned int offset,
21 void *val, size_t bytes)
23 struct rmem *priv = context;
24 size_t available = priv->mem->size;
25 loff_t off = offset;
26 void *addr;
27 int count;
30 * Only map the reserved memory at this point to avoid potential rogue
31 * kernel threads inadvertently modifying it. Based on the current
32 * uses-cases for this driver, the performance hit isn't a concern.
33 * Nor is likely to be, given the nature of the subsystem. Most nvmem
34 * devices operate over slow buses to begin with.
36 * An alternative would be setting the memory as RO, set_memory_ro(),
37 * but as of Dec 2020 this isn't possible on arm64.
39 addr = memremap(priv->mem->base, available, MEMREMAP_WB);
40 if (!addr) {
41 dev_err(priv->dev, "Failed to remap memory region\n");
42 return -ENOMEM;
45 count = memory_read_from_buffer(val, bytes, &off, addr, available);
47 memunmap(addr);
49 if (count < 0)
50 return count;
52 return count == bytes ? 0 : -EIO;
55 static int rmem_probe(struct platform_device *pdev)
57 struct nvmem_config config = { };
58 struct device *dev = &pdev->dev;
59 struct reserved_mem *mem;
60 struct rmem *priv;
62 priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
63 if (!priv)
64 return -ENOMEM;
65 priv->dev = dev;
67 mem = of_reserved_mem_lookup(dev->of_node);
68 if (!mem) {
69 dev_err(dev, "Failed to lookup reserved memory\n");
70 return -EINVAL;
72 priv->mem = mem;
74 config.dev = dev;
75 config.priv = priv;
76 config.name = "rmem";
77 config.id = NVMEM_DEVID_AUTO;
78 config.size = mem->size;
79 config.reg_read = rmem_read;
81 return PTR_ERR_OR_ZERO(devm_nvmem_register(dev, &config));
84 static const struct of_device_id rmem_match[] = {
85 { .compatible = "nvmem-rmem", },
86 { /* sentinel */ },
88 MODULE_DEVICE_TABLE(of, rmem_match);
90 static struct platform_driver rmem_driver = {
91 .probe = rmem_probe,
92 .driver = {
93 .name = "rmem",
94 .of_match_table = rmem_match,
97 module_platform_driver(rmem_driver);
99 MODULE_AUTHOR("Nicolas Saenz Julienne <nsaenzjulienne@suse.de>");
100 MODULE_DESCRIPTION("Reserved Memory Based nvmem Driver");
101 MODULE_LICENSE("GPL");