xref: /linux/drivers/of/address.c (revision 1b30456150e57a79e300b82eb2efac40c25a162e)
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 
815 	range->parent_bus_addr = of_read_number(parser->range + na, parser->pna);
816 	range->size = of_read_number(parser->range + parser->pna + na, ns);
817 
818 	parser->range += np;
819 
820 	/* Now consume following elements while they are contiguous */
821 	while (parser->range + np <= parser->end) {
822 		u32 flags = 0;
823 		u64 bus_addr, cpu_addr, size;
824 
825 		flags = parser->bus->get_flags(parser->range);
826 		bus_addr = of_read_number(parser->range + busflag_na, na - busflag_na);
827 		if (parser->dma)
828 			cpu_addr = of_translate_dma_address(parser->node,
829 					parser->range + na);
830 		else
831 			cpu_addr = of_translate_address(parser->node,
832 					parser->range + na);
833 		size = of_read_number(parser->range + parser->pna + na, ns);
834 
835 		if (flags != range->flags)
836 			break;
837 		if (bus_addr != range->bus_addr + range->size ||
838 		    cpu_addr != range->cpu_addr + range->size)
839 			break;
840 
841 		range->size += size;
842 		parser->range += np;
843 	}
844 
845 	return range;
846 }
847 EXPORT_SYMBOL_GPL(of_pci_range_parser_one);
848 
849 static u64 of_translate_ioport(struct device_node *dev, const __be32 *in_addr,
850 			u64 size)
851 {
852 	u64 taddr;
853 	unsigned long port;
854 	struct device_node *host;
855 
856 	taddr = __of_translate_address(dev, of_get_parent,
857 				       in_addr, "ranges", &host);
858 	if (host) {
859 		/* host-specific port access */
860 		port = logic_pio_trans_hwaddr(&host->fwnode, taddr, size);
861 		of_node_put(host);
862 	} else {
863 		/* memory-mapped I/O range */
864 		port = pci_address_to_pio(taddr);
865 	}
866 
867 	if (port == (unsigned long)-1)
868 		return OF_BAD_ADDR;
869 
870 	return port;
871 }
872 
873 #ifdef CONFIG_HAS_DMA
874 /**
875  * of_dma_get_range - Get DMA range info and put it into a map array
876  * @np:		device node to get DMA range info
877  * @map:	dma range structure to return
878  *
879  * Look in bottom up direction for the first "dma-ranges" property
880  * and parse it.  Put the information into a DMA offset map array.
881  *
882  * dma-ranges format:
883  *	DMA addr (dma_addr)	: naddr cells
884  *	CPU addr (phys_addr_t)	: pna cells
885  *	size			: nsize cells
886  *
887  * It returns -ENODEV if "dma-ranges" property was not found for this
888  * device in the DT.
889  */
890 int of_dma_get_range(struct device_node *np, const struct bus_dma_region **map)
891 {
892 	struct device_node *node __free(device_node) = of_node_get(np);
893 	const __be32 *ranges = NULL;
894 	bool found_dma_ranges = false;
895 	struct of_range_parser parser;
896 	struct of_range range;
897 	struct bus_dma_region *r;
898 	int len, num_ranges = 0;
899 
900 	while (node) {
901 		ranges = of_get_property(node, "dma-ranges", &len);
902 
903 		/* Ignore empty ranges, they imply no translation required */
904 		if (ranges && len > 0)
905 			break;
906 
907 		/* Once we find 'dma-ranges', then a missing one is an error */
908 		if (found_dma_ranges && !ranges)
909 			return -ENODEV;
910 
911 		found_dma_ranges = true;
912 
913 		node = of_get_next_dma_parent(node);
914 	}
915 
916 	if (!node || !ranges) {
917 		pr_debug("no dma-ranges found for node(%pOF)\n", np);
918 		return -ENODEV;
919 	}
920 	of_dma_range_parser_init(&parser, node);
921 	for_each_of_range(&parser, &range) {
922 		if (range.cpu_addr == OF_BAD_ADDR) {
923 			pr_err("translation of DMA address(%llx) to CPU address failed node(%pOF)\n",
924 			       range.bus_addr, node);
925 			continue;
926 		}
927 		num_ranges++;
928 	}
929 
930 	if (!num_ranges)
931 		return -EINVAL;
932 
933 	r = kcalloc(num_ranges + 1, sizeof(*r), GFP_KERNEL);
934 	if (!r)
935 		return -ENOMEM;
936 
937 	/*
938 	 * Record all info in the generic DMA ranges array for struct device,
939 	 * returning an error if we don't find any parsable ranges.
940 	 */
941 	*map = r;
942 	of_dma_range_parser_init(&parser, node);
943 	for_each_of_range(&parser, &range) {
944 		pr_debug("dma_addr(%llx) cpu_addr(%llx) size(%llx)\n",
945 			 range.bus_addr, range.cpu_addr, range.size);
946 		if (range.cpu_addr == OF_BAD_ADDR)
947 			continue;
948 		r->cpu_start = range.cpu_addr;
949 		r->dma_start = range.bus_addr;
950 		r->size = range.size;
951 		r++;
952 	}
953 	return 0;
954 }
955 #endif /* CONFIG_HAS_DMA */
956 
957 /**
958  * of_dma_get_max_cpu_address - Gets highest CPU address suitable for DMA
959  * @np: The node to start searching from or NULL to start from the root
960  *
961  * Gets the highest CPU physical address that is addressable by all DMA masters
962  * in the sub-tree pointed by np, or the whole tree if NULL is passed. If no
963  * DMA constrained device is found, it returns PHYS_ADDR_MAX.
964  */
965 phys_addr_t __init of_dma_get_max_cpu_address(struct device_node *np)
966 {
967 	phys_addr_t max_cpu_addr = PHYS_ADDR_MAX;
968 	struct of_range_parser parser;
969 	phys_addr_t subtree_max_addr;
970 	struct device_node *child;
971 	struct of_range range;
972 	const __be32 *ranges;
973 	u64 cpu_end = 0;
974 	int len;
975 
976 	if (!np)
977 		np = of_root;
978 
979 	ranges = of_get_property(np, "dma-ranges", &len);
980 	if (ranges && len) {
981 		of_dma_range_parser_init(&parser, np);
982 		for_each_of_range(&parser, &range)
983 			if (range.cpu_addr + range.size > cpu_end)
984 				cpu_end = range.cpu_addr + range.size - 1;
985 
986 		if (max_cpu_addr > cpu_end)
987 			max_cpu_addr = cpu_end;
988 	}
989 
990 	for_each_available_child_of_node(np, child) {
991 		subtree_max_addr = of_dma_get_max_cpu_address(child);
992 		if (max_cpu_addr > subtree_max_addr)
993 			max_cpu_addr = subtree_max_addr;
994 	}
995 
996 	return max_cpu_addr;
997 }
998 
999 /**
1000  * of_dma_is_coherent - Check if device is coherent
1001  * @np:	device node
1002  *
1003  * It returns true if "dma-coherent" property was found
1004  * for this device in the DT, or if DMA is coherent by
1005  * default for OF devices on the current platform and no
1006  * "dma-noncoherent" property was found for this device.
1007  */
1008 bool of_dma_is_coherent(struct device_node *np)
1009 {
1010 	struct device_node *node __free(device_node) = of_node_get(np);
1011 
1012 	while (node) {
1013 		if (of_property_read_bool(node, "dma-coherent"))
1014 			return true;
1015 
1016 		if (of_property_read_bool(node, "dma-noncoherent"))
1017 			return false;
1018 
1019 		node = of_get_next_dma_parent(node);
1020 	}
1021 	return dma_default_coherent;
1022 }
1023 EXPORT_SYMBOL_GPL(of_dma_is_coherent);
1024 
1025 /**
1026  * of_mmio_is_nonposted - Check if device uses non-posted MMIO
1027  * @np:	device node
1028  *
1029  * Returns true if the "nonposted-mmio" property was found for
1030  * the device's bus.
1031  *
1032  * This is currently only enabled on builds that support Apple ARM devices, as
1033  * an optimization.
1034  */
1035 static bool of_mmio_is_nonposted(const struct device_node *np)
1036 {
1037 	if (!IS_ENABLED(CONFIG_ARCH_APPLE))
1038 		return false;
1039 
1040 	struct device_node *parent __free(device_node) = of_get_parent(np);
1041 	if (!parent)
1042 		return false;
1043 
1044 	return of_property_read_bool(parent, "nonposted-mmio");
1045 }
1046 
1047 static int __of_address_to_resource(struct device_node *dev, int index, int bar_no,
1048 		struct resource *r)
1049 {
1050 	u64 taddr;
1051 	const __be32	*addrp;
1052 	u64		size;
1053 	unsigned int	flags;
1054 	const char	*name = NULL;
1055 
1056 	addrp = __of_get_address(dev, index, bar_no, &size, &flags);
1057 	if (addrp == NULL)
1058 		return -EINVAL;
1059 
1060 	/* Get optional "reg-names" property to add a name to a resource */
1061 	if (index >= 0)
1062 		of_property_read_string_index(dev, "reg-names",	index, &name);
1063 
1064 	if (flags & IORESOURCE_MEM)
1065 		taddr = of_translate_address(dev, addrp);
1066 	else if (flags & IORESOURCE_IO)
1067 		taddr = of_translate_ioport(dev, addrp, size);
1068 	else
1069 		return -EINVAL;
1070 
1071 	if (taddr == OF_BAD_ADDR)
1072 		return -EINVAL;
1073 	memset(r, 0, sizeof(struct resource));
1074 
1075 	if (of_mmio_is_nonposted(dev))
1076 		flags |= IORESOURCE_MEM_NONPOSTED;
1077 
1078 	r->flags = flags;
1079 	r->name = name ? name : dev->full_name;
1080 
1081 	return __of_address_resource_bounds(r, taddr, size);
1082 }
1083 
1084 /**
1085  * of_address_to_resource - Translate device tree address and return as resource
1086  * @dev:	Caller's Device Node
1087  * @index:	Index into the array
1088  * @r:		Pointer to resource array
1089  *
1090  * Returns -EINVAL if the range cannot be converted to resource.
1091  *
1092  * Note that if your address is a PIO address, the conversion will fail if
1093  * the physical address can't be internally converted to an IO token with
1094  * pci_address_to_pio(), that is because it's either called too early or it
1095  * can't be matched to any host bridge IO space
1096  */
1097 int of_address_to_resource(struct device_node *dev, int index,
1098 			   struct resource *r)
1099 {
1100 	return __of_address_to_resource(dev, index, -1, r);
1101 }
1102 EXPORT_SYMBOL_GPL(of_address_to_resource);
1103 
1104 int of_pci_address_to_resource(struct device_node *dev, int bar,
1105 			       struct resource *r)
1106 {
1107 
1108 	if (!IS_ENABLED(CONFIG_PCI))
1109 		return -ENOSYS;
1110 
1111 	return __of_address_to_resource(dev, -1, bar, r);
1112 }
1113 EXPORT_SYMBOL_GPL(of_pci_address_to_resource);
1114 
1115 /**
1116  * of_iomap - Maps the memory mapped IO for a given device_node
1117  * @np:		the device whose io range will be mapped
1118  * @index:	index of the io range
1119  *
1120  * Returns a pointer to the mapped memory
1121  */
1122 void __iomem *of_iomap(struct device_node *np, int index)
1123 {
1124 	struct resource res;
1125 
1126 	if (of_address_to_resource(np, index, &res))
1127 		return NULL;
1128 
1129 	if (res.flags & IORESOURCE_MEM_NONPOSTED)
1130 		return ioremap_np(res.start, resource_size(&res));
1131 	else
1132 		return ioremap(res.start, resource_size(&res));
1133 }
1134 EXPORT_SYMBOL(of_iomap);
1135 
1136 /*
1137  * of_io_request_and_map - Requests a resource and maps the memory mapped IO
1138  *			   for a given device_node
1139  * @device:	the device whose io range will be mapped
1140  * @index:	index of the io range
1141  * @name:	name "override" for the memory region request or NULL
1142  *
1143  * Returns a pointer to the requested and mapped memory or an ERR_PTR() encoded
1144  * error code on failure. Usage example:
1145  *
1146  *	base = of_io_request_and_map(node, 0, "foo");
1147  *	if (IS_ERR(base))
1148  *		return PTR_ERR(base);
1149  */
1150 void __iomem *of_io_request_and_map(struct device_node *np, int index,
1151 				    const char *name)
1152 {
1153 	struct resource res;
1154 	void __iomem *mem;
1155 
1156 	if (of_address_to_resource(np, index, &res))
1157 		return IOMEM_ERR_PTR(-EINVAL);
1158 
1159 	if (!name)
1160 		name = res.name;
1161 	if (!request_mem_region(res.start, resource_size(&res), name))
1162 		return IOMEM_ERR_PTR(-EBUSY);
1163 
1164 	if (res.flags & IORESOURCE_MEM_NONPOSTED)
1165 		mem = ioremap_np(res.start, resource_size(&res));
1166 	else
1167 		mem = ioremap(res.start, resource_size(&res));
1168 
1169 	if (!mem) {
1170 		release_mem_region(res.start, resource_size(&res));
1171 		return IOMEM_ERR_PTR(-ENOMEM);
1172 	}
1173 
1174 	return mem;
1175 }
1176 EXPORT_SYMBOL(of_io_request_and_map);
1177