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