1/* SPDX-License-Identifier: GPL-2.0 OR MIT */
2/* Copyright 2022 Innovative Advantage Inc. */
3
4#ifndef _LINUX_MFD_OCELOT_H
5#define _LINUX_MFD_OCELOT_H
6
7#include <linux/err.h>
8#include <linux/errno.h>
9#include <linux/ioport.h>
10#include <linux/platform_device.h>
11#include <linux/regmap.h>
12#include <linux/types.h>
13
14struct resource;
15
16static inline struct regmap *
17ocelot_regmap_from_resource_optional(struct platform_device *pdev,
18				     unsigned int index,
19				     const struct regmap_config *config)
20{
21	struct device *dev = &pdev->dev;
22	struct resource *res;
23	void __iomem *regs;
24
25	/*
26	 * Don't use _get_and_ioremap_resource() here, since that will invoke
27	 * prints of "invalid resource" which will simply add confusion.
28	 */
29	res = platform_get_resource(pdev, IORESOURCE_MEM, index);
30	if (res) {
31		regs = devm_ioremap_resource(dev, res);
32		if (IS_ERR(regs))
33			return ERR_CAST(regs);
34		return devm_regmap_init_mmio(dev, regs, config);
35	}
36
37	/*
38	 * Fall back to using REG and getting the resource from the parent
39	 * device, which is possible in an MFD configuration
40	 */
41	if (dev->parent) {
42		res = platform_get_resource(pdev, IORESOURCE_REG, index);
43		if (!res)
44			return NULL;
45
46		return dev_get_regmap(dev->parent, res->name);
47	}
48
49	return NULL;
50}
51
52static inline struct regmap *
53ocelot_regmap_from_resource(struct platform_device *pdev, unsigned int index,
54			    const struct regmap_config *config)
55{
56	struct regmap *map;
57
58	map = ocelot_regmap_from_resource_optional(pdev, index, config);
59	return map ?: ERR_PTR(-ENOENT);
60}
61
62#endif
63