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