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