1 /*
2  * Device Tree
3  *
4  * Copyright (C) 2012 Citrix Systems, Inc.
5  * Copyright 2009 Benjamin Herrenschmidt, IBM Corp
6  * benh@kernel.crashing.org
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  */
12 
13 #include <xen/types.h>
14 #include <xen/init.h>
15 #include <xen/guest_access.h>
16 #include <xen/device_tree.h>
17 #include <xen/kernel.h>
18 #include <xen/lib.h>
19 #include <xen/libfdt/libfdt.h>
20 #include <xen/mm.h>
21 #include <xen/stdarg.h>
22 #include <xen/string.h>
23 #include <xen/cpumask.h>
24 #include <xen/ctype.h>
25 #include <asm/setup.h>
26 #include <xen/err.h>
27 
28 const void *device_tree_flattened;
29 dt_irq_xlate_func dt_irq_xlate;
30 /* Host device tree */
31 struct dt_device_node *dt_host;
32 /* Interrupt controller node*/
33 const struct dt_device_node *dt_interrupt_controller;
34 
35 /**
36  * struct dt_alias_prop - Alias property in 'aliases' node
37  * @link: List node to link the structure in aliases_lookup list
38  * @alias: Alias property name
39  * @np: Pointer to device_node that the alias stands for
40  * @id: Index value from end of alias name
41  * @stem: Alias string without the index
42  *
43  * The structure represents one alias property of 'aliases' node as
44  * an entry in aliases_lookup list.
45  */
46 struct dt_alias_prop {
47     struct list_head link;
48     const char *alias;
49     struct dt_device_node *np;
50     int id;
51     char stem[0];
52 };
53 
54 static LIST_HEAD(aliases_lookup);
55 
56 #ifdef CONFIG_DEVICE_TREE_DEBUG
dt_dump_addr(const char * s,const __be32 * addr,int na)57 static void dt_dump_addr(const char *s, const __be32 *addr, int na)
58 {
59     dt_dprintk("%s", s);
60     while ( na-- )
61         dt_dprintk(" %08x", be32_to_cpu(*(addr++)));
62     dt_dprintk("\n");
63 }
64 #else
dt_dump_addr(const char * s,const __be32 * addr,int na)65 static void dt_dump_addr(const char *s, const __be32 *addr, int na) { }
66 #endif
67 
68 #define DT_BAD_ADDR ((u64)-1)
69 
70 /* Max address size we deal with */
71 #define DT_MAX_ADDR_CELLS 4
72 #define DT_CHECK_ADDR_COUNT(na) ((na) > 0 && (na) <= DT_MAX_ADDR_CELLS)
73 #define DT_CHECK_COUNTS(na, ns) (DT_CHECK_ADDR_COUNT(na) && (ns) > 0)
74 
75 /* Callbacks for bus specific translators */
76 struct dt_bus
77 {
78     const char *name;
79     const char *addresses;
80     bool_t (*match)(const struct dt_device_node *node);
81     void (*count_cells)(const struct dt_device_node *child,
82                         int *addrc, int *sizec);
83     u64 (*map)(__be32 *addr, const __be32 *range, int na, int ns, int pna);
84     int (*translate)(__be32 *addr, u64 offset, int na);
85     unsigned int (*get_flags)(const __be32 *addr);
86 };
87 
dt_get_range(const __be32 ** cell,const struct dt_device_node * np,u64 * address,u64 * size)88 void dt_get_range(const __be32 **cell, const struct dt_device_node *np,
89                   u64 *address, u64 *size)
90 {
91     *address = dt_next_cell(dt_n_addr_cells(np), cell);
92     *size = dt_next_cell(dt_n_size_cells(np), cell);
93 }
94 
dt_set_cell(__be32 ** cellp,int size,u64 val)95 void dt_set_cell(__be32 **cellp, int size, u64 val)
96 {
97     int cells = size;
98 
99     while ( size-- )
100     {
101         (*cellp)[size] = cpu_to_fdt32(val);
102         val >>= 32;
103     }
104 
105     (*cellp) += cells;
106 }
107 
dt_set_range(__be32 ** cellp,const struct dt_device_node * np,u64 address,u64 size)108 void dt_set_range(__be32 **cellp, const struct dt_device_node *np,
109                   u64 address, u64 size)
110 {
111     dt_set_cell(cellp, dt_n_addr_cells(np), address);
112     dt_set_cell(cellp, dt_n_size_cells(np), size);
113 }
114 
dt_child_set_range(__be32 ** cellp,const struct dt_device_node * parent,u64 address,u64 size)115 void dt_child_set_range(__be32 **cellp, const struct dt_device_node *parent,
116                         u64 address, u64 size)
117 {
118     dt_set_cell(cellp, dt_child_n_addr_cells(parent), address);
119     dt_set_cell(cellp, dt_child_n_size_cells(parent), size);
120 }
121 
unflatten_dt_alloc(unsigned long * mem,unsigned long size,unsigned long align)122 static void __init *unflatten_dt_alloc(unsigned long *mem, unsigned long size,
123                                        unsigned long align)
124 {
125     void *res;
126 
127     *mem = ROUNDUP(*mem, align);
128     res = (void *)*mem;
129     *mem += size;
130 
131     return res;
132 }
133 
134 /* Find a property with a given name for a given node and return it. */
dt_find_property(const struct dt_device_node * np,const char * name,u32 * lenp)135 const struct dt_property *dt_find_property(const struct dt_device_node *np,
136                                            const char *name, u32 *lenp)
137 {
138     const struct dt_property *pp;
139 
140     if ( !np )
141         return NULL;
142 
143     for ( pp = np->properties; pp; pp = pp->next )
144     {
145         if ( dt_prop_cmp(pp->name, name) == 0 )
146         {
147             if ( lenp )
148                 *lenp = pp->length;
149             break;
150         }
151     }
152 
153     return pp;
154 }
155 
dt_get_property(const struct dt_device_node * np,const char * name,u32 * lenp)156 const void *dt_get_property(const struct dt_device_node *np,
157                             const char *name, u32 *lenp)
158 {
159     const struct dt_property *pp = dt_find_property(np, name, lenp);
160 
161     return pp ? pp->value : NULL;
162 }
163 
dt_property_read_u32(const struct dt_device_node * np,const char * name,u32 * out_value)164 bool_t dt_property_read_u32(const struct dt_device_node *np,
165                          const char *name, u32 *out_value)
166 {
167     u32 len;
168     const __be32 *val;
169 
170     val = dt_get_property(np, name, &len);
171     if ( !val || len < sizeof(*out_value) )
172         return 0;
173 
174     *out_value = be32_to_cpup(val);
175 
176     return 1;
177 }
178 
179 
dt_property_read_u64(const struct dt_device_node * np,const char * name,u64 * out_value)180 bool_t dt_property_read_u64(const struct dt_device_node *np,
181                          const char *name, u64 *out_value)
182 {
183     u32 len;
184     const __be32 *val;
185 
186     val = dt_get_property(np, name, &len);
187     if ( !val || len < sizeof(*out_value) )
188         return 0;
189 
190     *out_value = dt_read_number(val, 2);
191 
192     return 1;
193 }
dt_property_read_string(const struct dt_device_node * np,const char * propname,const char ** out_string)194 int dt_property_read_string(const struct dt_device_node *np,
195                             const char *propname, const char **out_string)
196 {
197     const struct dt_property *pp = dt_find_property(np, propname, NULL);
198 
199     if ( !pp )
200         return -EINVAL;
201     if ( !pp->value )
202         return -ENODATA;
203     if ( strnlen(pp->value, pp->length) >= pp->length )
204         return -EILSEQ;
205 
206     *out_string = pp->value;
207 
208     return 0;
209 }
210 
dt_device_is_compatible(const struct dt_device_node * device,const char * compat)211 bool_t dt_device_is_compatible(const struct dt_device_node *device,
212                                const char *compat)
213 {
214     const char* cp;
215     u32 cplen, l;
216 
217     cp = dt_get_property(device, "compatible", &cplen);
218     if ( cp == NULL )
219         return 0;
220     while ( cplen > 0 )
221     {
222         if ( dt_compat_cmp(cp, compat) == 0 )
223             return 1;
224         l = strlen(cp) + 1;
225         cp += l;
226         cplen -= l;
227     }
228 
229     return 0;
230 }
231 
dt_machine_is_compatible(const char * compat)232 bool_t dt_machine_is_compatible(const char *compat)
233 {
234     const struct dt_device_node *root;
235     bool_t rc = 0;
236 
237     root = dt_find_node_by_path("/");
238     if ( root )
239     {
240         rc = dt_device_is_compatible(root, compat);
241     }
242     return rc;
243 }
244 
dt_find_node_by_name(struct dt_device_node * from,const char * name)245 struct dt_device_node *dt_find_node_by_name(struct dt_device_node *from,
246                                             const char *name)
247 {
248     struct dt_device_node *np;
249     struct dt_device_node *dt;
250 
251     dt = from ? from->allnext : dt_host;
252     dt_for_each_device_node(dt, np)
253         if ( np->name && (dt_node_cmp(np->name, name) == 0) )
254             break;
255 
256     return np;
257 }
258 
dt_find_node_by_type(struct dt_device_node * from,const char * type)259 struct dt_device_node *dt_find_node_by_type(struct dt_device_node *from,
260                                             const char *type)
261 {
262     struct dt_device_node *np;
263     struct dt_device_node *dt;
264 
265     dt = from ? from->allnext : dt_host;
266     dt_for_each_device_node(dt, np)
267         if ( np->type && (dt_node_cmp(np->type, type) == 0) )
268             break;
269 
270     return np;
271 }
272 
dt_find_node_by_path(const char * path)273 struct dt_device_node *dt_find_node_by_path(const char *path)
274 {
275     struct dt_device_node *np;
276 
277     dt_for_each_device_node(dt_host, np)
278         if ( np->full_name && (dt_node_cmp(np->full_name, path) == 0) )
279             break;
280 
281     return np;
282 }
283 
dt_find_node_by_gpath(XEN_GUEST_HANDLE (char)u_path,uint32_t u_plen,struct dt_device_node ** node)284 int dt_find_node_by_gpath(XEN_GUEST_HANDLE(char) u_path, uint32_t u_plen,
285                           struct dt_device_node **node)
286 {
287     char *path;
288 
289     path = safe_copy_string_from_guest(u_path, u_plen, PAGE_SIZE);
290     if ( IS_ERR(path) )
291         return PTR_ERR(path);
292 
293     *node = dt_find_node_by_path(path);
294 
295     xfree(path);
296 
297     return (*node == NULL) ? -ESRCH : 0;
298 }
299 
dt_find_node_by_alias(const char * alias)300 struct dt_device_node *dt_find_node_by_alias(const char *alias)
301 {
302     const struct dt_alias_prop *app;
303 
304     list_for_each_entry( app, &aliases_lookup, link )
305     {
306         if ( !strcmp(app->alias, alias) )
307             return app->np;
308     }
309 
310     return NULL;
311 }
312 
313 const struct dt_device_match *
dt_match_node(const struct dt_device_match * matches,const struct dt_device_node * node)314 dt_match_node(const struct dt_device_match *matches,
315               const struct dt_device_node *node)
316 {
317     if ( !matches )
318         return NULL;
319 
320     while ( matches->path || matches->type ||
321             matches->compatible || matches->not_available || matches->prop)
322     {
323         bool_t match = 1;
324 
325         if ( matches->path )
326             match &= dt_node_path_is_equal(node, matches->path);
327 
328         if ( matches->type )
329             match &= dt_device_type_is_equal(node, matches->type);
330 
331         if ( matches->compatible )
332             match &= dt_device_is_compatible(node, matches->compatible);
333 
334         if ( matches->not_available )
335             match &= !dt_device_is_available(node);
336 
337         if ( matches->prop )
338             match &= dt_find_property(node, matches->prop, NULL) != NULL;
339 
340         if ( match )
341             return matches;
342         matches++;
343     }
344 
345     return NULL;
346 }
347 
dt_get_parent(const struct dt_device_node * node)348 const struct dt_device_node *dt_get_parent(const struct dt_device_node *node)
349 {
350     if ( !node )
351         return NULL;
352 
353     return node->parent;
354 }
355 
356 struct dt_device_node *
dt_find_compatible_node(struct dt_device_node * from,const char * type,const char * compatible)357 dt_find_compatible_node(struct dt_device_node *from,
358                         const char *type,
359                         const char *compatible)
360 {
361     struct dt_device_node *np;
362     struct dt_device_node *dt;
363 
364     dt = from ? from->allnext : dt_host;
365     dt_for_each_device_node(dt, np)
366     {
367         if ( type
368              && !(np->type && (dt_node_cmp(np->type, type) == 0)) )
369             continue;
370         if ( dt_device_is_compatible(np, compatible) )
371             break;
372     }
373 
374     return np;
375 }
376 
377 struct dt_device_node *
dt_find_matching_node(struct dt_device_node * from,const struct dt_device_match * matches)378 dt_find_matching_node(struct dt_device_node *from,
379                       const struct dt_device_match *matches)
380 {
381     struct dt_device_node *np;
382     struct dt_device_node *dt;
383 
384     dt = from ? from->allnext : dt_host;
385     dt_for_each_device_node(dt, np)
386     {
387         if ( dt_match_node(matches, np) )
388             return np;
389     }
390 
391     return NULL;
392 }
393 
__dt_n_addr_cells(const struct dt_device_node * np,bool_t parent)394 static int __dt_n_addr_cells(const struct dt_device_node *np, bool_t parent)
395 {
396     const __be32 *ip;
397 
398     do {
399         if ( np->parent && !parent )
400             np = np->parent;
401         parent = false;
402 
403         ip = dt_get_property(np, "#address-cells", NULL);
404         if ( ip )
405             return be32_to_cpup(ip);
406     } while ( np->parent );
407     /* No #address-cells property for the root node */
408     return DT_ROOT_NODE_ADDR_CELLS_DEFAULT;
409 }
410 
__dt_n_size_cells(const struct dt_device_node * np,bool_t parent)411 int __dt_n_size_cells(const struct dt_device_node *np, bool_t parent)
412 {
413     const __be32 *ip;
414 
415     do {
416         if ( np->parent && !parent )
417             np = np->parent;
418         parent = false;
419 
420         ip = dt_get_property(np, "#size-cells", NULL);
421         if ( ip )
422             return be32_to_cpup(ip);
423     } while ( np->parent );
424     /* No #address-cells property for the root node */
425     return DT_ROOT_NODE_SIZE_CELLS_DEFAULT;
426 }
427 
dt_n_addr_cells(const struct dt_device_node * np)428 int dt_n_addr_cells(const struct dt_device_node *np)
429 {
430     return __dt_n_addr_cells(np, false);
431 }
432 
dt_n_size_cells(const struct dt_device_node * np)433 int dt_n_size_cells(const struct dt_device_node *np)
434 {
435     return __dt_n_size_cells(np, false);
436 }
437 
dt_child_n_addr_cells(const struct dt_device_node * parent)438 int dt_child_n_addr_cells(const struct dt_device_node *parent)
439 {
440     return __dt_n_addr_cells(parent, true);
441 }
442 
dt_child_n_size_cells(const struct dt_device_node * parent)443 int dt_child_n_size_cells(const struct dt_device_node *parent)
444 {
445     return __dt_n_size_cells(parent, true);
446 }
447 
448 /*
449  * These are defined in Linux where much of this code comes from, but
450  * are currently unused outside this file in the context of Xen.
451  */
452 #define IORESOURCE_BITS         0x000000ff      /* Bus-specific bits */
453 
454 #define IORESOURCE_TYPE_BITS    0x00001f00      /* Resource type */
455 #define IORESOURCE_IO           0x00000100      /* PCI/ISA I/O ports */
456 #define IORESOURCE_MEM          0x00000200
457 #define IORESOURCE_REG          0x00000300      /* Register offsets */
458 #define IORESOURCE_IRQ          0x00000400
459 #define IORESOURCE_DMA          0x00000800
460 #define IORESOURCE_BUS          0x00001000
461 
462 #define IORESOURCE_PREFETCH     0x00002000      /* No side effects */
463 #define IORESOURCE_READONLY     0x00004000
464 #define IORESOURCE_CACHEABLE    0x00008000
465 #define IORESOURCE_RANGELENGTH  0x00010000
466 #define IORESOURCE_SHADOWABLE   0x00020000
467 
468 /*
469  * Default translator (generic bus)
470  */
dt_bus_default_match(const struct dt_device_node * node)471 static bool_t dt_bus_default_match(const struct dt_device_node *node)
472 {
473     /* Root node doesn't have "ranges" property */
474     if ( node->parent == NULL )
475         return 1;
476 
477     /* The default bus is only used when the "ranges" property exists.
478      * Otherwise we can't translate the address
479      */
480     return (dt_get_property(node, "ranges", NULL) != NULL);
481 }
482 
dt_bus_default_count_cells(const struct dt_device_node * dev,int * addrc,int * sizec)483 static void dt_bus_default_count_cells(const struct dt_device_node *dev,
484                                 int *addrc, int *sizec)
485 {
486     if ( addrc )
487         *addrc = dt_n_addr_cells(dev);
488     if ( sizec )
489         *sizec = dt_n_size_cells(dev);
490 }
491 
dt_bus_default_map(__be32 * addr,const __be32 * range,int na,int ns,int pna)492 static u64 dt_bus_default_map(__be32 *addr, const __be32 *range,
493                               int na, int ns, int pna)
494 {
495     u64 cp, s, da;
496 
497     cp = dt_read_number(range, na);
498     s = dt_read_number(range + na + pna, ns);
499     da = dt_read_number(addr, na);
500 
501     dt_dprintk("DT: default map, cp=%llx, s=%llx, da=%llx\n",
502                (unsigned long long)cp, (unsigned long long)s,
503                (unsigned long long)da);
504 
505     /*
506      * If the number of address cells is larger than 2 we assume the
507      * mapping doesn't specify a physical address. Rather, the address
508      * specifies an identifier that must match exactly.
509      */
510     if ( na > 2 && memcmp(range, addr, na * 4) != 0 )
511         return DT_BAD_ADDR;
512 
513     if ( da < cp || da >= (cp + s) )
514         return DT_BAD_ADDR;
515     return da - cp;
516 }
517 
dt_bus_default_translate(__be32 * addr,u64 offset,int na)518 static int dt_bus_default_translate(__be32 *addr, u64 offset, int na)
519 {
520     u64 a = dt_read_number(addr, na);
521 
522     memset(addr, 0, na * 4);
523     a += offset;
524     if ( na > 1 )
525         addr[na - 2] = cpu_to_be32(a >> 32);
526     addr[na - 1] = cpu_to_be32(a & 0xffffffffu);
527 
528     return 0;
529 }
dt_bus_default_get_flags(const __be32 * addr)530 static unsigned int dt_bus_default_get_flags(const __be32 *addr)
531 {
532     return IORESOURCE_MEM;
533 }
534 
535 /*
536  * PCI bus specific translator
537  */
538 
dt_bus_pci_match(const struct dt_device_node * np)539 static bool_t dt_bus_pci_match(const struct dt_device_node *np)
540 {
541     /*
542      * "pciex" is PCI Express "vci" is for the /chaos bridge on 1st-gen PCI
543      * powermacs "ht" is hypertransport
544      */
545     return !strcmp(np->type, "pci") || !strcmp(np->type, "pciex") ||
546         !strcmp(np->type, "vci") || !strcmp(np->type, "ht");
547 }
548 
dt_bus_pci_count_cells(const struct dt_device_node * np,int * addrc,int * sizec)549 static void dt_bus_pci_count_cells(const struct dt_device_node *np,
550 				   int *addrc, int *sizec)
551 {
552     if (addrc)
553         *addrc = 3;
554     if (sizec)
555         *sizec = 2;
556 }
557 
dt_bus_pci_get_flags(const __be32 * addr)558 static unsigned int dt_bus_pci_get_flags(const __be32 *addr)
559 {
560     unsigned int flags = 0;
561     u32 w = be32_to_cpup(addr);
562 
563     switch((w >> 24) & 0x03) {
564     case 0x01:
565         flags |= IORESOURCE_IO;
566         break;
567     case 0x02: /* 32 bits */
568     case 0x03: /* 64 bits */
569         flags |= IORESOURCE_MEM;
570         break;
571     }
572     if (w & 0x40000000)
573         flags |= IORESOURCE_PREFETCH;
574     return flags;
575 }
576 
dt_bus_pci_map(__be32 * addr,const __be32 * range,int na,int ns,int pna)577 static u64 dt_bus_pci_map(__be32 *addr, const __be32 *range, int na, int ns,
578 		int pna)
579 {
580     u64 cp, s, da;
581     unsigned int af, rf;
582 
583     af = dt_bus_pci_get_flags(addr);
584     rf = dt_bus_pci_get_flags(range);
585 
586     /* Check address type match */
587     if ((af ^ rf) & (IORESOURCE_MEM | IORESOURCE_IO))
588         return DT_BAD_ADDR;
589 
590     /* Read address values, skipping high cell */
591     cp = dt_read_number(range + 1, na - 1);
592     s  = dt_read_number(range + na + pna, ns);
593     da = dt_read_number(addr + 1, na - 1);
594 
595     dt_dprintk("DT: PCI map, cp=%llx, s=%llx, da=%llx\n",
596                (unsigned long long)cp, (unsigned long long)s,
597                (unsigned long long)da);
598 
599     if (da < cp || da >= (cp + s))
600         return DT_BAD_ADDR;
601     return da - cp;
602 }
603 
dt_bus_pci_translate(__be32 * addr,u64 offset,int na)604 static int dt_bus_pci_translate(__be32 *addr, u64 offset, int na)
605 {
606     return dt_bus_default_translate(addr + 1, offset, na - 1);
607 }
608 
609 /*
610  * Array of bus specific translators
611  */
612 static const struct dt_bus dt_busses[] =
613 {
614     /* PCI */
615     {
616         .name = "pci",
617         .addresses = "assigned-addresses",
618         .match = dt_bus_pci_match,
619         .count_cells = dt_bus_pci_count_cells,
620         .map = dt_bus_pci_map,
621         .translate = dt_bus_pci_translate,
622         .get_flags = dt_bus_pci_get_flags,
623     },
624     /* Default */
625     {
626         .name = "default",
627         .addresses = "reg",
628         .match = dt_bus_default_match,
629         .count_cells = dt_bus_default_count_cells,
630         .map = dt_bus_default_map,
631         .translate = dt_bus_default_translate,
632         .get_flags = dt_bus_default_get_flags,
633     },
634 };
635 
dt_match_bus(const struct dt_device_node * np)636 static const struct dt_bus *dt_match_bus(const struct dt_device_node *np)
637 {
638     int i;
639 
640     for ( i = 0; i < ARRAY_SIZE(dt_busses); i++ )
641         if ( !dt_busses[i].match || dt_busses[i].match(np) )
642             return &dt_busses[i];
643 
644     return NULL;
645 }
646 
dt_get_address(const struct dt_device_node * dev,unsigned int index,u64 * size,unsigned int * flags)647 static const __be32 *dt_get_address(const struct dt_device_node *dev,
648                                     unsigned int index, u64 *size,
649                                     unsigned int *flags)
650 {
651     const __be32 *prop;
652     u32 psize;
653     const struct dt_device_node *parent;
654     const struct dt_bus *bus;
655     int onesize, i, na, ns;
656 
657     /* Get parent & match bus type */
658     parent = dt_get_parent(dev);
659     if ( parent == NULL )
660         return NULL;
661 
662     bus = dt_match_bus(parent);
663     if ( !bus )
664         return NULL;
665     bus->count_cells(dev, &na, &ns);
666 
667     if ( !DT_CHECK_ADDR_COUNT(na) )
668         return NULL;
669 
670     /* Get "reg" or "assigned-addresses" property */
671     prop = dt_get_property(dev, bus->addresses, &psize);
672     if ( prop == NULL )
673         return NULL;
674     psize /= 4;
675 
676     onesize = na + ns;
677     for ( i = 0; psize >= onesize; psize -= onesize, prop += onesize, i++ )
678     {
679         if ( i == index )
680         {
681             if ( size )
682                 *size = dt_read_number(prop + na, ns);
683             if ( flags )
684                 *flags = bus->get_flags(prop);
685             return prop;
686         }
687     }
688     return NULL;
689 }
690 
dt_translate_one(const struct dt_device_node * parent,const struct dt_bus * bus,const struct dt_bus * pbus,__be32 * addr,int na,int ns,int pna,const char * rprop)691 static int dt_translate_one(const struct dt_device_node *parent,
692                             const struct dt_bus *bus,
693                             const struct dt_bus *pbus,
694                             __be32 *addr, int na, int ns,
695                             int pna, const char *rprop)
696 {
697     const __be32 *ranges;
698     unsigned int rlen;
699     int rone;
700     u64 offset = DT_BAD_ADDR;
701 
702     ranges = dt_get_property(parent, rprop, &rlen);
703     if ( ranges == NULL )
704     {
705         printk(XENLOG_ERR "DT: no ranges; cannot translate\n");
706         return 1;
707     }
708     if ( rlen == 0 )
709     {
710         offset = dt_read_number(addr, na);
711         memset(addr, 0, pna * 4);
712         dt_dprintk("DT: empty ranges; 1:1 translation\n");
713         goto finish;
714     }
715 
716     dt_dprintk("DT: walking ranges...\n");
717 
718     /* Now walk through the ranges */
719     rlen /= 4;
720     rone = na + pna + ns;
721     for ( ; rlen >= rone; rlen -= rone, ranges += rone )
722     {
723         offset = bus->map(addr, ranges, na, ns, pna);
724         if ( offset != DT_BAD_ADDR )
725             break;
726     }
727     if ( offset == DT_BAD_ADDR )
728     {
729         dt_dprintk("DT: not found !\n");
730         return 1;
731     }
732     memcpy(addr, ranges + na, 4 * pna);
733 
734 finish:
735     dt_dump_addr("DT: parent translation for:", addr, pna);
736     dt_dprintk("DT: with offset: %llx\n", (unsigned long long)offset);
737 
738     /* Translate it into parent bus space */
739     return pbus->translate(addr, offset, pna);
740 }
741 
742 /*
743  * Translate an address from the device-tree into a CPU physical address,
744  * this walks up the tree and applies the various bus mappings on the
745  * way.
746  *
747  * Note: We consider that crossing any level with #size-cells == 0 to mean
748  * that translation is impossible (that is we are not dealing with a value
749  * that can be mapped to a cpu physical address). This is not really specified
750  * that way, but this is traditionally the way IBM at least do things
751  */
__dt_translate_address(const struct dt_device_node * dev,const __be32 * in_addr,const char * rprop)752 static u64 __dt_translate_address(const struct dt_device_node *dev,
753                                   const __be32 *in_addr, const char *rprop)
754 {
755     const struct dt_device_node *parent = NULL;
756     const struct dt_bus *bus, *pbus;
757     __be32 addr[DT_MAX_ADDR_CELLS];
758     int na, ns, pna, pns;
759     u64 result = DT_BAD_ADDR;
760 
761     dt_dprintk("DT: ** translation for device %s **\n", dev->full_name);
762 
763     /* Get parent & match bus type */
764     parent = dt_get_parent(dev);
765     if ( parent == NULL )
766         goto bail;
767     bus = dt_match_bus(parent);
768     if ( !bus )
769         goto bail;
770 
771     /* Count address cells & copy address locally */
772     bus->count_cells(dev, &na, &ns);
773     if ( !DT_CHECK_COUNTS(na, ns) )
774     {
775         printk(XENLOG_ERR "dt_parse: Bad cell count for device %s\n",
776                   dev->full_name);
777         goto bail;
778     }
779     memcpy(addr, in_addr, na * 4);
780 
781     dt_dprintk("DT: bus is %s (na=%d, ns=%d) on %s\n",
782                bus->name, na, ns, parent->full_name);
783     dt_dump_addr("DT: translating address:", addr, na);
784 
785     /* Translate */
786     for ( ;; )
787     {
788         /* Switch to parent bus */
789         dev = parent;
790         parent = dt_get_parent(dev);
791 
792         /* If root, we have finished */
793         if ( parent == NULL )
794         {
795             dt_dprintk("DT: reached root node\n");
796             result = dt_read_number(addr, na);
797             break;
798         }
799 
800         /* Get new parent bus and counts */
801         pbus = dt_match_bus(parent);
802         if ( pbus == NULL )
803         {
804             printk("DT: %s is not a valid bus\n", parent->full_name);
805             break;
806         }
807         pbus->count_cells(dev, &pna, &pns);
808         if ( !DT_CHECK_COUNTS(pna, pns) )
809         {
810             printk(XENLOG_ERR "dt_parse: Bad cell count for parent %s\n",
811                    dev->full_name);
812             break;
813         }
814 
815         dt_dprintk("DT: parent bus is %s (na=%d, ns=%d) on %s\n",
816                    pbus->name, pna, pns, parent->full_name);
817 
818         /* Apply bus translation */
819         if ( dt_translate_one(dev, bus, pbus, addr, na, ns, pna, rprop) )
820             break;
821 
822         /* Complete the move up one level */
823         na = pna;
824         ns = pns;
825         bus = pbus;
826 
827         dt_dump_addr("DT: one level translation:", addr, na);
828     }
829 
830 bail:
831     return result;
832 }
833 
834 /* dt_device_address - Translate device tree address and return it */
dt_device_get_address(const struct dt_device_node * dev,unsigned int index,u64 * addr,u64 * size)835 int dt_device_get_address(const struct dt_device_node *dev, unsigned int index,
836                           u64 *addr, u64 *size)
837 {
838     const __be32 *addrp;
839     unsigned int flags;
840 
841     addrp = dt_get_address(dev, index, size, &flags);
842     if ( addrp == NULL )
843         return -EINVAL;
844 
845     if ( !addr )
846         return -EINVAL;
847 
848     *addr = __dt_translate_address(dev, addrp, "ranges");
849 
850     if ( *addr == DT_BAD_ADDR )
851         return -EINVAL;
852 
853     return 0;
854 }
855 
856 
dt_for_each_range(const struct dt_device_node * dev,int (* cb)(const struct dt_device_node *,u64 addr,u64 length,void *),void * data)857 int dt_for_each_range(const struct dt_device_node *dev,
858                       int (*cb)(const struct dt_device_node *,
859                                 u64 addr, u64 length,
860                                 void *),
861                       void *data)
862 {
863     const struct dt_device_node *parent = NULL;
864     const struct dt_bus *bus, *pbus;
865     const __be32 *ranges;
866     __be32 addr[DT_MAX_ADDR_CELLS];
867     unsigned int rlen;
868     int na, ns, pna, pns, rone;
869 
870     bus = dt_match_bus(dev);
871     if ( !bus )
872         return 0; /* device is not a bus */
873 
874     parent = dt_get_parent(dev);
875     if ( parent == NULL )
876         return -EINVAL;
877 
878     ranges = dt_get_property(dev, "ranges", &rlen);
879     if ( ranges == NULL )
880     {
881         printk(XENLOG_ERR "DT: no ranges; cannot enumerate %s\n",
882                dev->full_name);
883         return -EINVAL;
884     }
885     if ( rlen == 0 ) /* Nothing to do */
886         return 0;
887 
888     bus->count_cells(dev, &na, &ns);
889     if ( !DT_CHECK_COUNTS(na, ns) )
890     {
891         printk(XENLOG_ERR "dt_parse: Bad cell count for device %s\n",
892                   dev->full_name);
893         return -EINVAL;
894     }
895 
896     pbus = dt_match_bus(parent);
897     if ( pbus == NULL )
898     {
899         printk("DT: %s is not a valid bus\n", parent->full_name);
900         return -EINVAL;
901     }
902 
903     pbus->count_cells(dev, &pna, &pns);
904     if ( !DT_CHECK_COUNTS(pna, pns) )
905     {
906         printk(XENLOG_ERR "dt_parse: Bad cell count for parent %s\n",
907                dev->full_name);
908         return -EINVAL;
909     }
910 
911     /* Now walk through the ranges */
912     rlen /= 4;
913     rone = na + pna + ns;
914 
915     dt_dprintk("%s: dev=%s, bus=%s, parent=%s, rlen=%d, rone=%d\n",
916                __func__,
917                dt_node_name(dev), bus->name,
918                dt_node_name(parent), rlen, rone);
919 
920     for ( ; rlen >= rone; rlen -= rone, ranges += rone )
921     {
922         u64 a, s;
923         int ret;
924 
925         memcpy(addr, ranges + na, 4 * pna);
926 
927         a = __dt_translate_address(dev, addr, "ranges");
928         s = dt_read_number(ranges + na + pna, ns);
929 
930         ret = cb(dev, a, s, data);
931         if ( ret )
932         {
933             dt_dprintk(" -> callback failed=%d\n", ret);
934             return ret;
935         }
936 
937     }
938 
939     return 0;
940 }
941 
942 /**
943  * dt_find_node_by_phandle - Find a node given a phandle
944  * @handle: phandle of the node to find
945  *
946  * Returns a node pointer.
947  */
dt_find_node_by_phandle(dt_phandle handle)948 static struct dt_device_node *dt_find_node_by_phandle(dt_phandle handle)
949 {
950     struct dt_device_node *np;
951 
952     dt_for_each_device_node(dt_host, np)
953         if ( np->phandle == handle )
954             break;
955 
956     return np;
957 }
958 
959 /**
960  * dt_irq_find_parent - Given a device node, find its interrupt parent node
961  * @child: pointer to device node
962  *
963  * Returns a pointer to the interrupt parent node, or NULL if the interrupt
964  * parent could not be determined.
965  */
966 static const struct dt_device_node *
dt_irq_find_parent(const struct dt_device_node * child)967 dt_irq_find_parent(const struct dt_device_node *child)
968 {
969     const struct dt_device_node *p;
970     const __be32 *parp;
971 
972     do
973     {
974         parp = dt_get_property(child, "interrupt-parent", NULL);
975         if ( parp == NULL )
976             p = dt_get_parent(child);
977         else
978             p = dt_find_node_by_phandle(be32_to_cpup(parp));
979         child = p;
980     } while ( p && dt_get_property(p, "#interrupt-cells", NULL) == NULL );
981 
982     return p;
983 }
984 
dt_number_of_irq(const struct dt_device_node * device)985 unsigned int dt_number_of_irq(const struct dt_device_node *device)
986 {
987     const struct dt_device_node *p;
988     const __be32 *intspec, *tmp;
989     u32 intsize, intlen;
990 
991     dt_dprintk("dt_irq_number: dev=%s\n", device->full_name);
992 
993     /* Get the interrupts property */
994     intspec = dt_get_property(device, "interrupts", &intlen);
995     if ( intspec == NULL )
996         return 0;
997     intlen /= sizeof(*intspec);
998 
999     dt_dprintk(" intspec=%d intlen=%d\n", be32_to_cpup(intspec), intlen);
1000 
1001     /* Look for the interrupt parent. */
1002     p = dt_irq_find_parent(device);
1003     if ( p == NULL )
1004         return 0;
1005 
1006     /* Get size of interrupt specifier */
1007     tmp = dt_get_property(p, "#interrupt-cells", NULL);
1008     if ( tmp == NULL )
1009         return 0;
1010     intsize = be32_to_cpu(*tmp);
1011 
1012     dt_dprintk(" intsize=%d intlen=%d\n", intsize, intlen);
1013 
1014     return (intlen / intsize);
1015 }
1016 
dt_number_of_address(const struct dt_device_node * dev)1017 unsigned int dt_number_of_address(const struct dt_device_node *dev)
1018 {
1019     const __be32 *prop;
1020     u32 psize;
1021     const struct dt_device_node *parent;
1022     const struct dt_bus *bus;
1023     int onesize, na, ns;
1024 
1025     /* Get parent & match bus type */
1026     parent = dt_get_parent(dev);
1027     if ( parent == NULL )
1028         return 0;
1029 
1030     bus = dt_match_bus(parent);
1031     if ( !bus )
1032         return 0;
1033     bus->count_cells(dev, &na, &ns);
1034 
1035     if ( !DT_CHECK_COUNTS(na, ns) )
1036         return 0;
1037 
1038     /* Get "reg" or "assigned-addresses" property */
1039     prop = dt_get_property(dev, bus->addresses, &psize);
1040     if ( prop == NULL )
1041         return 0;
1042 
1043     psize /= 4;
1044     onesize = na + ns;
1045 
1046     return (psize / onesize);
1047 }
1048 
dt_for_each_irq_map(const struct dt_device_node * dev,int (* cb)(const struct dt_device_node *,const struct dt_irq *,void *),void * data)1049 int dt_for_each_irq_map(const struct dt_device_node *dev,
1050                         int (*cb)(const struct dt_device_node *,
1051                                   const struct dt_irq *,
1052                                   void *),
1053                         void *data)
1054 {
1055     const struct dt_device_node *ipar, *tnode, *old = NULL;
1056     const __be32 *tmp, *imap;
1057     u32 intsize = 1, addrsize, pintsize = 0, paddrsize = 0;
1058     u32 imaplen;
1059     int i, ret;
1060 
1061     struct dt_raw_irq dt_raw_irq;
1062     struct dt_irq dt_irq;
1063 
1064     dt_dprintk("%s: par=%s cb=%p data=%p\n", __func__,
1065                dev->full_name, cb, data);
1066 
1067     ipar = dev;
1068 
1069     /* First get the #interrupt-cells property of the current cursor
1070      * that tells us how to interpret the passed-in intspec. If there
1071      * is none, we are nice and just walk up the tree
1072      */
1073     do {
1074         tmp = dt_get_property(ipar, "#interrupt-cells", NULL);
1075         if ( tmp != NULL )
1076         {
1077             intsize = be32_to_cpu(*tmp);
1078             break;
1079         }
1080         tnode = ipar;
1081         ipar = dt_irq_find_parent(ipar);
1082     } while ( ipar );
1083     if ( ipar == NULL )
1084     {
1085         dt_dprintk(" -> no parent found !\n");
1086         goto fail;
1087     }
1088 
1089     dt_dprintk("%s: ipar=%s, size=%d\n", __func__, ipar->full_name, intsize);
1090 
1091     if ( intsize > DT_MAX_IRQ_SPEC )
1092     {
1093         dt_dprintk(" -> too many irq specifier cells\n");
1094         goto fail;
1095     }
1096 
1097     /* Look for this #address-cells. We have to implement the old linux
1098      * trick of looking for the parent here as some device-trees rely on it
1099      */
1100     old = ipar;
1101     do {
1102         tmp = dt_get_property(old, "#address-cells", NULL);
1103         tnode = dt_get_parent(old);
1104         old = tnode;
1105     } while ( old && tmp == NULL );
1106 
1107     old = NULL;
1108     addrsize = (tmp == NULL) ? 2 : be32_to_cpu(*tmp);
1109 
1110     dt_dprintk(" -> addrsize=%d\n", addrsize);
1111 
1112     /* Now look for an interrupt-map */
1113     imap = dt_get_property(dev, "interrupt-map", &imaplen);
1114     /* No interrupt-map found. Ignore */
1115     if ( imap == NULL )
1116     {
1117         dt_dprintk(" -> no map, ignoring\n");
1118         return 0;
1119     }
1120     imaplen /= sizeof(u32);
1121 
1122     /* Parse interrupt-map */
1123     while ( imaplen > (addrsize + intsize + 1) )
1124     {
1125         /* skip child unit address and child interrupt specifier */
1126         imap += addrsize + intsize;
1127         imaplen -= addrsize + intsize;
1128 
1129         /* Get the interrupt parent */
1130         ipar = dt_find_node_by_phandle(be32_to_cpup(imap));
1131         imap++;
1132         --imaplen;
1133 
1134         /* Check if not found */
1135         if ( ipar == NULL )
1136         {
1137             dt_dprintk(" -> imap parent not found !\n");
1138             goto fail;
1139         }
1140 
1141         dt_dprintk(" -> ipar %s\n", dt_node_name(ipar));
1142 
1143         /* Get #interrupt-cells and #address-cells of new
1144          * parent
1145          */
1146         tmp = dt_get_property(ipar, "#interrupt-cells", NULL);
1147         if ( tmp == NULL )
1148         {
1149             dt_dprintk(" -> parent lacks #interrupt-cells!\n");
1150             goto fail;
1151         }
1152         pintsize = be32_to_cpu(*tmp);
1153         tmp = dt_get_property(ipar, "#address-cells", NULL);
1154         paddrsize = (tmp == NULL) ? 0 : be32_to_cpu(*tmp);
1155 
1156         dt_dprintk(" -> pintsize=%d, paddrsize=%d\n",
1157                    pintsize, paddrsize);
1158 
1159         if ( pintsize > DT_MAX_IRQ_SPEC )
1160         {
1161             dt_dprintk(" -> too many irq specifier cells in parent\n");
1162             goto fail;
1163         }
1164 
1165         /* Check for malformed properties */
1166         if ( imaplen < (paddrsize + pintsize) )
1167             goto fail;
1168 
1169         imap += paddrsize;
1170         imaplen -= paddrsize;
1171 
1172         dt_raw_irq.controller = ipar;
1173         dt_raw_irq.size = pintsize;
1174         for ( i = 0; i < pintsize; i++ )
1175             dt_raw_irq.specifier[i] = dt_read_number(imap + i, 1);
1176 
1177         if ( dt_raw_irq.controller != dt_interrupt_controller )
1178         {
1179             /*
1180              * We don't map IRQs connected to secondary IRQ controllers as
1181              * these IRQs have no meaning to us until they connect to the
1182              * primary controller.
1183              *
1184              * Secondary IRQ controllers will at some point connect to
1185              * the primary controller (possibly via other IRQ controllers).
1186              * We map the IRQs at that last connection point.
1187              */
1188             imap += pintsize;
1189             imaplen -= pintsize;
1190             dt_dprintk(" -> Skipped IRQ for secondary IRQ controller\n");
1191             continue;
1192         }
1193 
1194         ret = dt_irq_translate(&dt_raw_irq, &dt_irq);
1195         if ( ret )
1196         {
1197             dt_dprintk(" -> failed to translate IRQ: %d\n", ret);
1198             return ret;
1199         }
1200 
1201         ret = cb(dev, &dt_irq, data);
1202         if ( ret )
1203         {
1204             dt_dprintk(" -> callback failed=%d\n", ret);
1205             return ret;
1206         }
1207 
1208         imap += pintsize;
1209         imaplen -= pintsize;
1210 
1211         dt_dprintk(" -> imaplen=%d\n", imaplen);
1212     }
1213 
1214     return 0;
1215 
1216 fail:
1217     return -EINVAL;
1218 }
1219 
1220 /**
1221  * dt_irq_map_raw - Low level interrupt tree parsing
1222  * @parent:     the device interrupt parent
1223  * @intspec:    interrupt specifier ("interrupts" property of the device)
1224  * @ointsize:   size of the passed in interrupt specifier
1225  * @addr:       address specifier (start of "reg" property of the device)
1226  * @oirq:       structure dt_raw_irq filled by this function
1227  *
1228  * Returns 0 on success and a negative number on error
1229  *
1230  * This function is a low-level interrupt tree walking function. It
1231  * can be used to do a partial walk with synthesized reg and interrupts
1232  * properties, for example when resolving PCI interrupts when no device
1233  * node exist for the parent.
1234  */
dt_irq_map_raw(const struct dt_device_node * parent,const __be32 * intspec,u32 ointsize,const __be32 * addr,struct dt_raw_irq * oirq)1235 static int dt_irq_map_raw(const struct dt_device_node *parent,
1236                           const __be32 *intspec, u32 ointsize,
1237                           const __be32 *addr,
1238                           struct dt_raw_irq *oirq)
1239 {
1240     const struct dt_device_node *ipar, *tnode, *old = NULL, *newpar = NULL;
1241     const __be32 *tmp, *imap, *imask;
1242     u32 intsize = 1, addrsize, newintsize = 0, newaddrsize = 0;
1243     u32 imaplen;
1244     int match, i;
1245 
1246     dt_dprintk("dt_irq_map_raw: par=%s,intspec=[0x%08x 0x%08x...],ointsize=%d\n",
1247                parent->full_name, be32_to_cpup(intspec),
1248                be32_to_cpup(intspec + 1), ointsize);
1249 
1250     ipar = parent;
1251 
1252     /* First get the #interrupt-cells property of the current cursor
1253      * that tells us how to interpret the passed-in intspec. If there
1254      * is none, we are nice and just walk up the tree
1255      */
1256     do {
1257         tmp = dt_get_property(ipar, "#interrupt-cells", NULL);
1258         if ( tmp != NULL )
1259         {
1260             intsize = be32_to_cpu(*tmp);
1261             break;
1262         }
1263         tnode = ipar;
1264         ipar = dt_irq_find_parent(ipar);
1265     } while ( ipar );
1266     if ( ipar == NULL )
1267     {
1268         dt_dprintk(" -> no parent found !\n");
1269         goto fail;
1270     }
1271 
1272     dt_dprintk("dt_irq_map_raw: ipar=%s, size=%d\n", ipar->full_name, intsize);
1273 
1274     if ( ointsize != intsize )
1275         return -EINVAL;
1276 
1277     /* Look for this #address-cells. We have to implement the old linux
1278      * trick of looking for the parent here as some device-trees rely on it
1279      */
1280     old = ipar;
1281     do {
1282         tmp = dt_get_property(old, "#address-cells", NULL);
1283         tnode = dt_get_parent(old);
1284         old = tnode;
1285     } while ( old && tmp == NULL );
1286 
1287     old = NULL;
1288     addrsize = (tmp == NULL) ? 2 : be32_to_cpu(*tmp);
1289 
1290     dt_dprintk(" -> addrsize=%d\n", addrsize);
1291 
1292     /* Now start the actual "proper" walk of the interrupt tree */
1293     while ( ipar != NULL )
1294     {
1295         /* Now check if cursor is an interrupt-controller and if it is
1296          * then we are done
1297          */
1298         if ( dt_get_property(ipar, "interrupt-controller", NULL) != NULL )
1299         {
1300             dt_dprintk(" -> got it !\n");
1301             if ( intsize > DT_MAX_IRQ_SPEC )
1302             {
1303                 dt_dprintk(" -> intsize(%u) greater than DT_MAX_IRQ_SPEC(%u)\n",
1304                            intsize, DT_MAX_IRQ_SPEC);
1305                 goto fail;
1306             }
1307             for ( i = 0; i < intsize; i++ )
1308                 oirq->specifier[i] = dt_read_number(intspec + i, 1);
1309             oirq->size = intsize;
1310             oirq->controller = ipar;
1311             return 0;
1312         }
1313 
1314         /* Now look for an interrupt-map */
1315         imap = dt_get_property(ipar, "interrupt-map", &imaplen);
1316         /* No interrupt map, check for an interrupt parent */
1317         if ( imap == NULL )
1318         {
1319             dt_dprintk(" -> no map, getting parent\n");
1320             newpar = dt_irq_find_parent(ipar);
1321             goto skiplevel;
1322         }
1323         imaplen /= sizeof(u32);
1324 
1325         /* Look for a mask */
1326         imask = dt_get_property(ipar, "interrupt-map-mask", NULL);
1327 
1328         /* If we were passed no "reg" property and we attempt to parse
1329          * an interrupt-map, then #address-cells must be 0.
1330          * Fail if it's not.
1331          */
1332         if ( addr == NULL && addrsize != 0 )
1333         {
1334             dt_dprintk(" -> no reg passed in when needed !\n");
1335             goto fail;
1336         }
1337 
1338         /* Parse interrupt-map */
1339         match = 0;
1340         while ( imaplen > (addrsize + intsize + 1) && !match )
1341         {
1342             /* Compare specifiers */
1343             match = 1;
1344             for ( i = 0; i < addrsize && match; ++i )
1345             {
1346                 __be32 mask = imask ? imask[i] : cpu_to_be32(0xffffffffu);
1347                 match = ((addr[i] ^ imap[i]) & mask) == 0;
1348             }
1349             for ( ; i < (addrsize + intsize) && match; ++i )
1350             {
1351                 __be32 mask = imask ? imask[i] : cpu_to_be32(0xffffffffu);
1352                 match = ((intspec[i-addrsize] ^ imap[i]) & mask) == 0;
1353             }
1354             imap += addrsize + intsize;
1355             imaplen -= addrsize + intsize;
1356 
1357             dt_dprintk(" -> match=%d (imaplen=%d)\n", match, imaplen);
1358 
1359             /* Get the interrupt parent */
1360             newpar = dt_find_node_by_phandle(be32_to_cpup(imap));
1361             imap++;
1362             --imaplen;
1363 
1364             /* Check if not found */
1365             if ( newpar == NULL )
1366             {
1367                 dt_dprintk(" -> imap parent not found !\n");
1368                 goto fail;
1369             }
1370 
1371             /* Get #interrupt-cells and #address-cells of new
1372              * parent
1373              */
1374             tmp = dt_get_property(newpar, "#interrupt-cells", NULL);
1375             if ( tmp == NULL )
1376             {
1377                 dt_dprintk(" -> parent lacks #interrupt-cells!\n");
1378                 goto fail;
1379             }
1380             newintsize = be32_to_cpu(*tmp);
1381             tmp = dt_get_property(newpar, "#address-cells", NULL);
1382             newaddrsize = (tmp == NULL) ? 0 : be32_to_cpu(*tmp);
1383 
1384             dt_dprintk(" -> newintsize=%d, newaddrsize=%d\n",
1385                        newintsize, newaddrsize);
1386 
1387             /* Check for malformed properties */
1388             if ( imaplen < (newaddrsize + newintsize) )
1389                 goto fail;
1390 
1391             imap += newaddrsize + newintsize;
1392             imaplen -= newaddrsize + newintsize;
1393 
1394             dt_dprintk(" -> imaplen=%d\n", imaplen);
1395         }
1396         if ( !match )
1397             goto fail;
1398 
1399         old = newpar;
1400         addrsize = newaddrsize;
1401         intsize = newintsize;
1402         intspec = imap - intsize;
1403         addr = intspec - addrsize;
1404 
1405     skiplevel:
1406         /* Iterate again with new parent */
1407         dt_dprintk(" -> new parent: %s\n", dt_node_full_name(newpar));
1408         ipar = newpar;
1409         newpar = NULL;
1410     }
1411 fail:
1412     return -EINVAL;
1413 }
1414 
dt_device_get_raw_irq(const struct dt_device_node * device,unsigned int index,struct dt_raw_irq * out_irq)1415 int dt_device_get_raw_irq(const struct dt_device_node *device,
1416                           unsigned int index,
1417                           struct dt_raw_irq *out_irq)
1418 {
1419     const struct dt_device_node *p;
1420     const __be32 *intspec, *tmp, *addr;
1421     u32 intsize, intlen;
1422     int res = -EINVAL;
1423 
1424     dt_dprintk("dt_device_get_raw_irq: dev=%s, index=%u\n",
1425                device->full_name, index);
1426 
1427     /* Get the interrupts property */
1428     intspec = dt_get_property(device, "interrupts", &intlen);
1429     if ( intspec == NULL )
1430         return -EINVAL;
1431     intlen /= sizeof(*intspec);
1432 
1433     dt_dprintk(" intspec=%d intlen=%d\n", be32_to_cpup(intspec), intlen);
1434 
1435     /* Get the reg property (if any) */
1436     addr = dt_get_property(device, "reg", NULL);
1437 
1438     /* Look for the interrupt parent. */
1439     p = dt_irq_find_parent(device);
1440     if ( p == NULL )
1441         return -EINVAL;
1442 
1443     /* Get size of interrupt specifier */
1444     tmp = dt_get_property(p, "#interrupt-cells", NULL);
1445     if ( tmp == NULL )
1446         goto out;
1447     intsize = be32_to_cpu(*tmp);
1448 
1449     dt_dprintk(" intsize=%d intlen=%d\n", intsize, intlen);
1450 
1451     /* Check index */
1452     if ( (index + 1) * intsize > intlen )
1453         goto out;
1454 
1455     /* Get new specifier and map it */
1456     res = dt_irq_map_raw(p, intspec + index * intsize, intsize,
1457                          addr, out_irq);
1458     if ( res )
1459         goto out;
1460 out:
1461     return res;
1462 }
1463 
dt_irq_translate(const struct dt_raw_irq * raw,struct dt_irq * out_irq)1464 int dt_irq_translate(const struct dt_raw_irq *raw,
1465                      struct dt_irq *out_irq)
1466 {
1467     ASSERT(dt_irq_xlate != NULL);
1468     ASSERT(dt_interrupt_controller != NULL);
1469 
1470     /*
1471      * TODO: Retrieve the right irq_xlate. This is only works for the primary
1472      * interrupt controller.
1473      */
1474     if ( raw->controller != dt_interrupt_controller )
1475         return -EINVAL;
1476 
1477     return dt_irq_xlate(raw->specifier, raw->size,
1478                         &out_irq->irq, &out_irq->type);
1479 }
1480 
dt_device_get_irq(const struct dt_device_node * device,unsigned int index,struct dt_irq * out_irq)1481 int dt_device_get_irq(const struct dt_device_node *device, unsigned int index,
1482                       struct dt_irq *out_irq)
1483 {
1484     struct dt_raw_irq raw;
1485     int res;
1486 
1487     res = dt_device_get_raw_irq(device, index, &raw);
1488 
1489     if ( res )
1490         return res;
1491 
1492     return dt_irq_translate(&raw, out_irq);
1493 }
1494 
dt_device_is_available(const struct dt_device_node * device)1495 bool_t dt_device_is_available(const struct dt_device_node *device)
1496 {
1497     const char *status;
1498     u32 statlen;
1499 
1500     status = dt_get_property(device, "status", &statlen);
1501     if ( status == NULL )
1502         return 1;
1503 
1504     if ( statlen > 0 )
1505     {
1506         if ( !strcmp(status, "okay") || !strcmp(status, "ok") )
1507             return 1;
1508     }
1509 
1510     return 0;
1511 }
1512 
dt_device_for_passthrough(const struct dt_device_node * device)1513 bool_t dt_device_for_passthrough(const struct dt_device_node *device)
1514 {
1515     return (dt_find_property(device, "xen,passthrough", NULL) != NULL);
1516 
1517 }
1518 
__dt_parse_phandle_with_args(const struct dt_device_node * np,const char * list_name,const char * cells_name,int cell_count,int index,struct dt_phandle_args * out_args)1519 static int __dt_parse_phandle_with_args(const struct dt_device_node *np,
1520                                         const char *list_name,
1521                                         const char *cells_name,
1522                                         int cell_count, int index,
1523                                         struct dt_phandle_args *out_args)
1524 {
1525     const __be32 *list, *list_end;
1526     int rc = 0, cur_index = 0;
1527     u32 size, count = 0;
1528     struct dt_device_node *node = NULL;
1529     dt_phandle phandle;
1530 
1531     /* Retrieve the phandle list property */
1532     list = dt_get_property(np, list_name, &size);
1533     if ( !list )
1534         return -ENOENT;
1535     list_end = list + size / sizeof(*list);
1536 
1537     /* Loop over the phandles until all the requested entry is found */
1538     while ( list < list_end )
1539     {
1540         rc = -EINVAL;
1541         count = 0;
1542 
1543         /*
1544          * If phandle is 0, then it is an empty entry with no
1545          * arguments.  Skip forward to the next entry.
1546          * */
1547         phandle = be32_to_cpup(list++);
1548         if ( phandle )
1549         {
1550             /*
1551              * Find the provider node and parse the #*-cells
1552              * property to determine the argument length.
1553              *
1554              * This is not needed if the cell count is hard-coded
1555              * (i.e. cells_name not set, but cell_count is set),
1556              * except when we're going to return the found node
1557              * below.
1558              */
1559             if ( cells_name || cur_index == index )
1560             {
1561                 node = dt_find_node_by_phandle(phandle);
1562                 if ( !node )
1563                 {
1564                     printk(XENLOG_ERR "%s: could not find phandle\n",
1565                            np->full_name);
1566                     goto err;
1567                 }
1568             }
1569 
1570             if ( cells_name )
1571             {
1572                 if ( !dt_property_read_u32(node, cells_name, &count) )
1573                 {
1574                     printk("%s: could not get %s for %s\n",
1575                            np->full_name, cells_name, node->full_name);
1576                     goto err;
1577                 }
1578             }
1579             else
1580                 count = cell_count;
1581 
1582             /*
1583              * Make sure that the arguments actually fit in the
1584              * remaining property data length
1585              */
1586             if ( list + count > list_end )
1587             {
1588                 printk(XENLOG_ERR "%s: arguments longer than property\n",
1589                        np->full_name);
1590                 goto err;
1591             }
1592         }
1593 
1594         /*
1595          * All of the error cases above bail out of the loop, so at
1596          * this point, the parsing is successful. If the requested
1597          * index matches, then fill the out_args structure and return,
1598          * or return -ENOENT for an empty entry.
1599          */
1600         rc = -ENOENT;
1601         if ( cur_index == index )
1602         {
1603             if (!phandle)
1604                 goto err;
1605 
1606             if ( out_args )
1607             {
1608                 int i;
1609 
1610                 WARN_ON(count > MAX_PHANDLE_ARGS);
1611                 if (count > MAX_PHANDLE_ARGS)
1612                     count = MAX_PHANDLE_ARGS;
1613                 out_args->np = node;
1614                 out_args->args_count = count;
1615                 for ( i = 0; i < count; i++ )
1616                     out_args->args[i] = be32_to_cpup(list++);
1617             }
1618 
1619             /* Found it! return success */
1620             return 0;
1621         }
1622 
1623         node = NULL;
1624         list += count;
1625         cur_index++;
1626     }
1627 
1628     /*
1629      * Returning result will be one of:
1630      * -ENOENT : index is for empty phandle
1631      * -EINVAL : parsing error on data
1632      * [1..n]  : Number of phandle (count mode; when index = -1)
1633      */
1634     rc = index < 0 ? cur_index : -ENOENT;
1635 err:
1636     return rc;
1637 }
1638 
dt_parse_phandle(const struct dt_device_node * np,const char * phandle_name,int index)1639 struct dt_device_node *dt_parse_phandle(const struct dt_device_node *np,
1640                                         const char *phandle_name, int index)
1641 {
1642     struct dt_phandle_args args;
1643 
1644     if (index < 0)
1645         return NULL;
1646 
1647     if (__dt_parse_phandle_with_args(np, phandle_name, NULL, 0,
1648                                      index, &args))
1649         return NULL;
1650 
1651     return args.np;
1652 }
1653 
1654 
dt_parse_phandle_with_args(const struct dt_device_node * np,const char * list_name,const char * cells_name,int index,struct dt_phandle_args * out_args)1655 int dt_parse_phandle_with_args(const struct dt_device_node *np,
1656                                const char *list_name,
1657                                const char *cells_name, int index,
1658                                struct dt_phandle_args *out_args)
1659 {
1660     if ( index < 0 )
1661         return -EINVAL;
1662     return __dt_parse_phandle_with_args(np, list_name, cells_name, 0,
1663                                         index, out_args);
1664 }
1665 
1666 /**
1667  * unflatten_dt_node - Alloc and populate a device_node from the flat tree
1668  * @fdt: The parent device tree blob
1669  * @mem: Memory chunk to use for allocating device nodes and properties
1670  * @p: pointer to node in flat tree
1671  * @dad: Parent struct device_node
1672  * @allnextpp: pointer to ->allnext from last allocated device_node
1673  * @fpsize: Size of the node path up at the current depth.
1674  */
unflatten_dt_node(const void * fdt,unsigned long mem,unsigned long * p,struct dt_device_node * dad,struct dt_device_node *** allnextpp,unsigned long fpsize)1675 static unsigned long __init unflatten_dt_node(const void *fdt,
1676                                               unsigned long mem,
1677                                               unsigned long *p,
1678                                               struct dt_device_node *dad,
1679                                               struct dt_device_node ***allnextpp,
1680                                               unsigned long fpsize)
1681 {
1682     struct dt_device_node *np;
1683     struct dt_property *pp, **prev_pp = NULL;
1684     char *pathp;
1685     u32 tag;
1686     unsigned int l, allocl;
1687     int has_name = 0;
1688     int new_format = 0;
1689 
1690     tag = be32_to_cpup((__be32 *)(*p));
1691     if ( tag != FDT_BEGIN_NODE )
1692     {
1693         printk(XENLOG_WARNING "Weird tag at start of node: %x\n", tag);
1694         return mem;
1695     }
1696     *p += 4;
1697     pathp = (char *)*p;
1698     l = allocl = strlen(pathp) + 1;
1699     *p = ROUNDUP(*p + l, 4);
1700 
1701     /* version 0x10 has a more compact unit name here instead of the full
1702      * path. we accumulate the full path size using "fpsize", we'll rebuild
1703      * it later. We detect this because the first character of the name is
1704      * not '/'.
1705      */
1706     if ( (*pathp) != '/' )
1707     {
1708         new_format = 1;
1709         if ( fpsize == 0 )
1710         {
1711             /* root node: special case. fpsize accounts for path
1712              * plus terminating zero. root node only has '/', so
1713              * fpsize should be 2, but we want to avoid the first
1714              * level nodes to have two '/' so we use fpsize 1 here
1715              */
1716             fpsize = 1;
1717             allocl = 2;
1718         }
1719         else
1720         {
1721             /* account for '/' and path size minus terminal 0
1722              * already in 'l'
1723              */
1724             fpsize += l;
1725             allocl = fpsize;
1726         }
1727     }
1728 
1729     np = unflatten_dt_alloc(&mem, sizeof(struct dt_device_node) + allocl,
1730                             __alignof__(struct dt_device_node));
1731     if ( allnextpp )
1732     {
1733         memset(np, 0, sizeof(*np));
1734         np->full_name = ((char *)np) + sizeof(struct dt_device_node);
1735         /* By default dom0 owns the device */
1736         np->used_by = 0;
1737         /* By default the device is not protected */
1738         np->is_protected = false;
1739         INIT_LIST_HEAD(&np->domain_list);
1740 
1741         if ( new_format )
1742         {
1743             char *fn = np->full_name;
1744             /* rebuild full path for new format */
1745             if ( dad && dad->parent )
1746             {
1747                 strlcpy(fn, dad->full_name, allocl);
1748 #ifdef DEBUG_DT
1749                 if ( (strlen(fn) + l + 1) != allocl )
1750                 {
1751                     dt_dprintk("%s: p: %d, l: %d, a: %d\n",
1752                                pathp, (int)strlen(fn),
1753                                l, allocl);
1754                 }
1755 #endif
1756                 fn += strlen(fn);
1757             }
1758             *(fn++) = '/';
1759             memcpy(fn, pathp, l);
1760         }
1761         else
1762             memcpy(np->full_name, pathp, l);
1763         prev_pp = &np->properties;
1764         **allnextpp = np;
1765         *allnextpp = &np->allnext;
1766         if ( dad != NULL )
1767         {
1768             np->parent = dad;
1769             /* we temporarily use the next field as `last_child'*/
1770             if ( dad->next == NULL )
1771                 dad->child = np;
1772             else
1773                 dad->next->sibling = np;
1774             dad->next = np;
1775         }
1776     }
1777     /* process properties */
1778     while ( 1 )
1779     {
1780         u32 sz, noff;
1781         const char *pname;
1782 
1783         tag = be32_to_cpup((__be32 *)(*p));
1784         if ( tag == FDT_NOP )
1785         {
1786             *p += 4;
1787             continue;
1788         }
1789         if ( tag != FDT_PROP )
1790             break;
1791         *p += 4;
1792         sz = be32_to_cpup((__be32 *)(*p));
1793         noff = be32_to_cpup((__be32 *)((*p) + 4));
1794         *p += 8;
1795         if ( fdt_version(fdt) < 0x10 )
1796             *p = ROUNDUP(*p, sz >= 8 ? 8 : 4);
1797 
1798         pname = fdt_string(fdt, noff);
1799         if ( pname == NULL )
1800         {
1801             dt_dprintk("Can't find property name in list!\n");
1802             break;
1803         }
1804         if ( strcmp(pname, "name") == 0 )
1805             has_name = 1;
1806         l = strlen(pname) + 1;
1807         pp = unflatten_dt_alloc(&mem, sizeof(struct dt_property),
1808                                 __alignof__(struct dt_property));
1809         if ( allnextpp )
1810         {
1811             /* We accept flattened tree phandles either in
1812              * ePAPR-style "phandle" properties, or the
1813              * legacy "linux,phandle" properties.  If both
1814              * appear and have different values, things
1815              * will get weird.  Don't do that. */
1816             if ( (strcmp(pname, "phandle") == 0) ||
1817                  (strcmp(pname, "linux,phandle") == 0) )
1818             {
1819                 if ( np->phandle == 0 )
1820                     np->phandle = be32_to_cpup((__be32*)*p);
1821             }
1822             /* And we process the "ibm,phandle" property
1823              * used in pSeries dynamic device tree
1824              * stuff */
1825             if ( strcmp(pname, "ibm,phandle") == 0 )
1826                 np->phandle = be32_to_cpup((__be32 *)*p);
1827             pp->name = pname;
1828             pp->length = sz;
1829             pp->value = (void *)*p;
1830             *prev_pp = pp;
1831             prev_pp = &pp->next;
1832         }
1833         *p = ROUNDUP((*p) + sz, 4);
1834     }
1835     /* with version 0x10 we may not have the name property, recreate
1836      * it here from the unit name if absent
1837      */
1838     if ( !has_name )
1839     {
1840         char *p1 = pathp, *ps = pathp, *pa = NULL;
1841         int sz;
1842 
1843         while ( *p1 )
1844         {
1845             if ( (*p1) == '@' )
1846                 pa = p1;
1847             if ( (*p1) == '/' )
1848                 ps = p1 + 1;
1849             p1++;
1850         }
1851         if ( pa < ps )
1852             pa = p1;
1853         sz = (pa - ps) + 1;
1854         pp = unflatten_dt_alloc(&mem, sizeof(struct dt_property) + sz,
1855                                 __alignof__(struct dt_property));
1856         if ( allnextpp )
1857         {
1858             pp->name = "name";
1859             pp->length = sz;
1860             pp->value = pp + 1;
1861             /*
1862              * The device tree creation code assume that the property
1863              * "name" is not a fake.
1864              * To avoid a big divergence with Linux code, only remove
1865              * property link. In this case we will lose a bit of memory
1866              */
1867 #if 0
1868             *prev_pp = pp;
1869             prev_pp = &pp->next;
1870 #endif
1871             np->name = pp->value;
1872             memcpy(pp->value, ps, sz - 1);
1873             ((char *)pp->value)[sz - 1] = 0;
1874             dt_dprintk("fixed up name for %s -> %s\n", pathp,
1875                        (char *)pp->value);
1876             /* Generic device initialization */
1877             np->dev.type = DEV_DT;
1878             np->dev.of_node = np;
1879         }
1880     }
1881     if ( allnextpp )
1882     {
1883         *prev_pp = NULL;
1884         np->name = (np->name) ? : dt_get_property(np, "name", NULL);
1885         np->type = dt_get_property(np, "device_type", NULL);
1886 
1887         if ( !np->name )
1888             np->name = "<NULL>";
1889         if ( !np->type )
1890             np->type = "<NULL>";
1891     }
1892     while ( tag == FDT_BEGIN_NODE || tag == FDT_NOP )
1893     {
1894         if ( tag == FDT_NOP )
1895             *p += 4;
1896         else
1897             mem = unflatten_dt_node(fdt, mem, p, np, allnextpp, fpsize);
1898         tag = be32_to_cpup((__be32 *)(*p));
1899     }
1900     if ( tag != FDT_END_NODE )
1901     {
1902         printk(XENLOG_WARNING "Weird tag at end of node: %x\n", tag);
1903         return mem;
1904     }
1905 
1906     *p += 4;
1907     return mem;
1908 }
1909 
1910 /**
1911  * __unflatten_device_tree - create tree of device_nodes from flat blob
1912  *
1913  * unflattens a device-tree, creating the
1914  * tree of struct device_node. It also fills the "name" and "type"
1915  * pointers of the nodes so the normal device-tree walking functions
1916  * can be used.
1917  * @fdt: The fdt to expand
1918  * @mynodes: The device_node tree created by the call
1919  */
__unflatten_device_tree(const void * fdt,struct dt_device_node ** mynodes)1920 static void __init __unflatten_device_tree(const void *fdt,
1921                                            struct dt_device_node **mynodes)
1922 {
1923     unsigned long start, mem, size;
1924     struct dt_device_node **allnextp = mynodes;
1925 
1926     dt_dprintk(" -> unflatten_device_tree()\n");
1927 
1928     dt_dprintk("Unflattening device tree:\n");
1929     dt_dprintk("magic: %#08x\n", fdt_magic(fdt));
1930     dt_dprintk("size: %#08x\n", fdt_totalsize(fdt));
1931     dt_dprintk("version: %#08x\n", fdt_version(fdt));
1932 
1933     /* First pass, scan for size */
1934     start = ((unsigned long)fdt) + fdt_off_dt_struct(fdt);
1935     size = unflatten_dt_node(fdt, 0, &start, NULL, NULL, 0);
1936     size = (size | 3) + 1;
1937 
1938     dt_dprintk("  size is %#lx allocating...\n", size);
1939 
1940     /* Allocate memory for the expanded device tree */
1941     mem = (unsigned long)_xmalloc (size + 4, __alignof__(struct dt_device_node));
1942 
1943     ((__be32 *)mem)[size / 4] = cpu_to_be32(0xdeadbeef);
1944 
1945     dt_dprintk("  unflattening %lx...\n", mem);
1946 
1947     /* Second pass, do actual unflattening */
1948     start = ((unsigned long)fdt) + fdt_off_dt_struct(fdt);
1949     unflatten_dt_node(fdt, mem, &start, NULL, &allnextp, 0);
1950     if ( be32_to_cpup((__be32 *)start) != FDT_END )
1951         printk(XENLOG_WARNING "Weird tag at end of tree: %08x\n",
1952                   *((u32 *)start));
1953     if ( be32_to_cpu(((__be32 *)mem)[size / 4]) != 0xdeadbeef )
1954         printk(XENLOG_WARNING "End of tree marker overwritten: %08x\n",
1955                   be32_to_cpu(((__be32 *)mem)[size / 4]));
1956     *allnextp = NULL;
1957 
1958     dt_dprintk(" <- unflatten_device_tree()\n");
1959 }
1960 
dt_alias_add(struct dt_alias_prop * ap,struct dt_device_node * np,int id,const char * stem,int stem_len)1961 static void dt_alias_add(struct dt_alias_prop *ap,
1962                          struct dt_device_node *np,
1963                          int id, const char *stem, int stem_len)
1964 {
1965     ap->np = np;
1966     ap->id = id;
1967     strlcpy(ap->stem, stem, stem_len + 1);
1968     list_add_tail(&ap->link, &aliases_lookup);
1969     dt_dprintk("adding DT alias:%s: stem=%s id=%d node=%s\n",
1970                ap->alias, ap->stem, ap->id, dt_node_full_name(np));
1971 }
1972 
1973 /**
1974  * dt_alias_scan - Scan all properties of 'aliases' node
1975  *
1976  * The function scans all the properties of 'aliases' node and populate
1977  * the the global lookup table with the properties.  It returns the
1978  * number of alias_prop found, or error code in error case.
1979  */
dt_alias_scan(void)1980 static void __init dt_alias_scan(void)
1981 {
1982     const struct dt_property *pp;
1983     const struct dt_device_node *aliases;
1984 
1985     aliases = dt_find_node_by_path("/aliases");
1986     if ( !aliases )
1987         return;
1988 
1989     dt_for_each_property_node( aliases, pp )
1990     {
1991         const char *start = pp->name;
1992         const char *end = start + strlen(start);
1993         struct dt_device_node *np;
1994         struct dt_alias_prop *ap;
1995         int id, len;
1996 
1997         /* Skip those we do not want to proceed */
1998         if ( !strcmp(pp->name, "name") ||
1999              !strcmp(pp->name, "phandle") ||
2000              !strcmp(pp->name, "linux,phandle") )
2001             continue;
2002 
2003         np = dt_find_node_by_path(pp->value);
2004         if ( !np )
2005             continue;
2006 
2007         /* walk the alias backwards to extract the id and work out
2008          * the 'stem' string */
2009         while ( isdigit(*(end-1)) && end > start )
2010             end--;
2011         len = end - start;
2012 
2013         id = simple_strtoll(end, NULL, 10);
2014 
2015         /* Allocate an alias_prop with enough space for the stem */
2016         ap = _xmalloc(sizeof(*ap) + len + 1, 4);
2017         if ( !ap )
2018             continue;
2019         ap->alias = start;
2020         dt_alias_add(ap, np, id, start, len);
2021     }
2022 }
2023 
2024 struct dt_device_node * __init
dt_find_interrupt_controller(const struct dt_device_match * matches)2025 dt_find_interrupt_controller(const struct dt_device_match *matches)
2026 {
2027     struct dt_device_node *np = NULL;
2028 
2029     while ( (np = dt_find_matching_node(np, matches)) )
2030     {
2031         if ( !dt_find_property(np, "interrupt-controller", NULL) )
2032             continue;
2033 
2034         if ( dt_get_parent(np) )
2035             break;
2036     }
2037 
2038     return np;
2039 }
2040 
dt_unflatten_host_device_tree(void)2041 void __init dt_unflatten_host_device_tree(void)
2042 {
2043     __unflatten_device_tree(device_tree_flattened, &dt_host);
2044     dt_alias_scan();
2045 }
2046 
2047 /*
2048  * Local variables:
2049  * mode: C
2050  * c-file-style: "BSD"
2051  * c-basic-offset: 4
2052  * indent-tabs-mode: nil
2053  * End:
2054  */
2055