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