]> git.sur5r.net Git - u-boot/blob - lib/fdtdec.c
45f3fe7baf8e76505e4b769bb945a62452ba1522
[u-boot] / lib / fdtdec.c
1 /*
2  * Copyright (c) 2011 The Chromium OS Authors.
3  * SPDX-License-Identifier:     GPL-2.0+
4  */
5
6 #ifndef USE_HOSTCC
7 #include <common.h>
8 #include <boot_fit.h>
9 #include <dm.h>
10 #include <dm/of_extra.h>
11 #include <errno.h>
12 #include <fdtdec.h>
13 #include <fdt_support.h>
14 #include <libfdt.h>
15 #include <serial.h>
16 #include <asm/sections.h>
17 #include <linux/ctype.h>
18 #include <linux/lzo.h>
19
20 DECLARE_GLOBAL_DATA_PTR;
21
22 /*
23  * Here are the type we know about. One day we might allow drivers to
24  * register. For now we just put them here. The COMPAT macro allows us to
25  * turn this into a sparse list later, and keeps the ID with the name.
26  *
27  * NOTE: This list is basically a TODO list for things that need to be
28  * converted to driver model. So don't add new things here unless there is a
29  * good reason why driver-model conversion is infeasible. Examples include
30  * things which are used before driver model is available.
31  */
32 #define COMPAT(id, name) name
33 static const char * const compat_names[COMPAT_COUNT] = {
34         COMPAT(UNKNOWN, "<none>"),
35         COMPAT(NVIDIA_TEGRA20_EMC, "nvidia,tegra20-emc"),
36         COMPAT(NVIDIA_TEGRA20_EMC_TABLE, "nvidia,tegra20-emc-table"),
37         COMPAT(NVIDIA_TEGRA20_NAND, "nvidia,tegra20-nand"),
38         COMPAT(NVIDIA_TEGRA124_XUSB_PADCTL, "nvidia,tegra124-xusb-padctl"),
39         COMPAT(NVIDIA_TEGRA210_XUSB_PADCTL, "nvidia,tegra210-xusb-padctl"),
40         COMPAT(SMSC_LAN9215, "smsc,lan9215"),
41         COMPAT(SAMSUNG_EXYNOS5_SROMC, "samsung,exynos-sromc"),
42         COMPAT(SAMSUNG_S3C2440_I2C, "samsung,s3c2440-i2c"),
43         COMPAT(SAMSUNG_EXYNOS5_SOUND, "samsung,exynos-sound"),
44         COMPAT(WOLFSON_WM8994_CODEC, "wolfson,wm8994-codec"),
45         COMPAT(SAMSUNG_EXYNOS_USB_PHY, "samsung,exynos-usb-phy"),
46         COMPAT(SAMSUNG_EXYNOS5_USB3_PHY, "samsung,exynos5250-usb3-phy"),
47         COMPAT(SAMSUNG_EXYNOS_TMU, "samsung,exynos-tmu"),
48         COMPAT(SAMSUNG_EXYNOS_MIPI_DSI, "samsung,exynos-mipi-dsi"),
49         COMPAT(SAMSUNG_EXYNOS_DWMMC, "samsung,exynos-dwmmc"),
50         COMPAT(SAMSUNG_EXYNOS_MMC, "samsung,exynos-mmc"),
51         COMPAT(MAXIM_MAX77686_PMIC, "maxim,max77686"),
52         COMPAT(GENERIC_SPI_FLASH, "spi-flash"),
53         COMPAT(MAXIM_98095_CODEC, "maxim,max98095-codec"),
54         COMPAT(SAMSUNG_EXYNOS5_I2C, "samsung,exynos5-hsi2c"),
55         COMPAT(SAMSUNG_EXYNOS_SYSMMU, "samsung,sysmmu-v3.3"),
56         COMPAT(INTEL_MICROCODE, "intel,microcode"),
57         COMPAT(AMS_AS3722, "ams,as3722"),
58         COMPAT(INTEL_QRK_MRC, "intel,quark-mrc"),
59         COMPAT(ALTERA_SOCFPGA_DWMAC, "altr,socfpga-stmmac"),
60         COMPAT(ALTERA_SOCFPGA_DWMMC, "altr,socfpga-dw-mshc"),
61         COMPAT(ALTERA_SOCFPGA_DWC2USB, "snps,dwc2"),
62         COMPAT(INTEL_BAYTRAIL_FSP, "intel,baytrail-fsp"),
63         COMPAT(INTEL_BAYTRAIL_FSP_MDP, "intel,baytrail-fsp-mdp"),
64         COMPAT(INTEL_IVYBRIDGE_FSP, "intel,ivybridge-fsp"),
65         COMPAT(COMPAT_SUNXI_NAND, "allwinner,sun4i-a10-nand"),
66         COMPAT(ALTERA_SOCFPGA_CLK, "altr,clk-mgr"),
67         COMPAT(ALTERA_SOCFPGA_PINCTRL_SINGLE, "pinctrl-single"),
68         COMPAT(ALTERA_SOCFPGA_H2F_BRG, "altr,socfpga-hps2fpga-bridge"),
69         COMPAT(ALTERA_SOCFPGA_LWH2F_BRG, "altr,socfpga-lwhps2fpga-bridge"),
70         COMPAT(ALTERA_SOCFPGA_F2H_BRG, "altr,socfpga-fpga2hps-bridge"),
71         COMPAT(ALTERA_SOCFPGA_F2SDR0, "altr,socfpga-fpga2sdram0-bridge"),
72         COMPAT(ALTERA_SOCFPGA_F2SDR1, "altr,socfpga-fpga2sdram1-bridge"),
73         COMPAT(ALTERA_SOCFPGA_F2SDR2, "altr,socfpga-fpga2sdram2-bridge"),
74 };
75
76 const char *fdtdec_get_compatible(enum fdt_compat_id id)
77 {
78         /* We allow reading of the 'unknown' ID for testing purposes */
79         assert(id >= 0 && id < COMPAT_COUNT);
80         return compat_names[id];
81 }
82
83 fdt_addr_t fdtdec_get_addr_size_fixed(const void *blob, int node,
84                 const char *prop_name, int index, int na, int ns,
85                 fdt_size_t *sizep, bool translate)
86 {
87         const fdt32_t *prop, *prop_end;
88         const fdt32_t *prop_addr, *prop_size, *prop_after_size;
89         int len;
90         fdt_addr_t addr;
91
92         debug("%s: %s: ", __func__, prop_name);
93
94         if (na > (sizeof(fdt_addr_t) / sizeof(fdt32_t))) {
95                 debug("(na too large for fdt_addr_t type)\n");
96                 return FDT_ADDR_T_NONE;
97         }
98
99         if (ns > (sizeof(fdt_size_t) / sizeof(fdt32_t))) {
100                 debug("(ns too large for fdt_size_t type)\n");
101                 return FDT_ADDR_T_NONE;
102         }
103
104         prop = fdt_getprop(blob, node, prop_name, &len);
105         if (!prop) {
106                 debug("(not found)\n");
107                 return FDT_ADDR_T_NONE;
108         }
109         prop_end = prop + (len / sizeof(*prop));
110
111         prop_addr = prop + (index * (na + ns));
112         prop_size = prop_addr + na;
113         prop_after_size = prop_size + ns;
114         if (prop_after_size > prop_end) {
115                 debug("(not enough data: expected >= %d cells, got %d cells)\n",
116                       (u32)(prop_after_size - prop), ((u32)(prop_end - prop)));
117                 return FDT_ADDR_T_NONE;
118         }
119
120 #if CONFIG_IS_ENABLED(OF_TRANSLATE)
121         if (translate)
122                 addr = fdt_translate_address(blob, node, prop_addr);
123         else
124 #endif
125                 addr = fdtdec_get_number(prop_addr, na);
126
127         if (sizep) {
128                 *sizep = fdtdec_get_number(prop_size, ns);
129                 debug("addr=%08llx, size=%llx\n", (unsigned long long)addr,
130                       (unsigned long long)*sizep);
131         } else {
132                 debug("addr=%08llx\n", (unsigned long long)addr);
133         }
134
135         return addr;
136 }
137
138 fdt_addr_t fdtdec_get_addr_size_auto_parent(const void *blob, int parent,
139                 int node, const char *prop_name, int index, fdt_size_t *sizep,
140                 bool translate)
141 {
142         int na, ns;
143
144         debug("%s: ", __func__);
145
146         na = fdt_address_cells(blob, parent);
147         if (na < 1) {
148                 debug("(bad #address-cells)\n");
149                 return FDT_ADDR_T_NONE;
150         }
151
152         ns = fdt_size_cells(blob, parent);
153         if (ns < 0) {
154                 debug("(bad #size-cells)\n");
155                 return FDT_ADDR_T_NONE;
156         }
157
158         debug("na=%d, ns=%d, ", na, ns);
159
160         return fdtdec_get_addr_size_fixed(blob, node, prop_name, index, na,
161                                           ns, sizep, translate);
162 }
163
164 fdt_addr_t fdtdec_get_addr_size_auto_noparent(const void *blob, int node,
165                 const char *prop_name, int index, fdt_size_t *sizep,
166                 bool translate)
167 {
168         int parent;
169
170         debug("%s: ", __func__);
171
172         parent = fdt_parent_offset(blob, node);
173         if (parent < 0) {
174                 debug("(no parent found)\n");
175                 return FDT_ADDR_T_NONE;
176         }
177
178         return fdtdec_get_addr_size_auto_parent(blob, parent, node, prop_name,
179                                                 index, sizep, translate);
180 }
181
182 fdt_addr_t fdtdec_get_addr_size(const void *blob, int node,
183                 const char *prop_name, fdt_size_t *sizep)
184 {
185         int ns = sizep ? (sizeof(fdt_size_t) / sizeof(fdt32_t)) : 0;
186
187         return fdtdec_get_addr_size_fixed(blob, node, prop_name, 0,
188                                           sizeof(fdt_addr_t) / sizeof(fdt32_t),
189                                           ns, sizep, false);
190 }
191
192 fdt_addr_t fdtdec_get_addr(const void *blob, int node,
193                 const char *prop_name)
194 {
195         return fdtdec_get_addr_size(blob, node, prop_name, NULL);
196 }
197
198 #if defined(CONFIG_PCI) && defined(CONFIG_DM_PCI)
199 int fdtdec_get_pci_addr(const void *blob, int node, enum fdt_pci_space type,
200                 const char *prop_name, struct fdt_pci_addr *addr)
201 {
202         const u32 *cell;
203         int len;
204         int ret = -ENOENT;
205
206         debug("%s: %s: ", __func__, prop_name);
207
208         /*
209          * If we follow the pci bus bindings strictly, we should check
210          * the value of the node's parent node's #address-cells and
211          * #size-cells. They need to be 3 and 2 accordingly. However,
212          * for simplicity we skip the check here.
213          */
214         cell = fdt_getprop(blob, node, prop_name, &len);
215         if (!cell)
216                 goto fail;
217
218         if ((len % FDT_PCI_REG_SIZE) == 0) {
219                 int num = len / FDT_PCI_REG_SIZE;
220                 int i;
221
222                 for (i = 0; i < num; i++) {
223                         debug("pci address #%d: %08lx %08lx %08lx\n", i,
224                               (ulong)fdt32_to_cpu(cell[0]),
225                               (ulong)fdt32_to_cpu(cell[1]),
226                               (ulong)fdt32_to_cpu(cell[2]));
227                         if ((fdt32_to_cpu(*cell) & type) == type) {
228                                 addr->phys_hi = fdt32_to_cpu(cell[0]);
229                                 addr->phys_mid = fdt32_to_cpu(cell[1]);
230                                 addr->phys_lo = fdt32_to_cpu(cell[1]);
231                                 break;
232                         } else {
233                                 cell += (FDT_PCI_ADDR_CELLS +
234                                          FDT_PCI_SIZE_CELLS);
235                         }
236                 }
237
238                 if (i == num) {
239                         ret = -ENXIO;
240                         goto fail;
241                 }
242
243                 return 0;
244         } else {
245                 ret = -EINVAL;
246         }
247
248 fail:
249         debug("(not found)\n");
250         return ret;
251 }
252
253 int fdtdec_get_pci_vendev(const void *blob, int node, u16 *vendor, u16 *device)
254 {
255         const char *list, *end;
256         int len;
257
258         list = fdt_getprop(blob, node, "compatible", &len);
259         if (!list)
260                 return -ENOENT;
261
262         end = list + len;
263         while (list < end) {
264                 char *s;
265
266                 len = strlen(list);
267                 if (len >= strlen("pciVVVV,DDDD")) {
268                         s = strstr(list, "pci");
269
270                         /*
271                          * check if the string is something like pciVVVV,DDDD.RR
272                          * or just pciVVVV,DDDD
273                          */
274                         if (s && s[7] == ',' &&
275                             (s[12] == '.' || s[12] == 0)) {
276                                 s += 3;
277                                 *vendor = simple_strtol(s, NULL, 16);
278
279                                 s += 5;
280                                 *device = simple_strtol(s, NULL, 16);
281
282                                 return 0;
283                         }
284                 }
285                 list += (len + 1);
286         }
287
288         return -ENOENT;
289 }
290
291 int fdtdec_get_pci_bar32(struct udevice *dev, struct fdt_pci_addr *addr,
292                          u32 *bar)
293 {
294         int barnum;
295
296         /* extract the bar number from fdt_pci_addr */
297         barnum = addr->phys_hi & 0xff;
298         if ((barnum < PCI_BASE_ADDRESS_0) || (barnum > PCI_CARDBUS_CIS))
299                 return -EINVAL;
300
301         barnum = (barnum - PCI_BASE_ADDRESS_0) / 4;
302         *bar = dm_pci_read_bar32(dev, barnum);
303
304         return 0;
305 }
306 #endif
307
308 uint64_t fdtdec_get_uint64(const void *blob, int node, const char *prop_name,
309                 uint64_t default_val)
310 {
311         const uint64_t *cell64;
312         int length;
313
314         cell64 = fdt_getprop(blob, node, prop_name, &length);
315         if (!cell64 || length < sizeof(*cell64))
316                 return default_val;
317
318         return fdt64_to_cpu(*cell64);
319 }
320
321 int fdtdec_get_is_enabled(const void *blob, int node)
322 {
323         const char *cell;
324
325         /*
326          * It should say "okay", so only allow that. Some fdts use "ok" but
327          * this is a bug. Please fix your device tree source file. See here
328          * for discussion:
329          *
330          * http://www.mail-archive.com/u-boot@lists.denx.de/msg71598.html
331          */
332         cell = fdt_getprop(blob, node, "status", NULL);
333         if (cell)
334                 return 0 == strcmp(cell, "okay");
335         return 1;
336 }
337
338 enum fdt_compat_id fdtdec_lookup(const void *blob, int node)
339 {
340         enum fdt_compat_id id;
341
342         /* Search our drivers */
343         for (id = COMPAT_UNKNOWN; id < COMPAT_COUNT; id++)
344                 if (0 == fdt_node_check_compatible(blob, node,
345                                 compat_names[id]))
346                         return id;
347         return COMPAT_UNKNOWN;
348 }
349
350 int fdtdec_next_compatible(const void *blob, int node,
351                 enum fdt_compat_id id)
352 {
353         return fdt_node_offset_by_compatible(blob, node, compat_names[id]);
354 }
355
356 int fdtdec_next_compatible_subnode(const void *blob, int node,
357                 enum fdt_compat_id id, int *depthp)
358 {
359         do {
360                 node = fdt_next_node(blob, node, depthp);
361         } while (*depthp > 1);
362
363         /* If this is a direct subnode, and compatible, return it */
364         if (*depthp == 1 && 0 == fdt_node_check_compatible(
365                                                 blob, node, compat_names[id]))
366                 return node;
367
368         return -FDT_ERR_NOTFOUND;
369 }
370
371 int fdtdec_next_alias(const void *blob, const char *name,
372                 enum fdt_compat_id id, int *upto)
373 {
374 #define MAX_STR_LEN 20
375         char str[MAX_STR_LEN + 20];
376         int node, err;
377
378         /* snprintf() is not available */
379         assert(strlen(name) < MAX_STR_LEN);
380         sprintf(str, "%.*s%d", MAX_STR_LEN, name, *upto);
381         node = fdt_path_offset(blob, str);
382         if (node < 0)
383                 return node;
384         err = fdt_node_check_compatible(blob, node, compat_names[id]);
385         if (err < 0)
386                 return err;
387         if (err)
388                 return -FDT_ERR_NOTFOUND;
389         (*upto)++;
390         return node;
391 }
392
393 int fdtdec_find_aliases_for_id(const void *blob, const char *name,
394                         enum fdt_compat_id id, int *node_list, int maxcount)
395 {
396         memset(node_list, '\0', sizeof(*node_list) * maxcount);
397
398         return fdtdec_add_aliases_for_id(blob, name, id, node_list, maxcount);
399 }
400
401 /* TODO: Can we tighten this code up a little? */
402 int fdtdec_add_aliases_for_id(const void *blob, const char *name,
403                         enum fdt_compat_id id, int *node_list, int maxcount)
404 {
405         int name_len = strlen(name);
406         int nodes[maxcount];
407         int num_found = 0;
408         int offset, node;
409         int alias_node;
410         int count;
411         int i, j;
412
413         /* find the alias node if present */
414         alias_node = fdt_path_offset(blob, "/aliases");
415
416         /*
417          * start with nothing, and we can assume that the root node can't
418          * match
419          */
420         memset(nodes, '\0', sizeof(nodes));
421
422         /* First find all the compatible nodes */
423         for (node = count = 0; node >= 0 && count < maxcount;) {
424                 node = fdtdec_next_compatible(blob, node, id);
425                 if (node >= 0)
426                         nodes[count++] = node;
427         }
428         if (node >= 0)
429                 debug("%s: warning: maxcount exceeded with alias '%s'\n",
430                        __func__, name);
431
432         /* Now find all the aliases */
433         for (offset = fdt_first_property_offset(blob, alias_node);
434                         offset > 0;
435                         offset = fdt_next_property_offset(blob, offset)) {
436                 const struct fdt_property *prop;
437                 const char *path;
438                 int number;
439                 int found;
440
441                 node = 0;
442                 prop = fdt_get_property_by_offset(blob, offset, NULL);
443                 path = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
444                 if (prop->len && 0 == strncmp(path, name, name_len))
445                         node = fdt_path_offset(blob, prop->data);
446                 if (node <= 0)
447                         continue;
448
449                 /* Get the alias number */
450                 number = simple_strtoul(path + name_len, NULL, 10);
451                 if (number < 0 || number >= maxcount) {
452                         debug("%s: warning: alias '%s' is out of range\n",
453                                __func__, path);
454                         continue;
455                 }
456
457                 /* Make sure the node we found is actually in our list! */
458                 found = -1;
459                 for (j = 0; j < count; j++)
460                         if (nodes[j] == node) {
461                                 found = j;
462                                 break;
463                         }
464
465                 if (found == -1) {
466                         debug("%s: warning: alias '%s' points to a node "
467                                 "'%s' that is missing or is not compatible "
468                                 " with '%s'\n", __func__, path,
469                                 fdt_get_name(blob, node, NULL),
470                                compat_names[id]);
471                         continue;
472                 }
473
474                 /*
475                  * Add this node to our list in the right place, and mark
476                  * it as done.
477                  */
478                 if (fdtdec_get_is_enabled(blob, node)) {
479                         if (node_list[number]) {
480                                 debug("%s: warning: alias '%s' requires that "
481                                       "a node be placed in the list in a "
482                                       "position which is already filled by "
483                                       "node '%s'\n", __func__, path,
484                                       fdt_get_name(blob, node, NULL));
485                                 continue;
486                         }
487                         node_list[number] = node;
488                         if (number >= num_found)
489                                 num_found = number + 1;
490                 }
491                 nodes[found] = 0;
492         }
493
494         /* Add any nodes not mentioned by an alias */
495         for (i = j = 0; i < maxcount; i++) {
496                 if (!node_list[i]) {
497                         for (; j < maxcount; j++)
498                                 if (nodes[j] &&
499                                         fdtdec_get_is_enabled(blob, nodes[j]))
500                                         break;
501
502                         /* Have we run out of nodes to add? */
503                         if (j == maxcount)
504                                 break;
505
506                         assert(!node_list[i]);
507                         node_list[i] = nodes[j++];
508                         if (i >= num_found)
509                                 num_found = i + 1;
510                 }
511         }
512
513         return num_found;
514 }
515
516 int fdtdec_get_alias_seq(const void *blob, const char *base, int offset,
517                          int *seqp)
518 {
519         int base_len = strlen(base);
520         const char *find_name;
521         int find_namelen;
522         int prop_offset;
523         int aliases;
524
525         find_name = fdt_get_name(blob, offset, &find_namelen);
526         debug("Looking for '%s' at %d, name %s\n", base, offset, find_name);
527
528         aliases = fdt_path_offset(blob, "/aliases");
529         for (prop_offset = fdt_first_property_offset(blob, aliases);
530              prop_offset > 0;
531              prop_offset = fdt_next_property_offset(blob, prop_offset)) {
532                 const char *prop;
533                 const char *name;
534                 const char *slash;
535                 int len, val;
536
537                 prop = fdt_getprop_by_offset(blob, prop_offset, &name, &len);
538                 debug("   - %s, %s\n", name, prop);
539                 if (len < find_namelen || *prop != '/' || prop[len - 1] ||
540                     strncmp(name, base, base_len))
541                         continue;
542
543                 slash = strrchr(prop, '/');
544                 if (strcmp(slash + 1, find_name))
545                         continue;
546                 val = trailing_strtol(name);
547                 if (val != -1) {
548                         *seqp = val;
549                         debug("Found seq %d\n", *seqp);
550                         return 0;
551                 }
552         }
553
554         debug("Not found\n");
555         return -ENOENT;
556 }
557
558 const char *fdtdec_get_chosen_prop(const void *blob, const char *name)
559 {
560         int chosen_node;
561
562         if (!blob)
563                 return NULL;
564         chosen_node = fdt_path_offset(blob, "/chosen");
565         return fdt_getprop(blob, chosen_node, name, NULL);
566 }
567
568 int fdtdec_get_chosen_node(const void *blob, const char *name)
569 {
570         const char *prop;
571
572         prop = fdtdec_get_chosen_prop(blob, name);
573         if (!prop)
574                 return -FDT_ERR_NOTFOUND;
575         return fdt_path_offset(blob, prop);
576 }
577
578 int fdtdec_check_fdt(void)
579 {
580         /*
581          * We must have an FDT, but we cannot panic() yet since the console
582          * is not ready. So for now, just assert(). Boards which need an early
583          * FDT (prior to console ready) will need to make their own
584          * arrangements and do their own checks.
585          */
586         assert(!fdtdec_prepare_fdt());
587         return 0;
588 }
589
590 /*
591  * This function is a little odd in that it accesses global data. At some
592  * point if the architecture board.c files merge this will make more sense.
593  * Even now, it is common code.
594  */
595 int fdtdec_prepare_fdt(void)
596 {
597         if (!gd->fdt_blob || ((uintptr_t)gd->fdt_blob & 3) ||
598             fdt_check_header(gd->fdt_blob)) {
599 #ifdef CONFIG_SPL_BUILD
600                 puts("Missing DTB\n");
601 #else
602                 puts("No valid device tree binary found - please append one to U-Boot binary, use u-boot-dtb.bin or define CONFIG_OF_EMBED. For sandbox, use -d <file.dtb>\n");
603 # ifdef DEBUG
604                 if (gd->fdt_blob) {
605                         printf("fdt_blob=%p\n", gd->fdt_blob);
606                         print_buffer((ulong)gd->fdt_blob, gd->fdt_blob, 4,
607                                      32, 0);
608                 }
609 # endif
610 #endif
611                 return -1;
612         }
613         return 0;
614 }
615
616 int fdtdec_lookup_phandle(const void *blob, int node, const char *prop_name)
617 {
618         const u32 *phandle;
619         int lookup;
620
621         debug("%s: %s\n", __func__, prop_name);
622         phandle = fdt_getprop(blob, node, prop_name, NULL);
623         if (!phandle)
624                 return -FDT_ERR_NOTFOUND;
625
626         lookup = fdt_node_offset_by_phandle(blob, fdt32_to_cpu(*phandle));
627         return lookup;
628 }
629
630 /**
631  * Look up a property in a node and check that it has a minimum length.
632  *
633  * @param blob          FDT blob
634  * @param node          node to examine
635  * @param prop_name     name of property to find
636  * @param min_len       minimum property length in bytes
637  * @param err           0 if ok, or -FDT_ERR_NOTFOUND if the property is not
638                         found, or -FDT_ERR_BADLAYOUT if not enough data
639  * @return pointer to cell, which is only valid if err == 0
640  */
641 static const void *get_prop_check_min_len(const void *blob, int node,
642                 const char *prop_name, int min_len, int *err)
643 {
644         const void *cell;
645         int len;
646
647         debug("%s: %s\n", __func__, prop_name);
648         cell = fdt_getprop(blob, node, prop_name, &len);
649         if (!cell)
650                 *err = -FDT_ERR_NOTFOUND;
651         else if (len < min_len)
652                 *err = -FDT_ERR_BADLAYOUT;
653         else
654                 *err = 0;
655         return cell;
656 }
657
658 int fdtdec_get_int_array(const void *blob, int node, const char *prop_name,
659                 u32 *array, int count)
660 {
661         const u32 *cell;
662         int i, err = 0;
663
664         debug("%s: %s\n", __func__, prop_name);
665         cell = get_prop_check_min_len(blob, node, prop_name,
666                                       sizeof(u32) * count, &err);
667         if (!err) {
668                 for (i = 0; i < count; i++)
669                         array[i] = fdt32_to_cpu(cell[i]);
670         }
671         return err;
672 }
673
674 int fdtdec_get_int_array_count(const void *blob, int node,
675                                const char *prop_name, u32 *array, int count)
676 {
677         const u32 *cell;
678         int len, elems;
679         int i;
680
681         debug("%s: %s\n", __func__, prop_name);
682         cell = fdt_getprop(blob, node, prop_name, &len);
683         if (!cell)
684                 return -FDT_ERR_NOTFOUND;
685         elems = len / sizeof(u32);
686         if (count > elems)
687                 count = elems;
688         for (i = 0; i < count; i++)
689                 array[i] = fdt32_to_cpu(cell[i]);
690
691         return count;
692 }
693
694 const u32 *fdtdec_locate_array(const void *blob, int node,
695                                const char *prop_name, int count)
696 {
697         const u32 *cell;
698         int err;
699
700         cell = get_prop_check_min_len(blob, node, prop_name,
701                                       sizeof(u32) * count, &err);
702         return err ? NULL : cell;
703 }
704
705 int fdtdec_get_bool(const void *blob, int node, const char *prop_name)
706 {
707         const s32 *cell;
708         int len;
709
710         debug("%s: %s\n", __func__, prop_name);
711         cell = fdt_getprop(blob, node, prop_name, &len);
712         return cell != NULL;
713 }
714
715 int fdtdec_parse_phandle_with_args(const void *blob, int src_node,
716                                    const char *list_name,
717                                    const char *cells_name,
718                                    int cell_count, int index,
719                                    struct fdtdec_phandle_args *out_args)
720 {
721         const __be32 *list, *list_end;
722         int rc = 0, size, cur_index = 0;
723         uint32_t count = 0;
724         int node = -1;
725         int phandle;
726
727         /* Retrieve the phandle list property */
728         list = fdt_getprop(blob, src_node, list_name, &size);
729         if (!list)
730                 return -ENOENT;
731         list_end = list + size / sizeof(*list);
732
733         /* Loop over the phandles until all the requested entry is found */
734         while (list < list_end) {
735                 rc = -EINVAL;
736                 count = 0;
737
738                 /*
739                  * If phandle is 0, then it is an empty entry with no
740                  * arguments.  Skip forward to the next entry.
741                  */
742                 phandle = be32_to_cpup(list++);
743                 if (phandle) {
744                         /*
745                          * Find the provider node and parse the #*-cells
746                          * property to determine the argument length.
747                          *
748                          * This is not needed if the cell count is hard-coded
749                          * (i.e. cells_name not set, but cell_count is set),
750                          * except when we're going to return the found node
751                          * below.
752                          */
753                         if (cells_name || cur_index == index) {
754                                 node = fdt_node_offset_by_phandle(blob,
755                                                                   phandle);
756                                 if (!node) {
757                                         debug("%s: could not find phandle\n",
758                                               fdt_get_name(blob, src_node,
759                                                            NULL));
760                                         goto err;
761                                 }
762                         }
763
764                         if (cells_name) {
765                                 count = fdtdec_get_int(blob, node, cells_name,
766                                                        -1);
767                                 if (count == -1) {
768                                         debug("%s: could not get %s for %s\n",
769                                               fdt_get_name(blob, src_node,
770                                                            NULL),
771                                               cells_name,
772                                               fdt_get_name(blob, node,
773                                                            NULL));
774                                         goto err;
775                                 }
776                         } else {
777                                 count = cell_count;
778                         }
779
780                         /*
781                          * Make sure that the arguments actually fit in the
782                          * remaining property data length
783                          */
784                         if (list + count > list_end) {
785                                 debug("%s: arguments longer than property\n",
786                                       fdt_get_name(blob, src_node, NULL));
787                                 goto err;
788                         }
789                 }
790
791                 /*
792                  * All of the error cases above bail out of the loop, so at
793                  * this point, the parsing is successful. If the requested
794                  * index matches, then fill the out_args structure and return,
795                  * or return -ENOENT for an empty entry.
796                  */
797                 rc = -ENOENT;
798                 if (cur_index == index) {
799                         if (!phandle)
800                                 goto err;
801
802                         if (out_args) {
803                                 int i;
804
805                                 if (count > MAX_PHANDLE_ARGS) {
806                                         debug("%s: too many arguments %d\n",
807                                               fdt_get_name(blob, src_node,
808                                                            NULL), count);
809                                         count = MAX_PHANDLE_ARGS;
810                                 }
811                                 out_args->node = node;
812                                 out_args->args_count = count;
813                                 for (i = 0; i < count; i++) {
814                                         out_args->args[i] =
815                                                         be32_to_cpup(list++);
816                                 }
817                         }
818
819                         /* Found it! return success */
820                         return 0;
821                 }
822
823                 node = -1;
824                 list += count;
825                 cur_index++;
826         }
827
828         /*
829          * Result will be one of:
830          * -ENOENT : index is for empty phandle
831          * -EINVAL : parsing error on data
832          * [1..n]  : Number of phandle (count mode; when index = -1)
833          */
834         rc = index < 0 ? cur_index : -ENOENT;
835  err:
836         return rc;
837 }
838
839 int fdtdec_get_child_count(const void *blob, int node)
840 {
841         int subnode;
842         int num = 0;
843
844         fdt_for_each_subnode(subnode, blob, node)
845                 num++;
846
847         return num;
848 }
849
850 int fdtdec_get_byte_array(const void *blob, int node, const char *prop_name,
851                 u8 *array, int count)
852 {
853         const u8 *cell;
854         int err;
855
856         cell = get_prop_check_min_len(blob, node, prop_name, count, &err);
857         if (!err)
858                 memcpy(array, cell, count);
859         return err;
860 }
861
862 const u8 *fdtdec_locate_byte_array(const void *blob, int node,
863                              const char *prop_name, int count)
864 {
865         const u8 *cell;
866         int err;
867
868         cell = get_prop_check_min_len(blob, node, prop_name, count, &err);
869         if (err)
870                 return NULL;
871         return cell;
872 }
873
874 int fdtdec_get_config_int(const void *blob, const char *prop_name,
875                 int default_val)
876 {
877         int config_node;
878
879         debug("%s: %s\n", __func__, prop_name);
880         config_node = fdt_path_offset(blob, "/config");
881         if (config_node < 0)
882                 return default_val;
883         return fdtdec_get_int(blob, config_node, prop_name, default_val);
884 }
885
886 int fdtdec_get_config_bool(const void *blob, const char *prop_name)
887 {
888         int config_node;
889         const void *prop;
890
891         debug("%s: %s\n", __func__, prop_name);
892         config_node = fdt_path_offset(blob, "/config");
893         if (config_node < 0)
894                 return 0;
895         prop = fdt_get_property(blob, config_node, prop_name, NULL);
896
897         return prop != NULL;
898 }
899
900 char *fdtdec_get_config_string(const void *blob, const char *prop_name)
901 {
902         const char *nodep;
903         int nodeoffset;
904         int len;
905
906         debug("%s: %s\n", __func__, prop_name);
907         nodeoffset = fdt_path_offset(blob, "/config");
908         if (nodeoffset < 0)
909                 return NULL;
910
911         nodep = fdt_getprop(blob, nodeoffset, prop_name, &len);
912         if (!nodep)
913                 return NULL;
914
915         return (char *)nodep;
916 }
917
918 int fdtdec_decode_region(const void *blob, int node, const char *prop_name,
919                          fdt_addr_t *basep, fdt_size_t *sizep)
920 {
921         const fdt_addr_t *cell;
922         int len;
923
924         debug("%s: %s: %s\n", __func__, fdt_get_name(blob, node, NULL),
925               prop_name);
926         cell = fdt_getprop(blob, node, prop_name, &len);
927         if (!cell || (len < sizeof(fdt_addr_t) * 2)) {
928                 debug("cell=%p, len=%d\n", cell, len);
929                 return -1;
930         }
931
932         *basep = fdt_addr_to_cpu(*cell);
933         *sizep = fdt_size_to_cpu(cell[1]);
934         debug("%s: base=%08lx, size=%lx\n", __func__, (ulong)*basep,
935               (ulong)*sizep);
936
937         return 0;
938 }
939
940 u64 fdtdec_get_number(const fdt32_t *ptr, unsigned int cells)
941 {
942         u64 number = 0;
943
944         while (cells--)
945                 number = (number << 32) | fdt32_to_cpu(*ptr++);
946
947         return number;
948 }
949
950 int fdt_get_resource(const void *fdt, int node, const char *property,
951                      unsigned int index, struct fdt_resource *res)
952 {
953         const fdt32_t *ptr, *end;
954         int na, ns, len, parent;
955         unsigned int i = 0;
956
957         parent = fdt_parent_offset(fdt, node);
958         if (parent < 0)
959                 return parent;
960
961         na = fdt_address_cells(fdt, parent);
962         ns = fdt_size_cells(fdt, parent);
963
964         ptr = fdt_getprop(fdt, node, property, &len);
965         if (!ptr)
966                 return len;
967
968         end = ptr + len / sizeof(*ptr);
969
970         while (ptr + na + ns <= end) {
971                 if (i == index) {
972                         res->start = res->end = fdtdec_get_number(ptr, na);
973                         res->end += fdtdec_get_number(&ptr[na], ns) - 1;
974                         return 0;
975                 }
976
977                 ptr += na + ns;
978                 i++;
979         }
980
981         return -FDT_ERR_NOTFOUND;
982 }
983
984 int fdt_get_named_resource(const void *fdt, int node, const char *property,
985                            const char *prop_names, const char *name,
986                            struct fdt_resource *res)
987 {
988         int index;
989
990         index = fdt_stringlist_search(fdt, node, prop_names, name);
991         if (index < 0)
992                 return index;
993
994         return fdt_get_resource(fdt, node, property, index, res);
995 }
996
997 int fdtdec_decode_memory_region(const void *blob, int config_node,
998                                 const char *mem_type, const char *suffix,
999                                 fdt_addr_t *basep, fdt_size_t *sizep)
1000 {
1001         char prop_name[50];
1002         const char *mem;
1003         fdt_size_t size, offset_size;
1004         fdt_addr_t base, offset;
1005         int node;
1006
1007         if (config_node == -1) {
1008                 config_node = fdt_path_offset(blob, "/config");
1009                 if (config_node < 0) {
1010                         debug("%s: Cannot find /config node\n", __func__);
1011                         return -ENOENT;
1012                 }
1013         }
1014         if (!suffix)
1015                 suffix = "";
1016
1017         snprintf(prop_name, sizeof(prop_name), "%s-memory%s", mem_type,
1018                  suffix);
1019         mem = fdt_getprop(blob, config_node, prop_name, NULL);
1020         if (!mem) {
1021                 debug("%s: No memory type for '%s', using /memory\n", __func__,
1022                       prop_name);
1023                 mem = "/memory";
1024         }
1025
1026         node = fdt_path_offset(blob, mem);
1027         if (node < 0) {
1028                 debug("%s: Failed to find node '%s': %s\n", __func__, mem,
1029                       fdt_strerror(node));
1030                 return -ENOENT;
1031         }
1032
1033         /*
1034          * Not strictly correct - the memory may have multiple banks. We just
1035          * use the first
1036          */
1037         if (fdtdec_decode_region(blob, node, "reg", &base, &size)) {
1038                 debug("%s: Failed to decode memory region %s\n", __func__,
1039                       mem);
1040                 return -EINVAL;
1041         }
1042
1043         snprintf(prop_name, sizeof(prop_name), "%s-offset%s", mem_type,
1044                  suffix);
1045         if (fdtdec_decode_region(blob, config_node, prop_name, &offset,
1046                                  &offset_size)) {
1047                 debug("%s: Failed to decode memory region '%s'\n", __func__,
1048                       prop_name);
1049                 return -EINVAL;
1050         }
1051
1052         *basep = base + offset;
1053         *sizep = offset_size;
1054
1055         return 0;
1056 }
1057
1058 static int decode_timing_property(const void *blob, int node, const char *name,
1059                                   struct timing_entry *result)
1060 {
1061         int length, ret = 0;
1062         const u32 *prop;
1063
1064         prop = fdt_getprop(blob, node, name, &length);
1065         if (!prop) {
1066                 debug("%s: could not find property %s\n",
1067                       fdt_get_name(blob, node, NULL), name);
1068                 return length;
1069         }
1070
1071         if (length == sizeof(u32)) {
1072                 result->typ = fdtdec_get_int(blob, node, name, 0);
1073                 result->min = result->typ;
1074                 result->max = result->typ;
1075         } else {
1076                 ret = fdtdec_get_int_array(blob, node, name, &result->min, 3);
1077         }
1078
1079         return ret;
1080 }
1081
1082 int fdtdec_decode_display_timing(const void *blob, int parent, int index,
1083                                  struct display_timing *dt)
1084 {
1085         int i, node, timings_node;
1086         u32 val = 0;
1087         int ret = 0;
1088
1089         timings_node = fdt_subnode_offset(blob, parent, "display-timings");
1090         if (timings_node < 0)
1091                 return timings_node;
1092
1093         for (i = 0, node = fdt_first_subnode(blob, timings_node);
1094              node > 0 && i != index;
1095              node = fdt_next_subnode(blob, node))
1096                 i++;
1097
1098         if (node < 0)
1099                 return node;
1100
1101         memset(dt, 0, sizeof(*dt));
1102
1103         ret |= decode_timing_property(blob, node, "hback-porch",
1104                                       &dt->hback_porch);
1105         ret |= decode_timing_property(blob, node, "hfront-porch",
1106                                       &dt->hfront_porch);
1107         ret |= decode_timing_property(blob, node, "hactive", &dt->hactive);
1108         ret |= decode_timing_property(blob, node, "hsync-len", &dt->hsync_len);
1109         ret |= decode_timing_property(blob, node, "vback-porch",
1110                                       &dt->vback_porch);
1111         ret |= decode_timing_property(blob, node, "vfront-porch",
1112                                       &dt->vfront_porch);
1113         ret |= decode_timing_property(blob, node, "vactive", &dt->vactive);
1114         ret |= decode_timing_property(blob, node, "vsync-len", &dt->vsync_len);
1115         ret |= decode_timing_property(blob, node, "clock-frequency",
1116                                       &dt->pixelclock);
1117
1118         dt->flags = 0;
1119         val = fdtdec_get_int(blob, node, "vsync-active", -1);
1120         if (val != -1) {
1121                 dt->flags |= val ? DISPLAY_FLAGS_VSYNC_HIGH :
1122                                 DISPLAY_FLAGS_VSYNC_LOW;
1123         }
1124         val = fdtdec_get_int(blob, node, "hsync-active", -1);
1125         if (val != -1) {
1126                 dt->flags |= val ? DISPLAY_FLAGS_HSYNC_HIGH :
1127                                 DISPLAY_FLAGS_HSYNC_LOW;
1128         }
1129         val = fdtdec_get_int(blob, node, "de-active", -1);
1130         if (val != -1) {
1131                 dt->flags |= val ? DISPLAY_FLAGS_DE_HIGH :
1132                                 DISPLAY_FLAGS_DE_LOW;
1133         }
1134         val = fdtdec_get_int(blob, node, "pixelclk-active", -1);
1135         if (val != -1) {
1136                 dt->flags |= val ? DISPLAY_FLAGS_PIXDATA_POSEDGE :
1137                                 DISPLAY_FLAGS_PIXDATA_NEGEDGE;
1138         }
1139
1140         if (fdtdec_get_bool(blob, node, "interlaced"))
1141                 dt->flags |= DISPLAY_FLAGS_INTERLACED;
1142         if (fdtdec_get_bool(blob, node, "doublescan"))
1143                 dt->flags |= DISPLAY_FLAGS_DOUBLESCAN;
1144         if (fdtdec_get_bool(blob, node, "doubleclk"))
1145                 dt->flags |= DISPLAY_FLAGS_DOUBLECLK;
1146
1147         return ret;
1148 }
1149
1150 int fdtdec_setup_memory_size(void)
1151 {
1152         int ret, mem;
1153         struct fdt_resource res;
1154
1155         mem = fdt_path_offset(gd->fdt_blob, "/memory");
1156         if (mem < 0) {
1157                 debug("%s: Missing /memory node\n", __func__);
1158                 return -EINVAL;
1159         }
1160
1161         ret = fdt_get_resource(gd->fdt_blob, mem, "reg", 0, &res);
1162         if (ret != 0) {
1163                 debug("%s: Unable to decode first memory bank\n", __func__);
1164                 return -EINVAL;
1165         }
1166
1167         gd->ram_size = (phys_size_t)(res.end - res.start + 1);
1168         debug("%s: Initial DRAM size %llx\n", __func__,
1169               (unsigned long long)gd->ram_size);
1170
1171         return 0;
1172 }
1173
1174 #if defined(CONFIG_NR_DRAM_BANKS)
1175 int fdtdec_setup_memory_banksize(void)
1176 {
1177         int bank, ret, mem;
1178         struct fdt_resource res;
1179
1180         mem = fdt_path_offset(gd->fdt_blob, "/memory");
1181         if (mem < 0) {
1182                 debug("%s: Missing /memory node\n", __func__);
1183                 return -EINVAL;
1184         }
1185
1186         for (bank = 0; bank < CONFIG_NR_DRAM_BANKS; bank++) {
1187                 ret = fdt_get_resource(gd->fdt_blob, mem, "reg", bank, &res);
1188                 if (ret == -FDT_ERR_NOTFOUND)
1189                         break;
1190                 if (ret != 0)
1191                         return -EINVAL;
1192
1193                 gd->bd->bi_dram[bank].start = (phys_addr_t)res.start;
1194                 gd->bd->bi_dram[bank].size =
1195                         (phys_size_t)(res.end - res.start + 1);
1196
1197                 debug("%s: DRAM Bank #%d: start = 0x%llx, size = 0x%llx\n",
1198                       __func__, bank,
1199                       (unsigned long long)gd->bd->bi_dram[bank].start,
1200                       (unsigned long long)gd->bd->bi_dram[bank].size);
1201         }
1202
1203         return 0;
1204 }
1205 #endif
1206
1207 #if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1208 # if CONFIG_IS_ENABLED(MULTI_DTB_FIT_GZIP) ||\
1209         CONFIG_IS_ENABLED(MULTI_DTB_FIT_LZO)
1210 static int uncompress_blob(const void *src, ulong sz_src, void **dstp)
1211 {
1212         size_t sz_out = CONFIG_SPL_MULTI_DTB_FIT_UNCOMPRESS_SZ;
1213         ulong sz_in = sz_src;
1214         void *dst;
1215         int rc;
1216
1217         if (CONFIG_IS_ENABLED(GZIP))
1218                 if (gzip_parse_header(src, sz_in) < 0)
1219                         return -1;
1220         if (CONFIG_IS_ENABLED(LZO))
1221                 if (!lzop_is_valid_header(src))
1222                         return -EBADMSG;
1223
1224         if (CONFIG_IS_ENABLED(MULTI_DTB_FIT_DYN_ALLOC)) {
1225                 dst = malloc(sz_out);
1226                 if (!dst) {
1227                         puts("uncompress_blob: Unable to allocate memory\n");
1228                         return -ENOMEM;
1229                 }
1230         } else  {
1231 #  if CONFIG_IS_ENABLED(MULTI_DTB_FIT_USER_DEFINED_AREA)
1232                 dst = (void *)CONFIG_VAL(MULTI_DTB_FIT_USER_DEF_ADDR);
1233 #  else
1234                 return -ENOTSUPP;
1235 #  endif
1236         }
1237
1238         if (CONFIG_IS_ENABLED(GZIP))
1239                 rc = gunzip(dst, sz_out, (u8 *)src, &sz_in);
1240         else if (CONFIG_IS_ENABLED(LZO))
1241                 rc = lzop_decompress(src, sz_in, dst, &sz_out);
1242
1243         if (rc < 0) {
1244                 /* not a valid compressed blob */
1245                 puts("uncompress_blob: Unable to uncompress\n");
1246                 if (CONFIG_IS_ENABLED(MULTI_DTB_FIT_DYN_ALLOC))
1247                         free(dst);
1248                 return -EBADMSG;
1249         }
1250         *dstp = dst;
1251         return 0;
1252 }
1253 # else
1254 static int uncompress_blob(const void *src, ulong sz_src, void **dstp)
1255 {
1256         return -ENOTSUPP;
1257 }
1258 # endif
1259 #endif
1260
1261 int fdtdec_setup(void)
1262 {
1263 #if CONFIG_IS_ENABLED(OF_CONTROL)
1264 # if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1265         void *fdt_blob;
1266 # endif
1267 # ifdef CONFIG_OF_EMBED
1268         /* Get a pointer to the FDT */
1269         gd->fdt_blob = __dtb_dt_begin;
1270 # elif defined CONFIG_OF_SEPARATE
1271 #  ifdef CONFIG_SPL_BUILD
1272         /* FDT is at end of BSS unless it is in a different memory region */
1273         if (IS_ENABLED(CONFIG_SPL_SEPARATE_BSS))
1274                 gd->fdt_blob = (ulong *)&_image_binary_end;
1275         else
1276                 gd->fdt_blob = (ulong *)&__bss_end;
1277 #  else
1278         /* FDT is at end of image */
1279         gd->fdt_blob = (ulong *)&_end;
1280 #  endif
1281 # elif defined(CONFIG_OF_BOARD)
1282         /* Allow the board to override the fdt address. */
1283         gd->fdt_blob = board_fdt_blob_setup();
1284 # elif defined(CONFIG_OF_HOSTFILE)
1285         if (sandbox_read_fdt_from_file()) {
1286                 puts("Failed to read control FDT\n");
1287                 return -1;
1288         }
1289 # endif
1290 # ifndef CONFIG_SPL_BUILD
1291         /* Allow the early environment to override the fdt address */
1292         gd->fdt_blob = (void *)env_get_ulong("fdtcontroladdr", 16,
1293                                                 (uintptr_t)gd->fdt_blob);
1294 # endif
1295
1296 # if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1297         /*
1298          * Try and uncompress the blob.
1299          * Unfortunately there is no way to know how big the input blob really
1300          * is. So let us set the maximum input size arbitrarily high. 16MB
1301          * ought to be more than enough for packed DTBs.
1302          */
1303         if (uncompress_blob(gd->fdt_blob, 0x1000000, &fdt_blob) == 0)
1304                 gd->fdt_blob = fdt_blob;
1305
1306         /*
1307          * Check if blob is a FIT images containings DTBs.
1308          * If so, pick the most relevant
1309          */
1310         fdt_blob = locate_dtb_in_fit(gd->fdt_blob);
1311         if (fdt_blob)
1312                 gd->fdt_blob = fdt_blob;
1313 # endif
1314 #endif
1315
1316         return fdtdec_prepare_fdt();
1317 }
1318
1319 #endif /* !USE_HOSTCC */