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