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