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