xref: /kernel/linux/linux-6.6/drivers/of/address.c (revision 62306a36)
1// SPDX-License-Identifier: GPL-2.0
2#define pr_fmt(fmt)	"OF: " fmt
3
4#include <linux/device.h>
5#include <linux/fwnode.h>
6#include <linux/io.h>
7#include <linux/ioport.h>
8#include <linux/logic_pio.h>
9#include <linux/module.h>
10#include <linux/of_address.h>
11#include <linux/pci.h>
12#include <linux/pci_regs.h>
13#include <linux/sizes.h>
14#include <linux/slab.h>
15#include <linux/string.h>
16#include <linux/dma-direct.h> /* for bus_dma_region */
17
18#include "of_private.h"
19
20/* Max address size we deal with */
21#define OF_MAX_ADDR_CELLS	4
22#define OF_CHECK_ADDR_COUNT(na)	((na) > 0 && (na) <= OF_MAX_ADDR_CELLS)
23#define OF_CHECK_COUNTS(na, ns)	(OF_CHECK_ADDR_COUNT(na) && (ns) > 0)
24
25/* Debug utility */
26#ifdef DEBUG
27static void of_dump_addr(const char *s, const __be32 *addr, int na)
28{
29	pr_debug("%s", s);
30	while (na--)
31		pr_cont(" %08x", be32_to_cpu(*(addr++)));
32	pr_cont("\n");
33}
34#else
35static void of_dump_addr(const char *s, const __be32 *addr, int na) { }
36#endif
37
38/* Callbacks for bus specific translators */
39struct of_bus {
40	const char	*name;
41	const char	*addresses;
42	int		(*match)(struct device_node *parent);
43	void		(*count_cells)(struct device_node *child,
44				       int *addrc, int *sizec);
45	u64		(*map)(__be32 *addr, const __be32 *range,
46				int na, int ns, int pna);
47	int		(*translate)(__be32 *addr, u64 offset, int na);
48	bool	has_flags;
49	unsigned int	(*get_flags)(const __be32 *addr);
50};
51
52/*
53 * Default translator (generic bus)
54 */
55
56static void of_bus_default_count_cells(struct device_node *dev,
57				       int *addrc, int *sizec)
58{
59	if (addrc)
60		*addrc = of_n_addr_cells(dev);
61	if (sizec)
62		*sizec = of_n_size_cells(dev);
63}
64
65static u64 of_bus_default_map(__be32 *addr, const __be32 *range,
66		int na, int ns, int pna)
67{
68	u64 cp, s, da;
69
70	cp = of_read_number(range, na);
71	s  = of_read_number(range + na + pna, ns);
72	da = of_read_number(addr, na);
73
74	pr_debug("default map, cp=%llx, s=%llx, da=%llx\n", cp, s, da);
75
76	if (da < cp || da >= (cp + s))
77		return OF_BAD_ADDR;
78	return da - cp;
79}
80
81static int of_bus_default_translate(__be32 *addr, u64 offset, int na)
82{
83	u64 a = of_read_number(addr, na);
84	memset(addr, 0, na * 4);
85	a += offset;
86	if (na > 1)
87		addr[na - 2] = cpu_to_be32(a >> 32);
88	addr[na - 1] = cpu_to_be32(a & 0xffffffffu);
89
90	return 0;
91}
92
93static unsigned int of_bus_default_flags_get_flags(const __be32 *addr)
94{
95	return of_read_number(addr, 1);
96}
97
98static unsigned int of_bus_default_get_flags(const __be32 *addr)
99{
100	return IORESOURCE_MEM;
101}
102
103static u64 of_bus_default_flags_map(__be32 *addr, const __be32 *range, int na,
104				    int ns, int pna)
105{
106	u64 cp, s, da;
107
108	/* Check that flags match */
109	if (*addr != *range)
110		return OF_BAD_ADDR;
111
112	/* Read address values, skipping high cell */
113	cp = of_read_number(range + 1, na - 1);
114	s  = of_read_number(range + na + pna, ns);
115	da = of_read_number(addr + 1, na - 1);
116
117	pr_debug("default flags map, cp=%llx, s=%llx, da=%llx\n", cp, s, da);
118
119	if (da < cp || da >= (cp + s))
120		return OF_BAD_ADDR;
121	return da - cp;
122}
123
124static int of_bus_default_flags_translate(__be32 *addr, u64 offset, int na)
125{
126	/* Keep "flags" part (high cell) in translated address */
127	return of_bus_default_translate(addr + 1, offset, na - 1);
128}
129
130#ifdef CONFIG_PCI
131static unsigned int of_bus_pci_get_flags(const __be32 *addr)
132{
133	unsigned int flags = 0;
134	u32 w = be32_to_cpup(addr);
135
136	if (!IS_ENABLED(CONFIG_PCI))
137		return 0;
138
139	switch((w >> 24) & 0x03) {
140	case 0x01:
141		flags |= IORESOURCE_IO;
142		break;
143	case 0x02: /* 32 bits */
144		flags |= IORESOURCE_MEM;
145		break;
146
147	case 0x03: /* 64 bits */
148		flags |= IORESOURCE_MEM | IORESOURCE_MEM_64;
149		break;
150	}
151	if (w & 0x40000000)
152		flags |= IORESOURCE_PREFETCH;
153	return flags;
154}
155
156/*
157 * PCI bus specific translator
158 */
159
160static bool of_node_is_pcie(struct device_node *np)
161{
162	bool is_pcie = of_node_name_eq(np, "pcie");
163
164	if (is_pcie)
165		pr_warn_once("%pOF: Missing device_type\n", np);
166
167	return is_pcie;
168}
169
170static int of_bus_pci_match(struct device_node *np)
171{
172	/*
173 	 * "pciex" is PCI Express
174	 * "vci" is for the /chaos bridge on 1st-gen PCI powermacs
175	 * "ht" is hypertransport
176	 *
177	 * If none of the device_type match, and that the node name is
178	 * "pcie", accept the device as PCI (with a warning).
179	 */
180	return of_node_is_type(np, "pci") || of_node_is_type(np, "pciex") ||
181		of_node_is_type(np, "vci") || of_node_is_type(np, "ht") ||
182		of_node_is_pcie(np);
183}
184
185static void of_bus_pci_count_cells(struct device_node *np,
186				   int *addrc, int *sizec)
187{
188	if (addrc)
189		*addrc = 3;
190	if (sizec)
191		*sizec = 2;
192}
193
194static u64 of_bus_pci_map(__be32 *addr, const __be32 *range, int na, int ns,
195		int pna)
196{
197	u64 cp, s, da;
198	unsigned int af, rf;
199
200	af = of_bus_pci_get_flags(addr);
201	rf = of_bus_pci_get_flags(range);
202
203	/* Check address type match */
204	if ((af ^ rf) & (IORESOURCE_MEM | IORESOURCE_IO))
205		return OF_BAD_ADDR;
206
207	/* Read address values, skipping high cell */
208	cp = of_read_number(range + 1, na - 1);
209	s  = of_read_number(range + na + pna, ns);
210	da = of_read_number(addr + 1, na - 1);
211
212	pr_debug("PCI map, cp=%llx, s=%llx, da=%llx\n", cp, s, da);
213
214	if (da < cp || da >= (cp + s))
215		return OF_BAD_ADDR;
216	return da - cp;
217}
218
219static int of_bus_pci_translate(__be32 *addr, u64 offset, int na)
220{
221	return of_bus_default_translate(addr + 1, offset, na - 1);
222}
223#endif /* CONFIG_PCI */
224
225/*
226 * of_pci_range_to_resource - Create a resource from an of_pci_range
227 * @range:	the PCI range that describes the resource
228 * @np:		device node where the range belongs to
229 * @res:	pointer to a valid resource that will be updated to
230 *              reflect the values contained in the range.
231 *
232 * Returns -EINVAL if the range cannot be converted to resource.
233 *
234 * Note that if the range is an IO range, the resource will be converted
235 * using pci_address_to_pio() which can fail if it is called too early or
236 * if the range cannot be matched to any host bridge IO space (our case here).
237 * To guard against that we try to register the IO range first.
238 * If that fails we know that pci_address_to_pio() will do too.
239 */
240int of_pci_range_to_resource(struct of_pci_range *range,
241			     struct device_node *np, struct resource *res)
242{
243	int err;
244	res->flags = range->flags;
245	res->parent = res->child = res->sibling = NULL;
246	res->name = np->full_name;
247
248	if (res->flags & IORESOURCE_IO) {
249		unsigned long port;
250		err = pci_register_io_range(&np->fwnode, range->cpu_addr,
251				range->size);
252		if (err)
253			goto invalid_range;
254		port = pci_address_to_pio(range->cpu_addr);
255		if (port == (unsigned long)-1) {
256			err = -EINVAL;
257			goto invalid_range;
258		}
259		res->start = port;
260	} else {
261		if ((sizeof(resource_size_t) < 8) &&
262		    upper_32_bits(range->cpu_addr)) {
263			err = -EINVAL;
264			goto invalid_range;
265		}
266
267		res->start = range->cpu_addr;
268	}
269	res->end = res->start + range->size - 1;
270	return 0;
271
272invalid_range:
273	res->start = (resource_size_t)OF_BAD_ADDR;
274	res->end = (resource_size_t)OF_BAD_ADDR;
275	return err;
276}
277EXPORT_SYMBOL(of_pci_range_to_resource);
278
279/*
280 * of_range_to_resource - Create a resource from a ranges entry
281 * @np:		device node where the range belongs to
282 * @index:	the 'ranges' index to convert to a resource
283 * @res:	pointer to a valid resource that will be updated to
284 *              reflect the values contained in the range.
285 *
286 * Returns ENOENT if the entry is not found or EINVAL if the range cannot be
287 * converted to resource.
288 */
289int of_range_to_resource(struct device_node *np, int index, struct resource *res)
290{
291	int ret, i = 0;
292	struct of_range_parser parser;
293	struct of_range range;
294
295	ret = of_range_parser_init(&parser, np);
296	if (ret)
297		return ret;
298
299	for_each_of_range(&parser, &range)
300		if (i++ == index)
301			return of_pci_range_to_resource(&range, np, res);
302
303	return -ENOENT;
304}
305EXPORT_SYMBOL(of_range_to_resource);
306
307/*
308 * ISA bus specific translator
309 */
310
311static int of_bus_isa_match(struct device_node *np)
312{
313	return of_node_name_eq(np, "isa");
314}
315
316static void of_bus_isa_count_cells(struct device_node *child,
317				   int *addrc, int *sizec)
318{
319	if (addrc)
320		*addrc = 2;
321	if (sizec)
322		*sizec = 1;
323}
324
325static u64 of_bus_isa_map(__be32 *addr, const __be32 *range, int na, int ns,
326		int pna)
327{
328	u64 cp, s, da;
329
330	/* Check address type match */
331	if ((addr[0] ^ range[0]) & cpu_to_be32(1))
332		return OF_BAD_ADDR;
333
334	/* Read address values, skipping high cell */
335	cp = of_read_number(range + 1, na - 1);
336	s  = of_read_number(range + na + pna, ns);
337	da = of_read_number(addr + 1, na - 1);
338
339	pr_debug("ISA map, cp=%llx, s=%llx, da=%llx\n", cp, s, da);
340
341	if (da < cp || da >= (cp + s))
342		return OF_BAD_ADDR;
343	return da - cp;
344}
345
346static int of_bus_isa_translate(__be32 *addr, u64 offset, int na)
347{
348	return of_bus_default_translate(addr + 1, offset, na - 1);
349}
350
351static unsigned int of_bus_isa_get_flags(const __be32 *addr)
352{
353	unsigned int flags = 0;
354	u32 w = be32_to_cpup(addr);
355
356	if (w & 1)
357		flags |= IORESOURCE_IO;
358	else
359		flags |= IORESOURCE_MEM;
360	return flags;
361}
362
363static int of_bus_default_flags_match(struct device_node *np)
364{
365	return of_bus_n_addr_cells(np) == 3;
366}
367
368/*
369 * Array of bus specific translators
370 */
371
372static struct of_bus of_busses[] = {
373#ifdef CONFIG_PCI
374	/* PCI */
375	{
376		.name = "pci",
377		.addresses = "assigned-addresses",
378		.match = of_bus_pci_match,
379		.count_cells = of_bus_pci_count_cells,
380		.map = of_bus_pci_map,
381		.translate = of_bus_pci_translate,
382		.has_flags = true,
383		.get_flags = of_bus_pci_get_flags,
384	},
385#endif /* CONFIG_PCI */
386	/* ISA */
387	{
388		.name = "isa",
389		.addresses = "reg",
390		.match = of_bus_isa_match,
391		.count_cells = of_bus_isa_count_cells,
392		.map = of_bus_isa_map,
393		.translate = of_bus_isa_translate,
394		.has_flags = true,
395		.get_flags = of_bus_isa_get_flags,
396	},
397	/* Default with flags cell */
398	{
399		.name = "default-flags",
400		.addresses = "reg",
401		.match = of_bus_default_flags_match,
402		.count_cells = of_bus_default_count_cells,
403		.map = of_bus_default_flags_map,
404		.translate = of_bus_default_flags_translate,
405		.has_flags = true,
406		.get_flags = of_bus_default_flags_get_flags,
407	},
408	/* Default */
409	{
410		.name = "default",
411		.addresses = "reg",
412		.match = NULL,
413		.count_cells = of_bus_default_count_cells,
414		.map = of_bus_default_map,
415		.translate = of_bus_default_translate,
416		.get_flags = of_bus_default_get_flags,
417	},
418};
419
420static struct of_bus *of_match_bus(struct device_node *np)
421{
422	int i;
423
424	for (i = 0; i < ARRAY_SIZE(of_busses); i++)
425		if (!of_busses[i].match || of_busses[i].match(np))
426			return &of_busses[i];
427	BUG();
428	return NULL;
429}
430
431static int of_empty_ranges_quirk(struct device_node *np)
432{
433	if (IS_ENABLED(CONFIG_PPC)) {
434		/* To save cycles, we cache the result for global "Mac" setting */
435		static int quirk_state = -1;
436
437		/* PA-SEMI sdc DT bug */
438		if (of_device_is_compatible(np, "1682m-sdc"))
439			return true;
440
441		/* Make quirk cached */
442		if (quirk_state < 0)
443			quirk_state =
444				of_machine_is_compatible("Power Macintosh") ||
445				of_machine_is_compatible("MacRISC");
446		return quirk_state;
447	}
448	return false;
449}
450
451static int of_translate_one(struct device_node *parent, struct of_bus *bus,
452			    struct of_bus *pbus, __be32 *addr,
453			    int na, int ns, int pna, const char *rprop)
454{
455	const __be32 *ranges;
456	unsigned int rlen;
457	int rone;
458	u64 offset = OF_BAD_ADDR;
459
460	/*
461	 * Normally, an absence of a "ranges" property means we are
462	 * crossing a non-translatable boundary, and thus the addresses
463	 * below the current cannot be converted to CPU physical ones.
464	 * Unfortunately, while this is very clear in the spec, it's not
465	 * what Apple understood, and they do have things like /uni-n or
466	 * /ht nodes with no "ranges" property and a lot of perfectly
467	 * useable mapped devices below them. Thus we treat the absence of
468	 * "ranges" as equivalent to an empty "ranges" property which means
469	 * a 1:1 translation at that level. It's up to the caller not to try
470	 * to translate addresses that aren't supposed to be translated in
471	 * the first place. --BenH.
472	 *
473	 * As far as we know, this damage only exists on Apple machines, so
474	 * This code is only enabled on powerpc. --gcl
475	 *
476	 * This quirk also applies for 'dma-ranges' which frequently exist in
477	 * child nodes without 'dma-ranges' in the parent nodes. --RobH
478	 */
479	ranges = of_get_property(parent, rprop, &rlen);
480	if (ranges == NULL && !of_empty_ranges_quirk(parent) &&
481	    strcmp(rprop, "dma-ranges")) {
482		pr_debug("no ranges; cannot translate\n");
483		return 1;
484	}
485	if (ranges == NULL || rlen == 0) {
486		offset = of_read_number(addr, na);
487		memset(addr, 0, pna * 4);
488		pr_debug("empty ranges; 1:1 translation\n");
489		goto finish;
490	}
491
492	pr_debug("walking ranges...\n");
493
494	/* Now walk through the ranges */
495	rlen /= 4;
496	rone = na + pna + ns;
497	for (; rlen >= rone; rlen -= rone, ranges += rone) {
498		offset = bus->map(addr, ranges, na, ns, pna);
499		if (offset != OF_BAD_ADDR)
500			break;
501	}
502	if (offset == OF_BAD_ADDR) {
503		pr_debug("not found !\n");
504		return 1;
505	}
506	memcpy(addr, ranges + na, 4 * pna);
507
508 finish:
509	of_dump_addr("parent translation for:", addr, pna);
510	pr_debug("with offset: %llx\n", offset);
511
512	/* Translate it into parent bus space */
513	return pbus->translate(addr, offset, pna);
514}
515
516/*
517 * Translate an address from the device-tree into a CPU physical address,
518 * this walks up the tree and applies the various bus mappings on the
519 * way.
520 *
521 * Note: We consider that crossing any level with #size-cells == 0 to mean
522 * that translation is impossible (that is we are not dealing with a value
523 * that can be mapped to a cpu physical address). This is not really specified
524 * that way, but this is traditionally the way IBM at least do things
525 *
526 * Whenever the translation fails, the *host pointer will be set to the
527 * device that had registered logical PIO mapping, and the return code is
528 * relative to that node.
529 */
530static u64 __of_translate_address(struct device_node *dev,
531				  struct device_node *(*get_parent)(const struct device_node *),
532				  const __be32 *in_addr, const char *rprop,
533				  struct device_node **host)
534{
535	struct device_node *parent = NULL;
536	struct of_bus *bus, *pbus;
537	__be32 addr[OF_MAX_ADDR_CELLS];
538	int na, ns, pna, pns;
539	u64 result = OF_BAD_ADDR;
540
541	pr_debug("** translation for device %pOF **\n", dev);
542
543	/* Increase refcount at current level */
544	of_node_get(dev);
545
546	*host = NULL;
547	/* Get parent & match bus type */
548	parent = get_parent(dev);
549	if (parent == NULL)
550		goto bail;
551	bus = of_match_bus(parent);
552
553	/* Count address cells & copy address locally */
554	bus->count_cells(dev, &na, &ns);
555	if (!OF_CHECK_COUNTS(na, ns)) {
556		pr_debug("Bad cell count for %pOF\n", dev);
557		goto bail;
558	}
559	memcpy(addr, in_addr, na * 4);
560
561	pr_debug("bus is %s (na=%d, ns=%d) on %pOF\n",
562	    bus->name, na, ns, parent);
563	of_dump_addr("translating address:", addr, na);
564
565	/* Translate */
566	for (;;) {
567		struct logic_pio_hwaddr *iorange;
568
569		/* Switch to parent bus */
570		of_node_put(dev);
571		dev = parent;
572		parent = get_parent(dev);
573
574		/* If root, we have finished */
575		if (parent == NULL) {
576			pr_debug("reached root node\n");
577			result = of_read_number(addr, na);
578			break;
579		}
580
581		/*
582		 * For indirectIO device which has no ranges property, get
583		 * the address from reg directly.
584		 */
585		iorange = find_io_range_by_fwnode(&dev->fwnode);
586		if (iorange && (iorange->flags != LOGIC_PIO_CPU_MMIO)) {
587			result = of_read_number(addr + 1, na - 1);
588			pr_debug("indirectIO matched(%pOF) 0x%llx\n",
589				 dev, result);
590			*host = of_node_get(dev);
591			break;
592		}
593
594		/* Get new parent bus and counts */
595		pbus = of_match_bus(parent);
596		pbus->count_cells(dev, &pna, &pns);
597		if (!OF_CHECK_COUNTS(pna, pns)) {
598			pr_err("Bad cell count for %pOF\n", dev);
599			break;
600		}
601
602		pr_debug("parent bus is %s (na=%d, ns=%d) on %pOF\n",
603		    pbus->name, pna, pns, parent);
604
605		/* Apply bus translation */
606		if (of_translate_one(dev, bus, pbus, addr, na, ns, pna, rprop))
607			break;
608
609		/* Complete the move up one level */
610		na = pna;
611		ns = pns;
612		bus = pbus;
613
614		of_dump_addr("one level translation:", addr, na);
615	}
616 bail:
617	of_node_put(parent);
618	of_node_put(dev);
619
620	return result;
621}
622
623u64 of_translate_address(struct device_node *dev, const __be32 *in_addr)
624{
625	struct device_node *host;
626	u64 ret;
627
628	ret = __of_translate_address(dev, of_get_parent,
629				     in_addr, "ranges", &host);
630	if (host) {
631		of_node_put(host);
632		return OF_BAD_ADDR;
633	}
634
635	return ret;
636}
637EXPORT_SYMBOL(of_translate_address);
638
639#ifdef CONFIG_HAS_DMA
640struct device_node *__of_get_dma_parent(const struct device_node *np)
641{
642	struct of_phandle_args args;
643	int ret, index;
644
645	index = of_property_match_string(np, "interconnect-names", "dma-mem");
646	if (index < 0)
647		return of_get_parent(np);
648
649	ret = of_parse_phandle_with_args(np, "interconnects",
650					 "#interconnect-cells",
651					 index, &args);
652	if (ret < 0)
653		return of_get_parent(np);
654
655	return of_node_get(args.np);
656}
657#endif
658
659static struct device_node *of_get_next_dma_parent(struct device_node *np)
660{
661	struct device_node *parent;
662
663	parent = __of_get_dma_parent(np);
664	of_node_put(np);
665
666	return parent;
667}
668
669u64 of_translate_dma_address(struct device_node *dev, const __be32 *in_addr)
670{
671	struct device_node *host;
672	u64 ret;
673
674	ret = __of_translate_address(dev, __of_get_dma_parent,
675				     in_addr, "dma-ranges", &host);
676
677	if (host) {
678		of_node_put(host);
679		return OF_BAD_ADDR;
680	}
681
682	return ret;
683}
684EXPORT_SYMBOL(of_translate_dma_address);
685
686/**
687 * of_translate_dma_region - Translate device tree address and size tuple
688 * @dev: device tree node for which to translate
689 * @prop: pointer into array of cells
690 * @start: return value for the start of the DMA range
691 * @length: return value for the length of the DMA range
692 *
693 * Returns a pointer to the cell immediately following the translated DMA region.
694 */
695const __be32 *of_translate_dma_region(struct device_node *dev, const __be32 *prop,
696				      phys_addr_t *start, size_t *length)
697{
698	struct device_node *parent;
699	u64 address, size;
700	int na, ns;
701
702	parent = __of_get_dma_parent(dev);
703	if (!parent)
704		return NULL;
705
706	na = of_bus_n_addr_cells(parent);
707	ns = of_bus_n_size_cells(parent);
708
709	of_node_put(parent);
710
711	address = of_translate_dma_address(dev, prop);
712	if (address == OF_BAD_ADDR)
713		return NULL;
714
715	size = of_read_number(prop + na, ns);
716
717	if (start)
718		*start = address;
719
720	if (length)
721		*length = size;
722
723	return prop + na + ns;
724}
725EXPORT_SYMBOL(of_translate_dma_region);
726
727const __be32 *__of_get_address(struct device_node *dev, int index, int bar_no,
728			       u64 *size, unsigned int *flags)
729{
730	const __be32 *prop;
731	unsigned int psize;
732	struct device_node *parent;
733	struct of_bus *bus;
734	int onesize, i, na, ns;
735
736	/* Get parent & match bus type */
737	parent = of_get_parent(dev);
738	if (parent == NULL)
739		return NULL;
740	bus = of_match_bus(parent);
741	if (strcmp(bus->name, "pci") && (bar_no >= 0)) {
742		of_node_put(parent);
743		return NULL;
744	}
745	bus->count_cells(dev, &na, &ns);
746	of_node_put(parent);
747	if (!OF_CHECK_ADDR_COUNT(na))
748		return NULL;
749
750	/* Get "reg" or "assigned-addresses" property */
751	prop = of_get_property(dev, bus->addresses, &psize);
752	if (prop == NULL)
753		return NULL;
754	psize /= 4;
755
756	onesize = na + ns;
757	for (i = 0; psize >= onesize; psize -= onesize, prop += onesize, i++) {
758		u32 val = be32_to_cpu(prop[0]);
759		/* PCI bus matches on BAR number instead of index */
760		if (((bar_no >= 0) && ((val & 0xff) == ((bar_no * 4) + PCI_BASE_ADDRESS_0))) ||
761		    ((index >= 0) && (i == index))) {
762			if (size)
763				*size = of_read_number(prop + na, ns);
764			if (flags)
765				*flags = bus->get_flags(prop);
766			return prop;
767		}
768	}
769	return NULL;
770}
771EXPORT_SYMBOL(__of_get_address);
772
773/**
774 * of_property_read_reg - Retrieve the specified "reg" entry index without translating
775 * @np: device tree node for which to retrieve "reg" from
776 * @idx: "reg" entry index to read
777 * @addr: return value for the untranslated address
778 * @size: return value for the entry size
779 *
780 * Returns -EINVAL if "reg" is not found. Returns 0 on success with addr and
781 * size values filled in.
782 */
783int of_property_read_reg(struct device_node *np, int idx, u64 *addr, u64 *size)
784{
785	const __be32 *prop = of_get_address(np, idx, size, NULL);
786
787	if (!prop)
788		return -EINVAL;
789
790	*addr = of_read_number(prop, of_n_addr_cells(np));
791
792	return 0;
793}
794EXPORT_SYMBOL(of_property_read_reg);
795
796static int parser_init(struct of_pci_range_parser *parser,
797			struct device_node *node, const char *name)
798{
799	int rlen;
800
801	parser->node = node;
802	parser->pna = of_n_addr_cells(node);
803	parser->na = of_bus_n_addr_cells(node);
804	parser->ns = of_bus_n_size_cells(node);
805	parser->dma = !strcmp(name, "dma-ranges");
806	parser->bus = of_match_bus(node);
807
808	parser->range = of_get_property(node, name, &rlen);
809	if (parser->range == NULL)
810		return -ENOENT;
811
812	parser->end = parser->range + rlen / sizeof(__be32);
813
814	return 0;
815}
816
817int of_pci_range_parser_init(struct of_pci_range_parser *parser,
818				struct device_node *node)
819{
820	return parser_init(parser, node, "ranges");
821}
822EXPORT_SYMBOL_GPL(of_pci_range_parser_init);
823
824int of_pci_dma_range_parser_init(struct of_pci_range_parser *parser,
825				struct device_node *node)
826{
827	return parser_init(parser, node, "dma-ranges");
828}
829EXPORT_SYMBOL_GPL(of_pci_dma_range_parser_init);
830#define of_dma_range_parser_init of_pci_dma_range_parser_init
831
832struct of_pci_range *of_pci_range_parser_one(struct of_pci_range_parser *parser,
833						struct of_pci_range *range)
834{
835	int na = parser->na;
836	int ns = parser->ns;
837	int np = parser->pna + na + ns;
838	int busflag_na = 0;
839
840	if (!range)
841		return NULL;
842
843	if (!parser->range || parser->range + np > parser->end)
844		return NULL;
845
846	range->flags = parser->bus->get_flags(parser->range);
847
848	/* A extra cell for resource flags */
849	if (parser->bus->has_flags)
850		busflag_na = 1;
851
852	range->bus_addr = of_read_number(parser->range + busflag_na, na - busflag_na);
853
854	if (parser->dma)
855		range->cpu_addr = of_translate_dma_address(parser->node,
856				parser->range + na);
857	else
858		range->cpu_addr = of_translate_address(parser->node,
859				parser->range + na);
860	range->size = of_read_number(parser->range + parser->pna + na, ns);
861
862	parser->range += np;
863
864	/* Now consume following elements while they are contiguous */
865	while (parser->range + np <= parser->end) {
866		u32 flags = 0;
867		u64 bus_addr, cpu_addr, size;
868
869		flags = parser->bus->get_flags(parser->range);
870		bus_addr = of_read_number(parser->range + busflag_na, na - busflag_na);
871		if (parser->dma)
872			cpu_addr = of_translate_dma_address(parser->node,
873					parser->range + na);
874		else
875			cpu_addr = of_translate_address(parser->node,
876					parser->range + na);
877		size = of_read_number(parser->range + parser->pna + na, ns);
878
879		if (flags != range->flags)
880			break;
881		if (bus_addr != range->bus_addr + range->size ||
882		    cpu_addr != range->cpu_addr + range->size)
883			break;
884
885		range->size += size;
886		parser->range += np;
887	}
888
889	return range;
890}
891EXPORT_SYMBOL_GPL(of_pci_range_parser_one);
892
893static u64 of_translate_ioport(struct device_node *dev, const __be32 *in_addr,
894			u64 size)
895{
896	u64 taddr;
897	unsigned long port;
898	struct device_node *host;
899
900	taddr = __of_translate_address(dev, of_get_parent,
901				       in_addr, "ranges", &host);
902	if (host) {
903		/* host-specific port access */
904		port = logic_pio_trans_hwaddr(&host->fwnode, taddr, size);
905		of_node_put(host);
906	} else {
907		/* memory-mapped I/O range */
908		port = pci_address_to_pio(taddr);
909	}
910
911	if (port == (unsigned long)-1)
912		return OF_BAD_ADDR;
913
914	return port;
915}
916
917#ifdef CONFIG_HAS_DMA
918/**
919 * of_dma_get_range - Get DMA range info and put it into a map array
920 * @np:		device node to get DMA range info
921 * @map:	dma range structure to return
922 *
923 * Look in bottom up direction for the first "dma-ranges" property
924 * and parse it.  Put the information into a DMA offset map array.
925 *
926 * dma-ranges format:
927 *	DMA addr (dma_addr)	: naddr cells
928 *	CPU addr (phys_addr_t)	: pna cells
929 *	size			: nsize cells
930 *
931 * It returns -ENODEV if "dma-ranges" property was not found for this
932 * device in the DT.
933 */
934int of_dma_get_range(struct device_node *np, const struct bus_dma_region **map)
935{
936	struct device_node *node = of_node_get(np);
937	const __be32 *ranges = NULL;
938	bool found_dma_ranges = false;
939	struct of_range_parser parser;
940	struct of_range range;
941	struct bus_dma_region *r;
942	int len, num_ranges = 0;
943	int ret = 0;
944
945	while (node) {
946		ranges = of_get_property(node, "dma-ranges", &len);
947
948		/* Ignore empty ranges, they imply no translation required */
949		if (ranges && len > 0)
950			break;
951
952		/* Once we find 'dma-ranges', then a missing one is an error */
953		if (found_dma_ranges && !ranges) {
954			ret = -ENODEV;
955			goto out;
956		}
957		found_dma_ranges = true;
958
959		node = of_get_next_dma_parent(node);
960	}
961
962	if (!node || !ranges) {
963		pr_debug("no dma-ranges found for node(%pOF)\n", np);
964		ret = -ENODEV;
965		goto out;
966	}
967
968	of_dma_range_parser_init(&parser, node);
969	for_each_of_range(&parser, &range) {
970		if (range.cpu_addr == OF_BAD_ADDR) {
971			pr_err("translation of DMA address(%llx) to CPU address failed node(%pOF)\n",
972			       range.bus_addr, node);
973			continue;
974		}
975		num_ranges++;
976	}
977
978	if (!num_ranges) {
979		ret = -EINVAL;
980		goto out;
981	}
982
983	r = kcalloc(num_ranges + 1, sizeof(*r), GFP_KERNEL);
984	if (!r) {
985		ret = -ENOMEM;
986		goto out;
987	}
988
989	/*
990	 * Record all info in the generic DMA ranges array for struct device,
991	 * returning an error if we don't find any parsable ranges.
992	 */
993	*map = r;
994	of_dma_range_parser_init(&parser, node);
995	for_each_of_range(&parser, &range) {
996		pr_debug("dma_addr(%llx) cpu_addr(%llx) size(%llx)\n",
997			 range.bus_addr, range.cpu_addr, range.size);
998		if (range.cpu_addr == OF_BAD_ADDR)
999			continue;
1000		r->cpu_start = range.cpu_addr;
1001		r->dma_start = range.bus_addr;
1002		r->size = range.size;
1003		r->offset = range.cpu_addr - range.bus_addr;
1004		r++;
1005	}
1006out:
1007	of_node_put(node);
1008	return ret;
1009}
1010#endif /* CONFIG_HAS_DMA */
1011
1012/**
1013 * of_dma_get_max_cpu_address - Gets highest CPU address suitable for DMA
1014 * @np: The node to start searching from or NULL to start from the root
1015 *
1016 * Gets the highest CPU physical address that is addressable by all DMA masters
1017 * in the sub-tree pointed by np, or the whole tree if NULL is passed. If no
1018 * DMA constrained device is found, it returns PHYS_ADDR_MAX.
1019 */
1020phys_addr_t __init of_dma_get_max_cpu_address(struct device_node *np)
1021{
1022	phys_addr_t max_cpu_addr = PHYS_ADDR_MAX;
1023	struct of_range_parser parser;
1024	phys_addr_t subtree_max_addr;
1025	struct device_node *child;
1026	struct of_range range;
1027	const __be32 *ranges;
1028	u64 cpu_end = 0;
1029	int len;
1030
1031	if (!np)
1032		np = of_root;
1033
1034	ranges = of_get_property(np, "dma-ranges", &len);
1035	if (ranges && len) {
1036		of_dma_range_parser_init(&parser, np);
1037		for_each_of_range(&parser, &range)
1038			if (range.cpu_addr + range.size > cpu_end)
1039				cpu_end = range.cpu_addr + range.size - 1;
1040
1041		if (max_cpu_addr > cpu_end)
1042			max_cpu_addr = cpu_end;
1043	}
1044
1045	for_each_available_child_of_node(np, child) {
1046		subtree_max_addr = of_dma_get_max_cpu_address(child);
1047		if (max_cpu_addr > subtree_max_addr)
1048			max_cpu_addr = subtree_max_addr;
1049	}
1050
1051	return max_cpu_addr;
1052}
1053
1054/**
1055 * of_dma_is_coherent - Check if device is coherent
1056 * @np:	device node
1057 *
1058 * It returns true if "dma-coherent" property was found
1059 * for this device in the DT, or if DMA is coherent by
1060 * default for OF devices on the current platform and no
1061 * "dma-noncoherent" property was found for this device.
1062 */
1063bool of_dma_is_coherent(struct device_node *np)
1064{
1065	struct device_node *node;
1066	bool is_coherent = dma_default_coherent;
1067
1068	node = of_node_get(np);
1069
1070	while (node) {
1071		if (of_property_read_bool(node, "dma-coherent")) {
1072			is_coherent = true;
1073			break;
1074		}
1075		if (of_property_read_bool(node, "dma-noncoherent")) {
1076			is_coherent = false;
1077			break;
1078		}
1079		node = of_get_next_dma_parent(node);
1080	}
1081	of_node_put(node);
1082	return is_coherent;
1083}
1084EXPORT_SYMBOL_GPL(of_dma_is_coherent);
1085
1086/**
1087 * of_mmio_is_nonposted - Check if device uses non-posted MMIO
1088 * @np:	device node
1089 *
1090 * Returns true if the "nonposted-mmio" property was found for
1091 * the device's bus.
1092 *
1093 * This is currently only enabled on builds that support Apple ARM devices, as
1094 * an optimization.
1095 */
1096static bool of_mmio_is_nonposted(struct device_node *np)
1097{
1098	struct device_node *parent;
1099	bool nonposted;
1100
1101	if (!IS_ENABLED(CONFIG_ARCH_APPLE))
1102		return false;
1103
1104	parent = of_get_parent(np);
1105	if (!parent)
1106		return false;
1107
1108	nonposted = of_property_read_bool(parent, "nonposted-mmio");
1109
1110	of_node_put(parent);
1111	return nonposted;
1112}
1113
1114static int __of_address_to_resource(struct device_node *dev, int index, int bar_no,
1115		struct resource *r)
1116{
1117	u64 taddr;
1118	const __be32	*addrp;
1119	u64		size;
1120	unsigned int	flags;
1121	const char	*name = NULL;
1122
1123	addrp = __of_get_address(dev, index, bar_no, &size, &flags);
1124	if (addrp == NULL)
1125		return -EINVAL;
1126
1127	/* Get optional "reg-names" property to add a name to a resource */
1128	if (index >= 0)
1129		of_property_read_string_index(dev, "reg-names",	index, &name);
1130
1131	if (flags & IORESOURCE_MEM)
1132		taddr = of_translate_address(dev, addrp);
1133	else if (flags & IORESOURCE_IO)
1134		taddr = of_translate_ioport(dev, addrp, size);
1135	else
1136		return -EINVAL;
1137
1138	if (taddr == OF_BAD_ADDR)
1139		return -EINVAL;
1140	memset(r, 0, sizeof(struct resource));
1141
1142	if (of_mmio_is_nonposted(dev))
1143		flags |= IORESOURCE_MEM_NONPOSTED;
1144
1145	r->start = taddr;
1146	r->end = taddr + size - 1;
1147	r->flags = flags;
1148	r->name = name ? name : dev->full_name;
1149
1150	return 0;
1151}
1152
1153/**
1154 * of_address_to_resource - Translate device tree address and return as resource
1155 * @dev:	Caller's Device Node
1156 * @index:	Index into the array
1157 * @r:		Pointer to resource array
1158 *
1159 * Returns -EINVAL if the range cannot be converted to resource.
1160 *
1161 * Note that if your address is a PIO address, the conversion will fail if
1162 * the physical address can't be internally converted to an IO token with
1163 * pci_address_to_pio(), that is because it's either called too early or it
1164 * can't be matched to any host bridge IO space
1165 */
1166int of_address_to_resource(struct device_node *dev, int index,
1167			   struct resource *r)
1168{
1169	return __of_address_to_resource(dev, index, -1, r);
1170}
1171EXPORT_SYMBOL_GPL(of_address_to_resource);
1172
1173int of_pci_address_to_resource(struct device_node *dev, int bar,
1174			       struct resource *r)
1175{
1176
1177	if (!IS_ENABLED(CONFIG_PCI))
1178		return -ENOSYS;
1179
1180	return __of_address_to_resource(dev, -1, bar, r);
1181}
1182EXPORT_SYMBOL_GPL(of_pci_address_to_resource);
1183
1184/**
1185 * of_iomap - Maps the memory mapped IO for a given device_node
1186 * @np:		the device whose io range will be mapped
1187 * @index:	index of the io range
1188 *
1189 * Returns a pointer to the mapped memory
1190 */
1191void __iomem *of_iomap(struct device_node *np, int index)
1192{
1193	struct resource res;
1194
1195	if (of_address_to_resource(np, index, &res))
1196		return NULL;
1197
1198	if (res.flags & IORESOURCE_MEM_NONPOSTED)
1199		return ioremap_np(res.start, resource_size(&res));
1200	else
1201		return ioremap(res.start, resource_size(&res));
1202}
1203EXPORT_SYMBOL(of_iomap);
1204
1205/*
1206 * of_io_request_and_map - Requests a resource and maps the memory mapped IO
1207 *			   for a given device_node
1208 * @device:	the device whose io range will be mapped
1209 * @index:	index of the io range
1210 * @name:	name "override" for the memory region request or NULL
1211 *
1212 * Returns a pointer to the requested and mapped memory or an ERR_PTR() encoded
1213 * error code on failure. Usage example:
1214 *
1215 *	base = of_io_request_and_map(node, 0, "foo");
1216 *	if (IS_ERR(base))
1217 *		return PTR_ERR(base);
1218 */
1219void __iomem *of_io_request_and_map(struct device_node *np, int index,
1220				    const char *name)
1221{
1222	struct resource res;
1223	void __iomem *mem;
1224
1225	if (of_address_to_resource(np, index, &res))
1226		return IOMEM_ERR_PTR(-EINVAL);
1227
1228	if (!name)
1229		name = res.name;
1230	if (!request_mem_region(res.start, resource_size(&res), name))
1231		return IOMEM_ERR_PTR(-EBUSY);
1232
1233	if (res.flags & IORESOURCE_MEM_NONPOSTED)
1234		mem = ioremap_np(res.start, resource_size(&res));
1235	else
1236		mem = ioremap(res.start, resource_size(&res));
1237
1238	if (!mem) {
1239		release_mem_region(res.start, resource_size(&res));
1240		return IOMEM_ERR_PTR(-ENOMEM);
1241	}
1242
1243	return mem;
1244}
1245EXPORT_SYMBOL(of_io_request_and_map);
1246