0e8961dea3bca0ef72302657462f25285c15f1db
[linux-3.10.git] / arch / ppc64 / kernel / prom.c
1 /*
2  * 
3  *
4  * Procedures for interfacing to Open Firmware.
5  *
6  * Paul Mackerras       August 1996.
7  * Copyright (C) 1996 Paul Mackerras.
8  * 
9  *  Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
10  *    {engebret|bergner}@us.ibm.com 
11  *
12  *      This program is free software; you can redistribute it and/or
13  *      modify it under the terms of the GNU General Public License
14  *      as published by the Free Software Foundation; either version
15  *      2 of the License, or (at your option) any later version.
16  */
17
18 #undef DEBUG
19
20 #include <stdarg.h>
21 #include <linux/config.h>
22 #include <linux/kernel.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/threads.h>
26 #include <linux/spinlock.h>
27 #include <linux/types.h>
28 #include <linux/pci.h>
29 #include <linux/stringify.h>
30 #include <linux/delay.h>
31 #include <linux/initrd.h>
32 #include <linux/bitops.h>
33 #include <linux/module.h>
34
35 #include <asm/prom.h>
36 #include <asm/rtas.h>
37 #include <asm/lmb.h>
38 #include <asm/abs_addr.h>
39 #include <asm/page.h>
40 #include <asm/processor.h>
41 #include <asm/irq.h>
42 #include <asm/io.h>
43 #include <asm/smp.h>
44 #include <asm/system.h>
45 #include <asm/mmu.h>
46 #include <asm/pgtable.h>
47 #include <asm/pci.h>
48 #include <asm/iommu.h>
49 #include <asm/btext.h>
50 #include <asm/sections.h>
51 #include <asm/machdep.h>
52 #include <asm/pSeries_reconfig.h>
53
54 #ifdef DEBUG
55 #define DBG(fmt...) udbg_printf(fmt)
56 #else
57 #define DBG(fmt...)
58 #endif
59
60 struct pci_reg_property {
61         struct pci_address addr;
62         u32 size_hi;
63         u32 size_lo;
64 };
65
66 struct isa_reg_property {
67         u32 space;
68         u32 address;
69         u32 size;
70 };
71
72
73 typedef int interpret_func(struct device_node *, unsigned long *,
74                            int, int, int);
75
76 extern struct rtas_t rtas;
77 extern struct lmb lmb;
78 extern unsigned long klimit;
79 extern unsigned long memory_limit;
80
81 static int __initdata dt_root_addr_cells;
82 static int __initdata dt_root_size_cells;
83 static int __initdata iommu_is_off;
84 int __initdata iommu_force_on;
85 unsigned long tce_alloc_start, tce_alloc_end;
86
87 typedef u32 cell_t;
88
89 #if 0
90 static struct boot_param_header *initial_boot_params __initdata;
91 #else
92 struct boot_param_header *initial_boot_params;
93 #endif
94
95 static struct device_node *allnodes = NULL;
96
97 /* use when traversing tree through the allnext, child, sibling,
98  * or parent members of struct device_node.
99  */
100 static DEFINE_RWLOCK(devtree_lock);
101
102 /* export that to outside world */
103 struct device_node *of_chosen;
104
105 /*
106  * Wrapper for allocating memory for various data that needs to be
107  * attached to device nodes as they are processed at boot or when
108  * added to the device tree later (e.g. DLPAR).  At boot there is
109  * already a region reserved so we just increment *mem_start by size;
110  * otherwise we call kmalloc.
111  */
112 static void * prom_alloc(unsigned long size, unsigned long *mem_start)
113 {
114         unsigned long tmp;
115
116         if (!mem_start)
117                 return kmalloc(size, GFP_KERNEL);
118
119         tmp = *mem_start;
120         *mem_start += size;
121         return (void *)tmp;
122 }
123
124 /*
125  * Find the device_node with a given phandle.
126  */
127 static struct device_node * find_phandle(phandle ph)
128 {
129         struct device_node *np;
130
131         for (np = allnodes; np != 0; np = np->allnext)
132                 if (np->linux_phandle == ph)
133                         return np;
134         return NULL;
135 }
136
137 /*
138  * Find the interrupt parent of a node.
139  */
140 static struct device_node * __devinit intr_parent(struct device_node *p)
141 {
142         phandle *parp;
143
144         parp = (phandle *) get_property(p, "interrupt-parent", NULL);
145         if (parp == NULL)
146                 return p->parent;
147         return find_phandle(*parp);
148 }
149
150 /*
151  * Find out the size of each entry of the interrupts property
152  * for a node.
153  */
154 int __devinit prom_n_intr_cells(struct device_node *np)
155 {
156         struct device_node *p;
157         unsigned int *icp;
158
159         for (p = np; (p = intr_parent(p)) != NULL; ) {
160                 icp = (unsigned int *)
161                         get_property(p, "#interrupt-cells", NULL);
162                 if (icp != NULL)
163                         return *icp;
164                 if (get_property(p, "interrupt-controller", NULL) != NULL
165                     || get_property(p, "interrupt-map", NULL) != NULL) {
166                         printk("oops, node %s doesn't have #interrupt-cells\n",
167                                p->full_name);
168                         return 1;
169                 }
170         }
171 #ifdef DEBUG_IRQ
172         printk("prom_n_intr_cells failed for %s\n", np->full_name);
173 #endif
174         return 1;
175 }
176
177 /*
178  * Map an interrupt from a device up to the platform interrupt
179  * descriptor.
180  */
181 static int __devinit map_interrupt(unsigned int **irq, struct device_node **ictrler,
182                                    struct device_node *np, unsigned int *ints,
183                                    int nintrc)
184 {
185         struct device_node *p, *ipar;
186         unsigned int *imap, *imask, *ip;
187         int i, imaplen, match;
188         int newintrc = 0, newaddrc = 0;
189         unsigned int *reg;
190         int naddrc;
191
192         reg = (unsigned int *) get_property(np, "reg", NULL);
193         naddrc = prom_n_addr_cells(np);
194         p = intr_parent(np);
195         while (p != NULL) {
196                 if (get_property(p, "interrupt-controller", NULL) != NULL)
197                         /* this node is an interrupt controller, stop here */
198                         break;
199                 imap = (unsigned int *)
200                         get_property(p, "interrupt-map", &imaplen);
201                 if (imap == NULL) {
202                         p = intr_parent(p);
203                         continue;
204                 }
205                 imask = (unsigned int *)
206                         get_property(p, "interrupt-map-mask", NULL);
207                 if (imask == NULL) {
208                         printk("oops, %s has interrupt-map but no mask\n",
209                                p->full_name);
210                         return 0;
211                 }
212                 imaplen /= sizeof(unsigned int);
213                 match = 0;
214                 ipar = NULL;
215                 while (imaplen > 0 && !match) {
216                         /* check the child-interrupt field */
217                         match = 1;
218                         for (i = 0; i < naddrc && match; ++i)
219                                 match = ((reg[i] ^ imap[i]) & imask[i]) == 0;
220                         for (; i < naddrc + nintrc && match; ++i)
221                                 match = ((ints[i-naddrc] ^ imap[i]) & imask[i]) == 0;
222                         imap += naddrc + nintrc;
223                         imaplen -= naddrc + nintrc;
224                         /* grab the interrupt parent */
225                         ipar = find_phandle((phandle) *imap++);
226                         --imaplen;
227                         if (ipar == NULL) {
228                                 printk("oops, no int parent %x in map of %s\n",
229                                        imap[-1], p->full_name);
230                                 return 0;
231                         }
232                         /* find the parent's # addr and intr cells */
233                         ip = (unsigned int *)
234                                 get_property(ipar, "#interrupt-cells", NULL);
235                         if (ip == NULL) {
236                                 printk("oops, no #interrupt-cells on %s\n",
237                                        ipar->full_name);
238                                 return 0;
239                         }
240                         newintrc = *ip;
241                         ip = (unsigned int *)
242                                 get_property(ipar, "#address-cells", NULL);
243                         newaddrc = (ip == NULL)? 0: *ip;
244                         imap += newaddrc + newintrc;
245                         imaplen -= newaddrc + newintrc;
246                 }
247                 if (imaplen < 0) {
248                         printk("oops, error decoding int-map on %s, len=%d\n",
249                                p->full_name, imaplen);
250                         return 0;
251                 }
252                 if (!match) {
253 #ifdef DEBUG_IRQ
254                         printk("oops, no match in %s int-map for %s\n",
255                                p->full_name, np->full_name);
256 #endif
257                         return 0;
258                 }
259                 p = ipar;
260                 naddrc = newaddrc;
261                 nintrc = newintrc;
262                 ints = imap - nintrc;
263                 reg = ints - naddrc;
264         }
265         if (p == NULL) {
266 #ifdef DEBUG_IRQ
267                 printk("hmmm, int tree for %s doesn't have ctrler\n",
268                        np->full_name);
269 #endif
270                 return 0;
271         }
272         *irq = ints;
273         *ictrler = p;
274         return nintrc;
275 }
276
277 static int __devinit finish_node_interrupts(struct device_node *np,
278                                             unsigned long *mem_start,
279                                             int measure_only)
280 {
281         unsigned int *ints;
282         int intlen, intrcells, intrcount;
283         int i, j, n;
284         unsigned int *irq, virq;
285         struct device_node *ic;
286
287         ints = (unsigned int *) get_property(np, "interrupts", &intlen);
288         if (ints == NULL)
289                 return 0;
290         intrcells = prom_n_intr_cells(np);
291         intlen /= intrcells * sizeof(unsigned int);
292
293         np->intrs = prom_alloc(intlen * sizeof(*(np->intrs)), mem_start);
294         if (!np->intrs)
295                 return -ENOMEM;
296
297         if (measure_only)
298                 return 0;
299
300         intrcount = 0;
301         for (i = 0; i < intlen; ++i, ints += intrcells) {
302                 n = map_interrupt(&irq, &ic, np, ints, intrcells);
303                 if (n <= 0)
304                         continue;
305
306                 /* don't map IRQ numbers under a cascaded 8259 controller */
307                 if (ic && device_is_compatible(ic, "chrp,iic")) {
308                         np->intrs[intrcount].line = irq[0];
309                 } else {
310                         virq = virt_irq_create_mapping(irq[0]);
311                         if (virq == NO_IRQ) {
312                                 printk(KERN_CRIT "Could not allocate interrupt"
313                                        " number for %s\n", np->full_name);
314                                 continue;
315                         }
316                         np->intrs[intrcount].line = irq_offset_up(virq);
317                 }
318
319                 /* We offset irq numbers for the u3 MPIC by 128 in PowerMac */
320                 if (systemcfg->platform == PLATFORM_POWERMAC && ic && ic->parent) {
321                         char *name = get_property(ic->parent, "name", NULL);
322                         if (name && !strcmp(name, "u3"))
323                                 np->intrs[intrcount].line += 128;
324                         else if (!(name && !strcmp(name, "mac-io")))
325                                 /* ignore other cascaded controllers, such as
326                                    the k2-sata-root */
327                                 break;
328                 }
329                 np->intrs[intrcount].sense = 1;
330                 if (n > 1)
331                         np->intrs[intrcount].sense = irq[1];
332                 if (n > 2) {
333                         printk("hmmm, got %d intr cells for %s:", n,
334                                np->full_name);
335                         for (j = 0; j < n; ++j)
336                                 printk(" %d", irq[j]);
337                         printk("\n");
338                 }
339                 ++intrcount;
340         }
341         np->n_intrs = intrcount;
342
343         return 0;
344 }
345
346 static int __devinit interpret_pci_props(struct device_node *np,
347                                          unsigned long *mem_start,
348                                          int naddrc, int nsizec,
349                                          int measure_only)
350 {
351         struct address_range *adr;
352         struct pci_reg_property *pci_addrs;
353         int i, l, n_addrs;
354
355         pci_addrs = (struct pci_reg_property *)
356                 get_property(np, "assigned-addresses", &l);
357         if (!pci_addrs)
358                 return 0;
359
360         n_addrs = l / sizeof(*pci_addrs);
361
362         adr = prom_alloc(n_addrs * sizeof(*adr), mem_start);
363         if (!adr)
364                 return -ENOMEM;
365
366         if (measure_only)
367                 return 0;
368
369         np->addrs = adr;
370         np->n_addrs = n_addrs;
371
372         for (i = 0; i < n_addrs; i++) {
373                 adr[i].space = pci_addrs[i].addr.a_hi;
374                 adr[i].address = pci_addrs[i].addr.a_lo |
375                         ((u64)pci_addrs[i].addr.a_mid << 32);
376                 adr[i].size = pci_addrs[i].size_lo;
377         }
378
379         return 0;
380 }
381
382 static int __init interpret_dbdma_props(struct device_node *np,
383                                         unsigned long *mem_start,
384                                         int naddrc, int nsizec,
385                                         int measure_only)
386 {
387         struct reg_property32 *rp;
388         struct address_range *adr;
389         unsigned long base_address;
390         int i, l;
391         struct device_node *db;
392
393         base_address = 0;
394         if (!measure_only) {
395                 for (db = np->parent; db != NULL; db = db->parent) {
396                         if (!strcmp(db->type, "dbdma") && db->n_addrs != 0) {
397                                 base_address = db->addrs[0].address;
398                                 break;
399                         }
400                 }
401         }
402
403         rp = (struct reg_property32 *) get_property(np, "reg", &l);
404         if (rp != 0 && l >= sizeof(struct reg_property32)) {
405                 i = 0;
406                 adr = (struct address_range *) (*mem_start);
407                 while ((l -= sizeof(struct reg_property32)) >= 0) {
408                         if (!measure_only) {
409                                 adr[i].space = 2;
410                                 adr[i].address = rp[i].address + base_address;
411                                 adr[i].size = rp[i].size;
412                         }
413                         ++i;
414                 }
415                 np->addrs = adr;
416                 np->n_addrs = i;
417                 (*mem_start) += i * sizeof(struct address_range);
418         }
419
420         return 0;
421 }
422
423 static int __init interpret_macio_props(struct device_node *np,
424                                         unsigned long *mem_start,
425                                         int naddrc, int nsizec,
426                                         int measure_only)
427 {
428         struct reg_property32 *rp;
429         struct address_range *adr;
430         unsigned long base_address;
431         int i, l;
432         struct device_node *db;
433
434         base_address = 0;
435         if (!measure_only) {
436                 for (db = np->parent; db != NULL; db = db->parent) {
437                         if (!strcmp(db->type, "mac-io") && db->n_addrs != 0) {
438                                 base_address = db->addrs[0].address;
439                                 break;
440                         }
441                 }
442         }
443
444         rp = (struct reg_property32 *) get_property(np, "reg", &l);
445         if (rp != 0 && l >= sizeof(struct reg_property32)) {
446                 i = 0;
447                 adr = (struct address_range *) (*mem_start);
448                 while ((l -= sizeof(struct reg_property32)) >= 0) {
449                         if (!measure_only) {
450                                 adr[i].space = 2;
451                                 adr[i].address = rp[i].address + base_address;
452                                 adr[i].size = rp[i].size;
453                         }
454                         ++i;
455                 }
456                 np->addrs = adr;
457                 np->n_addrs = i;
458                 (*mem_start) += i * sizeof(struct address_range);
459         }
460
461         return 0;
462 }
463
464 static int __init interpret_isa_props(struct device_node *np,
465                                       unsigned long *mem_start,
466                                       int naddrc, int nsizec,
467                                       int measure_only)
468 {
469         struct isa_reg_property *rp;
470         struct address_range *adr;
471         int i, l;
472
473         rp = (struct isa_reg_property *) get_property(np, "reg", &l);
474         if (rp != 0 && l >= sizeof(struct isa_reg_property)) {
475                 i = 0;
476                 adr = (struct address_range *) (*mem_start);
477                 while ((l -= sizeof(struct isa_reg_property)) >= 0) {
478                         if (!measure_only) {
479                                 adr[i].space = rp[i].space;
480                                 adr[i].address = rp[i].address;
481                                 adr[i].size = rp[i].size;
482                         }
483                         ++i;
484                 }
485                 np->addrs = adr;
486                 np->n_addrs = i;
487                 (*mem_start) += i * sizeof(struct address_range);
488         }
489
490         return 0;
491 }
492
493 static int __init interpret_root_props(struct device_node *np,
494                                        unsigned long *mem_start,
495                                        int naddrc, int nsizec,
496                                        int measure_only)
497 {
498         struct address_range *adr;
499         int i, l;
500         unsigned int *rp;
501         int rpsize = (naddrc + nsizec) * sizeof(unsigned int);
502
503         rp = (unsigned int *) get_property(np, "reg", &l);
504         if (rp != 0 && l >= rpsize) {
505                 i = 0;
506                 adr = (struct address_range *) (*mem_start);
507                 while ((l -= rpsize) >= 0) {
508                         if (!measure_only) {
509                                 adr[i].space = 0;
510                                 adr[i].address = rp[naddrc - 1];
511                                 adr[i].size = rp[naddrc + nsizec - 1];
512                         }
513                         ++i;
514                         rp += naddrc + nsizec;
515                 }
516                 np->addrs = adr;
517                 np->n_addrs = i;
518                 (*mem_start) += i * sizeof(struct address_range);
519         }
520
521         return 0;
522 }
523
524 static int __devinit finish_node(struct device_node *np,
525                                  unsigned long *mem_start,
526                                  interpret_func *ifunc,
527                                  int naddrc, int nsizec,
528                                  int measure_only)
529 {
530         struct device_node *child;
531         int *ip, rc = 0;
532
533         /* get the device addresses and interrupts */
534         if (ifunc != NULL)
535                 rc = ifunc(np, mem_start, naddrc, nsizec, measure_only);
536         if (rc)
537                 goto out;
538
539         rc = finish_node_interrupts(np, mem_start, measure_only);
540         if (rc)
541                 goto out;
542
543         /* Look for #address-cells and #size-cells properties. */
544         ip = (int *) get_property(np, "#address-cells", NULL);
545         if (ip != NULL)
546                 naddrc = *ip;
547         ip = (int *) get_property(np, "#size-cells", NULL);
548         if (ip != NULL)
549                 nsizec = *ip;
550
551         if (!strcmp(np->name, "device-tree") || np->parent == NULL)
552                 ifunc = interpret_root_props;
553         else if (np->type == 0)
554                 ifunc = NULL;
555         else if (!strcmp(np->type, "pci") || !strcmp(np->type, "vci"))
556                 ifunc = interpret_pci_props;
557         else if (!strcmp(np->type, "dbdma"))
558                 ifunc = interpret_dbdma_props;
559         else if (!strcmp(np->type, "mac-io") || ifunc == interpret_macio_props)
560                 ifunc = interpret_macio_props;
561         else if (!strcmp(np->type, "isa"))
562                 ifunc = interpret_isa_props;
563         else if (!strcmp(np->name, "uni-n") || !strcmp(np->name, "u3"))
564                 ifunc = interpret_root_props;
565         else if (!((ifunc == interpret_dbdma_props
566                     || ifunc == interpret_macio_props)
567                    && (!strcmp(np->type, "escc")
568                        || !strcmp(np->type, "media-bay"))))
569                 ifunc = NULL;
570
571         for (child = np->child; child != NULL; child = child->sibling) {
572                 rc = finish_node(child, mem_start, ifunc,
573                                  naddrc, nsizec, measure_only);
574                 if (rc)
575                         goto out;
576         }
577 out:
578         return rc;
579 }
580
581 /**
582  * finish_device_tree is called once things are running normally
583  * (i.e. with text and data mapped to the address they were linked at).
584  * It traverses the device tree and fills in some of the additional,
585  * fields in each node like {n_}addrs and {n_}intrs, the virt interrupt
586  * mapping is also initialized at this point.
587  */
588 void __init finish_device_tree(void)
589 {
590         unsigned long start, end, size = 0;
591
592         DBG(" -> finish_device_tree\n");
593
594         if (ppc64_interrupt_controller == IC_INVALID) {
595                 DBG("failed to configure interrupt controller type\n");
596                 panic("failed to configure interrupt controller type\n");
597         }
598         
599         /* Initialize virtual IRQ map */
600         virt_irq_init();
601
602         /*
603          * Finish device-tree (pre-parsing some properties etc...)
604          * We do this in 2 passes. One with "measure_only" set, which
605          * will only measure the amount of memory needed, then we can
606          * allocate that memory, and call finish_node again. However,
607          * we must be careful as most routines will fail nowadays when
608          * prom_alloc() returns 0, so we must make sure our first pass
609          * doesn't start at 0. We pre-initialize size to 16 for that
610          * reason and then remove those additional 16 bytes
611          */
612         size = 16;
613         finish_node(allnodes, &size, NULL, 0, 0, 1);
614         size -= 16;
615         end = start = (unsigned long)abs_to_virt(lmb_alloc(size, 128));
616         finish_node(allnodes, &end, NULL, 0, 0, 0);
617         BUG_ON(end != start + size);
618
619         DBG(" <- finish_device_tree\n");
620 }
621
622 #ifdef DEBUG
623 #define printk udbg_printf
624 #endif
625
626 static inline char *find_flat_dt_string(u32 offset)
627 {
628         return ((char *)initial_boot_params) +
629                 initial_boot_params->off_dt_strings + offset;
630 }
631
632 /**
633  * This function is used to scan the flattened device-tree, it is
634  * used to extract the memory informations at boot before we can
635  * unflatten the tree
636  */
637 int __init of_scan_flat_dt(int (*it)(unsigned long node,
638                                      const char *uname, int depth,
639                                      void *data),
640                            void *data)
641 {
642         unsigned long p = ((unsigned long)initial_boot_params) +
643                 initial_boot_params->off_dt_struct;
644         int rc = 0;
645         int depth = -1;
646
647         do {
648                 u32 tag = *((u32 *)p);
649                 char *pathp;
650                 
651                 p += 4;
652                 if (tag == OF_DT_END_NODE) {
653                         depth --;
654                         continue;
655                 }
656                 if (tag == OF_DT_NOP)
657                         continue;
658                 if (tag == OF_DT_END)
659                         break;
660                 if (tag == OF_DT_PROP) {
661                         u32 sz = *((u32 *)p);
662                         p += 8;
663                         if (initial_boot_params->version < 0x10)
664                                 p = _ALIGN(p, sz >= 8 ? 8 : 4);
665                         p += sz;
666                         p = _ALIGN(p, 4);
667                         continue;
668                 }
669                 if (tag != OF_DT_BEGIN_NODE) {
670                         printk(KERN_WARNING "Invalid tag %x scanning flattened"
671                                " device tree !\n", tag);
672                         return -EINVAL;
673                 }
674                 depth++;
675                 pathp = (char *)p;
676                 p = _ALIGN(p + strlen(pathp) + 1, 4);
677                 if ((*pathp) == '/') {
678                         char *lp, *np;
679                         for (lp = NULL, np = pathp; *np; np++)
680                                 if ((*np) == '/')
681                                         lp = np+1;
682                         if (lp != NULL)
683                                 pathp = lp;
684                 }
685                 rc = it(p, pathp, depth, data);
686                 if (rc != 0)
687                         break;          
688         } while(1);
689
690         return rc;
691 }
692
693 /**
694  * This  function can be used within scan_flattened_dt callback to get
695  * access to properties
696  */
697 void* __init of_get_flat_dt_prop(unsigned long node, const char *name,
698                                  unsigned long *size)
699 {
700         unsigned long p = node;
701
702         do {
703                 u32 tag = *((u32 *)p);
704                 u32 sz, noff;
705                 const char *nstr;
706
707                 p += 4;
708                 if (tag == OF_DT_NOP)
709                         continue;
710                 if (tag != OF_DT_PROP)
711                         return NULL;
712
713                 sz = *((u32 *)p);
714                 noff = *((u32 *)(p + 4));
715                 p += 8;
716                 if (initial_boot_params->version < 0x10)
717                         p = _ALIGN(p, sz >= 8 ? 8 : 4);
718
719                 nstr = find_flat_dt_string(noff);
720                 if (nstr == NULL) {
721                         printk(KERN_WARNING "Can't find property index"
722                                " name !\n");
723                         return NULL;
724                 }
725                 if (strcmp(name, nstr) == 0) {
726                         if (size)
727                                 *size = sz;
728                         return (void *)p;
729                 }
730                 p += sz;
731                 p = _ALIGN(p, 4);
732         } while(1);
733 }
734
735 static void *__init unflatten_dt_alloc(unsigned long *mem, unsigned long size,
736                                        unsigned long align)
737 {
738         void *res;
739
740         *mem = _ALIGN(*mem, align);
741         res = (void *)*mem;
742         *mem += size;
743
744         return res;
745 }
746
747 static unsigned long __init unflatten_dt_node(unsigned long mem,
748                                               unsigned long *p,
749                                               struct device_node *dad,
750                                               struct device_node ***allnextpp,
751                                               unsigned long fpsize)
752 {
753         struct device_node *np;
754         struct property *pp, **prev_pp = NULL;
755         char *pathp;
756         u32 tag;
757         unsigned int l, allocl;
758         int has_name = 0;
759         int new_format = 0;
760
761         tag = *((u32 *)(*p));
762         if (tag != OF_DT_BEGIN_NODE) {
763                 printk("Weird tag at start of node: %x\n", tag);
764                 return mem;
765         }
766         *p += 4;
767         pathp = (char *)*p;
768         l = allocl = strlen(pathp) + 1;
769         *p = _ALIGN(*p + l, 4);
770
771         /* version 0x10 has a more compact unit name here instead of the full
772          * path. we accumulate the full path size using "fpsize", we'll rebuild
773          * it later. We detect this because the first character of the name is
774          * not '/'.
775          */
776         if ((*pathp) != '/') {
777                 new_format = 1;
778                 if (fpsize == 0) {
779                         /* root node: special case. fpsize accounts for path
780                          * plus terminating zero. root node only has '/', so
781                          * fpsize should be 2, but we want to avoid the first
782                          * level nodes to have two '/' so we use fpsize 1 here
783                          */
784                         fpsize = 1;
785                         allocl = 2;
786                 } else {
787                         /* account for '/' and path size minus terminal 0
788                          * already in 'l'
789                          */
790                         fpsize += l;
791                         allocl = fpsize;
792                 }
793         }
794
795
796         np = unflatten_dt_alloc(&mem, sizeof(struct device_node) + allocl,
797                                 __alignof__(struct device_node));
798         if (allnextpp) {
799                 memset(np, 0, sizeof(*np));
800                 np->full_name = ((char*)np) + sizeof(struct device_node);
801                 if (new_format) {
802                         char *p = np->full_name;
803                         /* rebuild full path for new format */
804                         if (dad && dad->parent) {
805                                 strcpy(p, dad->full_name);
806 #ifdef DEBUG
807                                 if ((strlen(p) + l + 1) != allocl) {
808                                         DBG("%s: p: %d, l: %d, a: %d\n",
809                                             pathp, strlen(p), l, allocl);
810                                 }
811 #endif
812                                 p += strlen(p);
813                         }
814                         *(p++) = '/';
815                         memcpy(p, pathp, l);
816                 } else
817                         memcpy(np->full_name, pathp, l);
818                 prev_pp = &np->properties;
819                 **allnextpp = np;
820                 *allnextpp = &np->allnext;
821                 if (dad != NULL) {
822                         np->parent = dad;
823                         /* we temporarily use the next field as `last_child'*/
824                         if (dad->next == 0)
825                                 dad->child = np;
826                         else
827                                 dad->next->sibling = np;
828                         dad->next = np;
829                 }
830                 kref_init(&np->kref);
831         }
832         while(1) {
833                 u32 sz, noff;
834                 char *pname;
835
836                 tag = *((u32 *)(*p));
837                 if (tag == OF_DT_NOP) {
838                         *p += 4;
839                         continue;
840                 }
841                 if (tag != OF_DT_PROP)
842                         break;
843                 *p += 4;
844                 sz = *((u32 *)(*p));
845                 noff = *((u32 *)((*p) + 4));
846                 *p += 8;
847                 if (initial_boot_params->version < 0x10)
848                         *p = _ALIGN(*p, sz >= 8 ? 8 : 4);
849
850                 pname = find_flat_dt_string(noff);
851                 if (pname == NULL) {
852                         printk("Can't find property name in list !\n");
853                         break;
854                 }
855                 if (strcmp(pname, "name") == 0)
856                         has_name = 1;
857                 l = strlen(pname) + 1;
858                 pp = unflatten_dt_alloc(&mem, sizeof(struct property),
859                                         __alignof__(struct property));
860                 if (allnextpp) {
861                         if (strcmp(pname, "linux,phandle") == 0) {
862                                 np->node = *((u32 *)*p);
863                                 if (np->linux_phandle == 0)
864                                         np->linux_phandle = np->node;
865                         }
866                         if (strcmp(pname, "ibm,phandle") == 0)
867                                 np->linux_phandle = *((u32 *)*p);
868                         pp->name = pname;
869                         pp->length = sz;
870                         pp->value = (void *)*p;
871                         *prev_pp = pp;
872                         prev_pp = &pp->next;
873                 }
874                 *p = _ALIGN((*p) + sz, 4);
875         }
876         /* with version 0x10 we may not have the name property, recreate
877          * it here from the unit name if absent
878          */
879         if (!has_name) {
880                 char *p = pathp, *ps = pathp, *pa = NULL;
881                 int sz;
882
883                 while (*p) {
884                         if ((*p) == '@')
885                                 pa = p;
886                         if ((*p) == '/')
887                                 ps = p + 1;
888                         p++;
889                 }
890                 if (pa < ps)
891                         pa = p;
892                 sz = (pa - ps) + 1;
893                 pp = unflatten_dt_alloc(&mem, sizeof(struct property) + sz,
894                                         __alignof__(struct property));
895                 if (allnextpp) {
896                         pp->name = "name";
897                         pp->length = sz;
898                         pp->value = (unsigned char *)(pp + 1);
899                         *prev_pp = pp;
900                         prev_pp = &pp->next;
901                         memcpy(pp->value, ps, sz - 1);
902                         ((char *)pp->value)[sz - 1] = 0;
903                         DBG("fixed up name for %s -> %s\n", pathp, pp->value);
904                 }
905         }
906         if (allnextpp) {
907                 *prev_pp = NULL;
908                 np->name = get_property(np, "name", NULL);
909                 np->type = get_property(np, "device_type", NULL);
910
911                 if (!np->name)
912                         np->name = "<NULL>";
913                 if (!np->type)
914                         np->type = "<NULL>";
915         }
916         while (tag == OF_DT_BEGIN_NODE) {
917                 mem = unflatten_dt_node(mem, p, np, allnextpp, fpsize);
918                 tag = *((u32 *)(*p));
919         }
920         if (tag != OF_DT_END_NODE) {
921                 printk("Weird tag at end of node: %x\n", tag);
922                 return mem;
923         }
924         *p += 4;
925         return mem;
926 }
927
928
929 /**
930  * unflattens the device-tree passed by the firmware, creating the
931  * tree of struct device_node. It also fills the "name" and "type"
932  * pointers of the nodes so the normal device-tree walking functions
933  * can be used (this used to be done by finish_device_tree)
934  */
935 void __init unflatten_device_tree(void)
936 {
937         unsigned long start, mem, size;
938         struct device_node **allnextp = &allnodes;
939         char *p = NULL;
940         int l = 0;
941
942         DBG(" -> unflatten_device_tree()\n");
943
944         /* First pass, scan for size */
945         start = ((unsigned long)initial_boot_params) +
946                 initial_boot_params->off_dt_struct;
947         size = unflatten_dt_node(0, &start, NULL, NULL, 0);
948         size = (size | 3) + 1;
949
950         DBG("  size is %lx, allocating...\n", size);
951
952         /* Allocate memory for the expanded device tree */
953         mem = lmb_alloc(size + 4, __alignof__(struct device_node));
954         if (!mem) {
955                 DBG("Couldn't allocate memory with lmb_alloc()!\n");
956                 panic("Couldn't allocate memory with lmb_alloc()!\n");
957         }
958         mem = (unsigned long)abs_to_virt(mem);
959
960         ((u32 *)mem)[size / 4] = 0xdeadbeef;
961
962         DBG("  unflattening...\n", mem);
963
964         /* Second pass, do actual unflattening */
965         start = ((unsigned long)initial_boot_params) +
966                 initial_boot_params->off_dt_struct;
967         unflatten_dt_node(mem, &start, NULL, &allnextp, 0);
968         if (*((u32 *)start) != OF_DT_END)
969                 printk(KERN_WARNING "Weird tag at end of tree: %08x\n", *((u32 *)start));
970         if (((u32 *)mem)[size / 4] != 0xdeadbeef)
971                 printk(KERN_WARNING "End of tree marker overwritten: %08x\n",
972                        ((u32 *)mem)[size / 4] );
973         *allnextp = NULL;
974
975         /* Get pointer to OF "/chosen" node for use everywhere */
976         of_chosen = of_find_node_by_path("/chosen");
977
978         /* Retreive command line */
979         if (of_chosen != NULL) {
980                 p = (char *)get_property(of_chosen, "bootargs", &l);
981                 if (p != NULL && l > 0)
982                         strlcpy(cmd_line, p, min(l, COMMAND_LINE_SIZE));
983         }
984 #ifdef CONFIG_CMDLINE
985         if (l == 0 || (l == 1 && (*p) == 0))
986                 strlcpy(cmd_line, CONFIG_CMDLINE, COMMAND_LINE_SIZE);
987 #endif /* CONFIG_CMDLINE */
988
989         DBG("Command line is: %s\n", cmd_line);
990
991         DBG(" <- unflatten_device_tree()\n");
992 }
993
994
995 static int __init early_init_dt_scan_cpus(unsigned long node,
996                                           const char *uname, int depth, void *data)
997 {
998         char *type = of_get_flat_dt_prop(node, "device_type", NULL);
999         u32 *prop;
1000         unsigned long size;
1001
1002         /* We are scanning "cpu" nodes only */
1003         if (type == NULL || strcmp(type, "cpu") != 0)
1004                 return 0;
1005
1006         if (initial_boot_params && initial_boot_params->version >= 2) {
1007                 /* version 2 of the kexec param format adds the phys cpuid
1008                  * of booted proc.
1009                  */
1010                 boot_cpuid_phys = initial_boot_params->boot_cpuid_phys;
1011                 boot_cpuid = 0;
1012         } else {
1013                 /* Check if it's the boot-cpu, set it's hw index in paca now */
1014                 if (of_get_flat_dt_prop(node, "linux,boot-cpu", NULL)
1015                     != NULL) {
1016                         u32 *prop = of_get_flat_dt_prop(node, "reg", NULL);
1017                         set_hard_smp_processor_id(0, prop == NULL ? 0 : *prop);
1018                         boot_cpuid_phys = get_hard_smp_processor_id(0);
1019                 }
1020         }
1021
1022 #ifdef CONFIG_ALTIVEC
1023         /* Check if we have a VMX and eventually update CPU features */
1024         prop = (u32 *)of_get_flat_dt_prop(node, "ibm,vmx", NULL);
1025         if (prop && (*prop) > 0) {
1026                 cur_cpu_spec->cpu_features |= CPU_FTR_ALTIVEC;
1027                 cur_cpu_spec->cpu_user_features |= PPC_FEATURE_HAS_ALTIVEC;
1028         }
1029
1030         /* Same goes for Apple's "altivec" property */
1031         prop = (u32 *)of_get_flat_dt_prop(node, "altivec", NULL);
1032         if (prop) {
1033                 cur_cpu_spec->cpu_features |= CPU_FTR_ALTIVEC;
1034                 cur_cpu_spec->cpu_user_features |= PPC_FEATURE_HAS_ALTIVEC;
1035         }
1036 #endif /* CONFIG_ALTIVEC */
1037
1038         /*
1039          * Check for an SMT capable CPU and set the CPU feature. We do
1040          * this by looking at the size of the ibm,ppc-interrupt-server#s
1041          * property
1042          */
1043         prop = (u32 *)of_get_flat_dt_prop(node, "ibm,ppc-interrupt-server#s",
1044                                        &size);
1045         cur_cpu_spec->cpu_features &= ~CPU_FTR_SMT;
1046         if (prop && ((size / sizeof(u32)) > 1))
1047                 cur_cpu_spec->cpu_features |= CPU_FTR_SMT;
1048
1049         return 0;
1050 }
1051
1052 static int __init early_init_dt_scan_chosen(unsigned long node,
1053                                             const char *uname, int depth, void *data)
1054 {
1055         u32 *prop;
1056         u64 *prop64;
1057
1058         DBG("search \"chosen\", depth: %d, uname: %s\n", depth, uname);
1059
1060         if (depth != 1 || strcmp(uname, "chosen") != 0)
1061                 return 0;
1062
1063         /* get platform type */
1064         prop = (u32 *)of_get_flat_dt_prop(node, "linux,platform", NULL);
1065         if (prop == NULL)
1066                 return 0;
1067         systemcfg->platform = *prop;
1068
1069         /* check if iommu is forced on or off */
1070         if (of_get_flat_dt_prop(node, "linux,iommu-off", NULL) != NULL)
1071                 iommu_is_off = 1;
1072         if (of_get_flat_dt_prop(node, "linux,iommu-force-on", NULL) != NULL)
1073                 iommu_force_on = 1;
1074
1075         prop64 = (u64*)of_get_flat_dt_prop(node, "linux,memory-limit", NULL);
1076         if (prop64)
1077                 memory_limit = *prop64;
1078
1079         prop64 = (u64*)of_get_flat_dt_prop(node, "linux,tce-alloc-start",NULL);
1080         if (prop64)
1081                 tce_alloc_start = *prop64;
1082
1083         prop64 = (u64*)of_get_flat_dt_prop(node, "linux,tce-alloc-end", NULL);
1084         if (prop64)
1085                 tce_alloc_end = *prop64;
1086
1087 #ifdef CONFIG_PPC_RTAS
1088         /* To help early debugging via the front panel, we retreive a minimal
1089          * set of RTAS infos now if available
1090          */
1091         {
1092                 u64 *basep, *entryp;
1093
1094                 basep = (u64*)of_get_flat_dt_prop(node,
1095                                                   "linux,rtas-base", NULL);
1096                 entryp = (u64*)of_get_flat_dt_prop(node,
1097                                                    "linux,rtas-entry", NULL);
1098                 prop = (u32*)of_get_flat_dt_prop(node,
1099                                                  "linux,rtas-size", NULL);
1100                 if (basep && entryp && prop) {
1101                         rtas.base = *basep;
1102                         rtas.entry = *entryp;
1103                         rtas.size = *prop;
1104                 }
1105         }
1106 #endif /* CONFIG_PPC_RTAS */
1107
1108         /* break now */
1109         return 1;
1110 }
1111
1112 static int __init early_init_dt_scan_root(unsigned long node,
1113                                           const char *uname, int depth, void *data)
1114 {
1115         u32 *prop;
1116
1117         if (depth != 0)
1118                 return 0;
1119
1120         prop = (u32 *)of_get_flat_dt_prop(node, "#size-cells", NULL);
1121         dt_root_size_cells = (prop == NULL) ? 1 : *prop;
1122         DBG("dt_root_size_cells = %x\n", dt_root_size_cells);
1123
1124         prop = (u32 *)of_get_flat_dt_prop(node, "#address-cells", NULL);
1125         dt_root_addr_cells = (prop == NULL) ? 2 : *prop;
1126         DBG("dt_root_addr_cells = %x\n", dt_root_addr_cells);
1127         
1128         /* break now */
1129         return 1;
1130 }
1131
1132 static unsigned long __init dt_mem_next_cell(int s, cell_t **cellp)
1133 {
1134         cell_t *p = *cellp;
1135         unsigned long r = 0;
1136
1137         /* Ignore more than 2 cells */
1138         while (s > 2) {
1139                 p++;
1140                 s--;
1141         }
1142         while (s) {
1143                 r <<= 32;
1144                 r |= *(p++);
1145                 s--;
1146         }
1147
1148         *cellp = p;
1149         return r;
1150 }
1151
1152
1153 static int __init early_init_dt_scan_memory(unsigned long node,
1154                                             const char *uname, int depth, void *data)
1155 {
1156         char *type = of_get_flat_dt_prop(node, "device_type", NULL);
1157         cell_t *reg, *endp;
1158         unsigned long l;
1159
1160         /* We are scanning "memory" nodes only */
1161         if (type == NULL || strcmp(type, "memory") != 0)
1162                 return 0;
1163
1164         reg = (cell_t *)of_get_flat_dt_prop(node, "reg", &l);
1165         if (reg == NULL)
1166                 return 0;
1167
1168         endp = reg + (l / sizeof(cell_t));
1169
1170         DBG("memory scan node %s ..., reg size %ld, data: %x %x %x %x, ...\n",
1171             uname, l, reg[0], reg[1], reg[2], reg[3]);
1172
1173         while ((endp - reg) >= (dt_root_addr_cells + dt_root_size_cells)) {
1174                 unsigned long base, size;
1175
1176                 base = dt_mem_next_cell(dt_root_addr_cells, &reg);
1177                 size = dt_mem_next_cell(dt_root_size_cells, &reg);
1178
1179                 if (size == 0)
1180                         continue;
1181                 DBG(" - %lx ,  %lx\n", base, size);
1182                 if (iommu_is_off) {
1183                         if (base >= 0x80000000ul)
1184                                 continue;
1185                         if ((base + size) > 0x80000000ul)
1186                                 size = 0x80000000ul - base;
1187                 }
1188                 lmb_add(base, size);
1189         }
1190         return 0;
1191 }
1192
1193 static void __init early_reserve_mem(void)
1194 {
1195         u64 base, size;
1196         u64 *reserve_map = (u64 *)(((unsigned long)initial_boot_params) +
1197                                    initial_boot_params->off_mem_rsvmap);
1198         while (1) {
1199                 base = *(reserve_map++);
1200                 size = *(reserve_map++);
1201                 if (size == 0)
1202                         break;
1203                 DBG("reserving: %lx -> %lx\n", base, size);
1204                 lmb_reserve(base, size);
1205         }
1206
1207 #if 0
1208         DBG("memory reserved, lmbs :\n");
1209         lmb_dump_all();
1210 #endif
1211 }
1212
1213 void __init early_init_devtree(void *params)
1214 {
1215         DBG(" -> early_init_devtree()\n");
1216
1217         /* Setup flat device-tree pointer */
1218         initial_boot_params = params;
1219
1220         /* Retreive various informations from the /chosen node of the
1221          * device-tree, including the platform type, initrd location and
1222          * size, TCE reserve, and more ...
1223          */
1224         of_scan_flat_dt(early_init_dt_scan_chosen, NULL);
1225
1226         /* Scan memory nodes and rebuild LMBs */
1227         lmb_init();
1228         of_scan_flat_dt(early_init_dt_scan_root, NULL);
1229         of_scan_flat_dt(early_init_dt_scan_memory, NULL);
1230         lmb_enforce_memory_limit(memory_limit);
1231         lmb_analyze();
1232         systemcfg->physicalMemorySize = lmb_phys_mem_size();
1233         lmb_reserve(0, __pa(klimit));
1234
1235         DBG("Phys. mem: %lx\n", systemcfg->physicalMemorySize);
1236
1237         /* Reserve LMB regions used by kernel, initrd, dt, etc... */
1238         early_reserve_mem();
1239
1240         DBG("Scanning CPUs ...\n");
1241
1242         /* Retreive hash table size from flattened tree plus other
1243          * CPU related informations (altivec support, boot CPU ID, ...)
1244          */
1245         of_scan_flat_dt(early_init_dt_scan_cpus, NULL);
1246
1247         DBG(" <- early_init_devtree()\n");
1248 }
1249
1250 #undef printk
1251
1252 int
1253 prom_n_addr_cells(struct device_node* np)
1254 {
1255         int* ip;
1256         do {
1257                 if (np->parent)
1258                         np = np->parent;
1259                 ip = (int *) get_property(np, "#address-cells", NULL);
1260                 if (ip != NULL)
1261                         return *ip;
1262         } while (np->parent);
1263         /* No #address-cells property for the root node, default to 1 */
1264         return 1;
1265 }
1266
1267 int
1268 prom_n_size_cells(struct device_node* np)
1269 {
1270         int* ip;
1271         do {
1272                 if (np->parent)
1273                         np = np->parent;
1274                 ip = (int *) get_property(np, "#size-cells", NULL);
1275                 if (ip != NULL)
1276                         return *ip;
1277         } while (np->parent);
1278         /* No #size-cells property for the root node, default to 1 */
1279         return 1;
1280 }
1281
1282 /**
1283  * Work out the sense (active-low level / active-high edge)
1284  * of each interrupt from the device tree.
1285  */
1286 void __init prom_get_irq_senses(unsigned char *senses, int off, int max)
1287 {
1288         struct device_node *np;
1289         int i, j;
1290
1291         /* default to level-triggered */
1292         memset(senses, 1, max - off);
1293
1294         for (np = allnodes; np != 0; np = np->allnext) {
1295                 for (j = 0; j < np->n_intrs; j++) {
1296                         i = np->intrs[j].line;
1297                         if (i >= off && i < max)
1298                                 senses[i-off] = np->intrs[j].sense ?
1299                                         IRQ_SENSE_LEVEL | IRQ_POLARITY_NEGATIVE :
1300                                         IRQ_SENSE_EDGE | IRQ_POLARITY_POSITIVE;
1301                 }
1302         }
1303 }
1304
1305 /**
1306  * Construct and return a list of the device_nodes with a given name.
1307  */
1308 struct device_node *
1309 find_devices(const char *name)
1310 {
1311         struct device_node *head, **prevp, *np;
1312
1313         prevp = &head;
1314         for (np = allnodes; np != 0; np = np->allnext) {
1315                 if (np->name != 0 && strcasecmp(np->name, name) == 0) {
1316                         *prevp = np;
1317                         prevp = &np->next;
1318                 }
1319         }
1320         *prevp = NULL;
1321         return head;
1322 }
1323 EXPORT_SYMBOL(find_devices);
1324
1325 /**
1326  * Construct and return a list of the device_nodes with a given type.
1327  */
1328 struct device_node *
1329 find_type_devices(const char *type)
1330 {
1331         struct device_node *head, **prevp, *np;
1332
1333         prevp = &head;
1334         for (np = allnodes; np != 0; np = np->allnext) {
1335                 if (np->type != 0 && strcasecmp(np->type, type) == 0) {
1336                         *prevp = np;
1337                         prevp = &np->next;
1338                 }
1339         }
1340         *prevp = NULL;
1341         return head;
1342 }
1343 EXPORT_SYMBOL(find_type_devices);
1344
1345 /**
1346  * Returns all nodes linked together
1347  */
1348 struct device_node *
1349 find_all_nodes(void)
1350 {
1351         struct device_node *head, **prevp, *np;
1352
1353         prevp = &head;
1354         for (np = allnodes; np != 0; np = np->allnext) {
1355                 *prevp = np;
1356                 prevp = &np->next;
1357         }
1358         *prevp = NULL;
1359         return head;
1360 }
1361 EXPORT_SYMBOL(find_all_nodes);
1362
1363 /** Checks if the given "compat" string matches one of the strings in
1364  * the device's "compatible" property
1365  */
1366 int
1367 device_is_compatible(struct device_node *device, const char *compat)
1368 {
1369         const char* cp;
1370         int cplen, l;
1371
1372         cp = (char *) get_property(device, "compatible", &cplen);
1373         if (cp == NULL)
1374                 return 0;
1375         while (cplen > 0) {
1376                 if (strncasecmp(cp, compat, strlen(compat)) == 0)
1377                         return 1;
1378                 l = strlen(cp) + 1;
1379                 cp += l;
1380                 cplen -= l;
1381         }
1382
1383         return 0;
1384 }
1385 EXPORT_SYMBOL(device_is_compatible);
1386
1387
1388 /**
1389  * Indicates whether the root node has a given value in its
1390  * compatible property.
1391  */
1392 int
1393 machine_is_compatible(const char *compat)
1394 {
1395         struct device_node *root;
1396         int rc = 0;
1397
1398         root = of_find_node_by_path("/");
1399         if (root) {
1400                 rc = device_is_compatible(root, compat);
1401                 of_node_put(root);
1402         }
1403         return rc;
1404 }
1405 EXPORT_SYMBOL(machine_is_compatible);
1406
1407 /**
1408  * Construct and return a list of the device_nodes with a given type
1409  * and compatible property.
1410  */
1411 struct device_node *
1412 find_compatible_devices(const char *type, const char *compat)
1413 {
1414         struct device_node *head, **prevp, *np;
1415
1416         prevp = &head;
1417         for (np = allnodes; np != 0; np = np->allnext) {
1418                 if (type != NULL
1419                     && !(np->type != 0 && strcasecmp(np->type, type) == 0))
1420                         continue;
1421                 if (device_is_compatible(np, compat)) {
1422                         *prevp = np;
1423                         prevp = &np->next;
1424                 }
1425         }
1426         *prevp = NULL;
1427         return head;
1428 }
1429 EXPORT_SYMBOL(find_compatible_devices);
1430
1431 /**
1432  * Find the device_node with a given full_name.
1433  */
1434 struct device_node *
1435 find_path_device(const char *path)
1436 {
1437         struct device_node *np;
1438
1439         for (np = allnodes; np != 0; np = np->allnext)
1440                 if (np->full_name != 0 && strcasecmp(np->full_name, path) == 0)
1441                         return np;
1442         return NULL;
1443 }
1444 EXPORT_SYMBOL(find_path_device);
1445
1446 /*******
1447  *
1448  * New implementation of the OF "find" APIs, return a refcounted
1449  * object, call of_node_put() when done.  The device tree and list
1450  * are protected by a rw_lock.
1451  *
1452  * Note that property management will need some locking as well,
1453  * this isn't dealt with yet.
1454  *
1455  *******/
1456
1457 /**
1458  *      of_find_node_by_name - Find a node by its "name" property
1459  *      @from:  The node to start searching from or NULL, the node
1460  *              you pass will not be searched, only the next one
1461  *              will; typically, you pass what the previous call
1462  *              returned. of_node_put() will be called on it
1463  *      @name:  The name string to match against
1464  *
1465  *      Returns a node pointer with refcount incremented, use
1466  *      of_node_put() on it when done.
1467  */
1468 struct device_node *of_find_node_by_name(struct device_node *from,
1469         const char *name)
1470 {
1471         struct device_node *np;
1472
1473         read_lock(&devtree_lock);
1474         np = from ? from->allnext : allnodes;
1475         for (; np != 0; np = np->allnext)
1476                 if (np->name != 0 && strcasecmp(np->name, name) == 0
1477                     && of_node_get(np))
1478                         break;
1479         if (from)
1480                 of_node_put(from);
1481         read_unlock(&devtree_lock);
1482         return np;
1483 }
1484 EXPORT_SYMBOL(of_find_node_by_name);
1485
1486 /**
1487  *      of_find_node_by_type - Find a node by its "device_type" property
1488  *      @from:  The node to start searching from or NULL, the node
1489  *              you pass will not be searched, only the next one
1490  *              will; typically, you pass what the previous call
1491  *              returned. of_node_put() will be called on it
1492  *      @name:  The type string to match against
1493  *
1494  *      Returns a node pointer with refcount incremented, use
1495  *      of_node_put() on it when done.
1496  */
1497 struct device_node *of_find_node_by_type(struct device_node *from,
1498         const char *type)
1499 {
1500         struct device_node *np;
1501
1502         read_lock(&devtree_lock);
1503         np = from ? from->allnext : allnodes;
1504         for (; np != 0; np = np->allnext)
1505                 if (np->type != 0 && strcasecmp(np->type, type) == 0
1506                     && of_node_get(np))
1507                         break;
1508         if (from)
1509                 of_node_put(from);
1510         read_unlock(&devtree_lock);
1511         return np;
1512 }
1513 EXPORT_SYMBOL(of_find_node_by_type);
1514
1515 /**
1516  *      of_find_compatible_node - Find a node based on type and one of the
1517  *                                tokens in its "compatible" property
1518  *      @from:          The node to start searching from or NULL, the node
1519  *                      you pass will not be searched, only the next one
1520  *                      will; typically, you pass what the previous call
1521  *                      returned. of_node_put() will be called on it
1522  *      @type:          The type string to match "device_type" or NULL to ignore
1523  *      @compatible:    The string to match to one of the tokens in the device
1524  *                      "compatible" list.
1525  *
1526  *      Returns a node pointer with refcount incremented, use
1527  *      of_node_put() on it when done.
1528  */
1529 struct device_node *of_find_compatible_node(struct device_node *from,
1530         const char *type, const char *compatible)
1531 {
1532         struct device_node *np;
1533
1534         read_lock(&devtree_lock);
1535         np = from ? from->allnext : allnodes;
1536         for (; np != 0; np = np->allnext) {
1537                 if (type != NULL
1538                     && !(np->type != 0 && strcasecmp(np->type, type) == 0))
1539                         continue;
1540                 if (device_is_compatible(np, compatible) && of_node_get(np))
1541                         break;
1542         }
1543         if (from)
1544                 of_node_put(from);
1545         read_unlock(&devtree_lock);
1546         return np;
1547 }
1548 EXPORT_SYMBOL(of_find_compatible_node);
1549
1550 /**
1551  *      of_find_node_by_path - Find a node matching a full OF path
1552  *      @path:  The full path to match
1553  *
1554  *      Returns a node pointer with refcount incremented, use
1555  *      of_node_put() on it when done.
1556  */
1557 struct device_node *of_find_node_by_path(const char *path)
1558 {
1559         struct device_node *np = allnodes;
1560
1561         read_lock(&devtree_lock);
1562         for (; np != 0; np = np->allnext) {
1563                 if (np->full_name != 0 && strcasecmp(np->full_name, path) == 0
1564                     && of_node_get(np))
1565                         break;
1566         }
1567         read_unlock(&devtree_lock);
1568         return np;
1569 }
1570 EXPORT_SYMBOL(of_find_node_by_path);
1571
1572 /**
1573  *      of_find_node_by_phandle - Find a node given a phandle
1574  *      @handle:        phandle of the node to find
1575  *
1576  *      Returns a node pointer with refcount incremented, use
1577  *      of_node_put() on it when done.
1578  */
1579 struct device_node *of_find_node_by_phandle(phandle handle)
1580 {
1581         struct device_node *np;
1582
1583         read_lock(&devtree_lock);
1584         for (np = allnodes; np != 0; np = np->allnext)
1585                 if (np->linux_phandle == handle)
1586                         break;
1587         if (np)
1588                 of_node_get(np);
1589         read_unlock(&devtree_lock);
1590         return np;
1591 }
1592 EXPORT_SYMBOL(of_find_node_by_phandle);
1593
1594 /**
1595  *      of_find_all_nodes - Get next node in global list
1596  *      @prev:  Previous node or NULL to start iteration
1597  *              of_node_put() will be called on it
1598  *
1599  *      Returns a node pointer with refcount incremented, use
1600  *      of_node_put() on it when done.
1601  */
1602 struct device_node *of_find_all_nodes(struct device_node *prev)
1603 {
1604         struct device_node *np;
1605
1606         read_lock(&devtree_lock);
1607         np = prev ? prev->allnext : allnodes;
1608         for (; np != 0; np = np->allnext)
1609                 if (of_node_get(np))
1610                         break;
1611         if (prev)
1612                 of_node_put(prev);
1613         read_unlock(&devtree_lock);
1614         return np;
1615 }
1616 EXPORT_SYMBOL(of_find_all_nodes);
1617
1618 /**
1619  *      of_get_parent - Get a node's parent if any
1620  *      @node:  Node to get parent
1621  *
1622  *      Returns a node pointer with refcount incremented, use
1623  *      of_node_put() on it when done.
1624  */
1625 struct device_node *of_get_parent(const struct device_node *node)
1626 {
1627         struct device_node *np;
1628
1629         if (!node)
1630                 return NULL;
1631
1632         read_lock(&devtree_lock);
1633         np = of_node_get(node->parent);
1634         read_unlock(&devtree_lock);
1635         return np;
1636 }
1637 EXPORT_SYMBOL(of_get_parent);
1638
1639 /**
1640  *      of_get_next_child - Iterate a node childs
1641  *      @node:  parent node
1642  *      @prev:  previous child of the parent node, or NULL to get first
1643  *
1644  *      Returns a node pointer with refcount incremented, use
1645  *      of_node_put() on it when done.
1646  */
1647 struct device_node *of_get_next_child(const struct device_node *node,
1648         struct device_node *prev)
1649 {
1650         struct device_node *next;
1651
1652         read_lock(&devtree_lock);
1653         next = prev ? prev->sibling : node->child;
1654         for (; next != 0; next = next->sibling)
1655                 if (of_node_get(next))
1656                         break;
1657         if (prev)
1658                 of_node_put(prev);
1659         read_unlock(&devtree_lock);
1660         return next;
1661 }
1662 EXPORT_SYMBOL(of_get_next_child);
1663
1664 /**
1665  *      of_node_get - Increment refcount of a node
1666  *      @node:  Node to inc refcount, NULL is supported to
1667  *              simplify writing of callers
1668  *
1669  *      Returns node.
1670  */
1671 struct device_node *of_node_get(struct device_node *node)
1672 {
1673         if (node)
1674                 kref_get(&node->kref);
1675         return node;
1676 }
1677 EXPORT_SYMBOL(of_node_get);
1678
1679 static inline struct device_node * kref_to_device_node(struct kref *kref)
1680 {
1681         return container_of(kref, struct device_node, kref);
1682 }
1683
1684 /**
1685  *      of_node_release - release a dynamically allocated node
1686  *      @kref:  kref element of the node to be released
1687  *
1688  *      In of_node_put() this function is passed to kref_put()
1689  *      as the destructor.
1690  */
1691 static void of_node_release(struct kref *kref)
1692 {
1693         struct device_node *node = kref_to_device_node(kref);
1694         struct property *prop = node->properties;
1695
1696         if (!OF_IS_DYNAMIC(node))
1697                 return;
1698         while (prop) {
1699                 struct property *next = prop->next;
1700                 kfree(prop->name);
1701                 kfree(prop->value);
1702                 kfree(prop);
1703                 prop = next;
1704         }
1705         kfree(node->intrs);
1706         kfree(node->addrs);
1707         kfree(node->full_name);
1708         kfree(node->data);
1709         kfree(node);
1710 }
1711
1712 /**
1713  *      of_node_put - Decrement refcount of a node
1714  *      @node:  Node to dec refcount, NULL is supported to
1715  *              simplify writing of callers
1716  *
1717  */
1718 void of_node_put(struct device_node *node)
1719 {
1720         if (node)
1721                 kref_put(&node->kref, of_node_release);
1722 }
1723 EXPORT_SYMBOL(of_node_put);
1724
1725 /*
1726  * Fix up the uninitialized fields in a new device node:
1727  * name, type, n_addrs, addrs, n_intrs, intrs, and pci-specific fields
1728  *
1729  * A lot of boot-time code is duplicated here, because functions such
1730  * as finish_node_interrupts, interpret_pci_props, etc. cannot use the
1731  * slab allocator.
1732  *
1733  * This should probably be split up into smaller chunks.
1734  */
1735
1736 static int of_finish_dynamic_node(struct device_node *node,
1737                                   unsigned long *unused1, int unused2,
1738                                   int unused3, int unused4)
1739 {
1740         struct device_node *parent = of_get_parent(node);
1741         int err = 0;
1742         phandle *ibm_phandle;
1743
1744         node->name = get_property(node, "name", NULL);
1745         node->type = get_property(node, "device_type", NULL);
1746
1747         if (!parent) {
1748                 err = -ENODEV;
1749                 goto out;
1750         }
1751
1752         /* We don't support that function on PowerMac, at least
1753          * not yet
1754          */
1755         if (systemcfg->platform == PLATFORM_POWERMAC)
1756                 return -ENODEV;
1757
1758         /* fix up new node's linux_phandle field */
1759         if ((ibm_phandle = (unsigned int *)get_property(node, "ibm,phandle", NULL)))
1760                 node->linux_phandle = *ibm_phandle;
1761
1762 out:
1763         of_node_put(parent);
1764         return err;
1765 }
1766
1767 /*
1768  * Plug a device node into the tree and global list.
1769  */
1770 void of_attach_node(struct device_node *np)
1771 {
1772         write_lock(&devtree_lock);
1773         np->sibling = np->parent->child;
1774         np->allnext = allnodes;
1775         np->parent->child = np;
1776         allnodes = np;
1777         write_unlock(&devtree_lock);
1778 }
1779
1780 /*
1781  * "Unplug" a node from the device tree.  The caller must hold
1782  * a reference to the node.  The memory associated with the node
1783  * is not freed until its refcount goes to zero.
1784  */
1785 void of_detach_node(const struct device_node *np)
1786 {
1787         struct device_node *parent;
1788
1789         write_lock(&devtree_lock);
1790
1791         parent = np->parent;
1792
1793         if (allnodes == np)
1794                 allnodes = np->allnext;
1795         else {
1796                 struct device_node *prev;
1797                 for (prev = allnodes;
1798                      prev->allnext != np;
1799                      prev = prev->allnext)
1800                         ;
1801                 prev->allnext = np->allnext;
1802         }
1803
1804         if (parent->child == np)
1805                 parent->child = np->sibling;
1806         else {
1807                 struct device_node *prevsib;
1808                 for (prevsib = np->parent->child;
1809                      prevsib->sibling != np;
1810                      prevsib = prevsib->sibling)
1811                         ;
1812                 prevsib->sibling = np->sibling;
1813         }
1814
1815         write_unlock(&devtree_lock);
1816 }
1817
1818 static int prom_reconfig_notifier(struct notifier_block *nb, unsigned long action, void *node)
1819 {
1820         int err;
1821
1822         switch (action) {
1823         case PSERIES_RECONFIG_ADD:
1824                 err = finish_node(node, NULL, of_finish_dynamic_node, 0, 0, 0);
1825                 if (err < 0) {
1826                         printk(KERN_ERR "finish_node returned %d\n", err);
1827                         err = NOTIFY_BAD;
1828                 }
1829                 break;
1830         default:
1831                 err = NOTIFY_DONE;
1832                 break;
1833         }
1834         return err;
1835 }
1836
1837 static struct notifier_block prom_reconfig_nb = {
1838         .notifier_call = prom_reconfig_notifier,
1839         .priority = 10, /* This one needs to run first */
1840 };
1841
1842 static int __init prom_reconfig_setup(void)
1843 {
1844         return pSeries_reconfig_notifier_register(&prom_reconfig_nb);
1845 }
1846 __initcall(prom_reconfig_setup);
1847
1848 /*
1849  * Find a property with a given name for a given node
1850  * and return the value.
1851  */
1852 unsigned char *
1853 get_property(struct device_node *np, const char *name, int *lenp)
1854 {
1855         struct property *pp;
1856
1857         for (pp = np->properties; pp != 0; pp = pp->next)
1858                 if (strcmp(pp->name, name) == 0) {
1859                         if (lenp != 0)
1860                                 *lenp = pp->length;
1861                         return pp->value;
1862                 }
1863         return NULL;
1864 }
1865 EXPORT_SYMBOL(get_property);
1866
1867 /*
1868  * Add a property to a node
1869  */
1870 void
1871 prom_add_property(struct device_node* np, struct property* prop)
1872 {
1873         struct property **next = &np->properties;
1874
1875         prop->next = NULL;      
1876         while (*next)
1877                 next = &(*next)->next;
1878         *next = prop;
1879 }
1880
1881 #if 0
1882 void
1883 print_properties(struct device_node *np)
1884 {
1885         struct property *pp;
1886         char *cp;
1887         int i, n;
1888
1889         for (pp = np->properties; pp != 0; pp = pp->next) {
1890                 printk(KERN_INFO "%s", pp->name);
1891                 for (i = strlen(pp->name); i < 16; ++i)
1892                         printk(" ");
1893                 cp = (char *) pp->value;
1894                 for (i = pp->length; i > 0; --i, ++cp)
1895                         if ((i > 1 && (*cp < 0x20 || *cp > 0x7e))
1896                             || (i == 1 && *cp != 0))
1897                                 break;
1898                 if (i == 0 && pp->length > 1) {
1899                         /* looks like a string */
1900                         printk(" %s\n", (char *) pp->value);
1901                 } else {
1902                         /* dump it in hex */
1903                         n = pp->length;
1904                         if (n > 64)
1905                                 n = 64;
1906                         if (pp->length % 4 == 0) {
1907                                 unsigned int *p = (unsigned int *) pp->value;
1908
1909                                 n /= 4;
1910                                 for (i = 0; i < n; ++i) {
1911                                         if (i != 0 && (i % 4) == 0)
1912                                                 printk("\n                ");
1913                                         printk(" %08x", *p++);
1914                                 }
1915                         } else {
1916                                 unsigned char *bp = pp->value;
1917
1918                                 for (i = 0; i < n; ++i) {
1919                                         if (i != 0 && (i % 16) == 0)
1920                                                 printk("\n                ");
1921                                         printk(" %02x", *bp++);
1922                                 }
1923                         }
1924                         printk("\n");
1925                         if (pp->length > 64)
1926                                 printk("                 ... (length = %d)\n",
1927                                        pp->length);
1928                 }
1929         }
1930 }
1931 #endif
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941