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