common: Drop net.h from common header
[oweals/u-boot.git] / lib / fdtdec.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2011 The Chromium OS Authors.
4  */
5
6 #ifndef USE_HOSTCC
7 #include <common.h>
8 #include <boot_fit.h>
9 #include <dm.h>
10 #include <hang.h>
11 #include <init.h>
12 #include <malloc.h>
13 #include <net.h>
14 #include <dm/of_extra.h>
15 #include <env.h>
16 #include <errno.h>
17 #include <fdtdec.h>
18 #include <fdt_support.h>
19 #include <gzip.h>
20 #include <mapmem.h>
21 #include <linux/libfdt.h>
22 #include <serial.h>
23 #include <asm/sections.h>
24 #include <linux/ctype.h>
25 #include <linux/lzo.h>
26
27 DECLARE_GLOBAL_DATA_PTR;
28
29 /*
30  * Here are the type we know about. One day we might allow drivers to
31  * register. For now we just put them here. The COMPAT macro allows us to
32  * turn this into a sparse list later, and keeps the ID with the name.
33  *
34  * NOTE: This list is basically a TODO list for things that need to be
35  * converted to driver model. So don't add new things here unless there is a
36  * good reason why driver-model conversion is infeasible. Examples include
37  * things which are used before driver model is available.
38  */
39 #define COMPAT(id, name) name
40 static const char * const compat_names[COMPAT_COUNT] = {
41         COMPAT(UNKNOWN, "<none>"),
42         COMPAT(NVIDIA_TEGRA20_EMC, "nvidia,tegra20-emc"),
43         COMPAT(NVIDIA_TEGRA20_EMC_TABLE, "nvidia,tegra20-emc-table"),
44         COMPAT(NVIDIA_TEGRA20_NAND, "nvidia,tegra20-nand"),
45         COMPAT(NVIDIA_TEGRA124_XUSB_PADCTL, "nvidia,tegra124-xusb-padctl"),
46         COMPAT(NVIDIA_TEGRA210_XUSB_PADCTL, "nvidia,tegra210-xusb-padctl"),
47         COMPAT(SMSC_LAN9215, "smsc,lan9215"),
48         COMPAT(SAMSUNG_EXYNOS5_SROMC, "samsung,exynos-sromc"),
49         COMPAT(SAMSUNG_EXYNOS_USB_PHY, "samsung,exynos-usb-phy"),
50         COMPAT(SAMSUNG_EXYNOS5_USB3_PHY, "samsung,exynos5250-usb3-phy"),
51         COMPAT(SAMSUNG_EXYNOS_TMU, "samsung,exynos-tmu"),
52         COMPAT(SAMSUNG_EXYNOS_MIPI_DSI, "samsung,exynos-mipi-dsi"),
53         COMPAT(SAMSUNG_EXYNOS_DWMMC, "samsung,exynos-dwmmc"),
54         COMPAT(GENERIC_SPI_FLASH, "jedec,spi-nor"),
55         COMPAT(SAMSUNG_EXYNOS_SYSMMU, "samsung,sysmmu-v3.3"),
56         COMPAT(INTEL_MICROCODE, "intel,microcode"),
57         COMPAT(INTEL_QRK_MRC, "intel,quark-mrc"),
58         COMPAT(ALTERA_SOCFPGA_DWMAC, "altr,socfpga-stmmac"),
59         COMPAT(ALTERA_SOCFPGA_DWMMC, "altr,socfpga-dw-mshc"),
60         COMPAT(ALTERA_SOCFPGA_DWC2USB, "snps,dwc2"),
61         COMPAT(INTEL_BAYTRAIL_FSP, "intel,baytrail-fsp"),
62         COMPAT(INTEL_BAYTRAIL_FSP_MDP, "intel,baytrail-fsp-mdp"),
63         COMPAT(INTEL_IVYBRIDGE_FSP, "intel,ivybridge-fsp"),
64         COMPAT(COMPAT_SUNXI_NAND, "allwinner,sun4i-a10-nand"),
65         COMPAT(ALTERA_SOCFPGA_CLK, "altr,clk-mgr"),
66         COMPAT(ALTERA_SOCFPGA_PINCTRL_SINGLE, "pinctrl-single"),
67         COMPAT(ALTERA_SOCFPGA_H2F_BRG, "altr,socfpga-hps2fpga-bridge"),
68         COMPAT(ALTERA_SOCFPGA_LWH2F_BRG, "altr,socfpga-lwhps2fpga-bridge"),
69         COMPAT(ALTERA_SOCFPGA_F2H_BRG, "altr,socfpga-fpga2hps-bridge"),
70         COMPAT(ALTERA_SOCFPGA_F2SDR0, "altr,socfpga-fpga2sdram0-bridge"),
71         COMPAT(ALTERA_SOCFPGA_F2SDR1, "altr,socfpga-fpga2sdram1-bridge"),
72         COMPAT(ALTERA_SOCFPGA_F2SDR2, "altr,socfpga-fpga2sdram2-bridge"),
73         COMPAT(ALTERA_SOCFPGA_FPGA0, "altr,socfpga-a10-fpga-mgr"),
74         COMPAT(ALTERA_SOCFPGA_NOC, "altr,socfpga-a10-noc"),
75         COMPAT(ALTERA_SOCFPGA_CLK_INIT, "altr,socfpga-a10-clk-init")
76 };
77
78 const char *fdtdec_get_compatible(enum fdt_compat_id id)
79 {
80         /* We allow reading of the 'unknown' ID for testing purposes */
81         assert(id >= 0 && id < COMPAT_COUNT);
82         return compat_names[id];
83 }
84
85 fdt_addr_t fdtdec_get_addr_size_fixed(const void *blob, int node,
86                                       const char *prop_name, int index, int na,
87                                       int ns, fdt_size_t *sizep,
88                                       bool translate)
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         prop = fdt_getprop(blob, node, prop_name, &len);
98         if (!prop) {
99                 debug("(not found)\n");
100                 return FDT_ADDR_T_NONE;
101         }
102         prop_end = prop + (len / sizeof(*prop));
103
104         prop_addr = prop + (index * (na + ns));
105         prop_size = prop_addr + na;
106         prop_after_size = prop_size + ns;
107         if (prop_after_size > prop_end) {
108                 debug("(not enough data: expected >= %d cells, got %d cells)\n",
109                       (u32)(prop_after_size - prop), ((u32)(prop_end - prop)));
110                 return FDT_ADDR_T_NONE;
111         }
112
113 #if CONFIG_IS_ENABLED(OF_TRANSLATE)
114         if (translate)
115                 addr = fdt_translate_address(blob, node, prop_addr);
116         else
117 #endif
118                 addr = fdtdec_get_number(prop_addr, na);
119
120         if (sizep) {
121                 *sizep = fdtdec_get_number(prop_size, ns);
122                 debug("addr=%08llx, size=%llx\n", (unsigned long long)addr,
123                       (unsigned long long)*sizep);
124         } else {
125                 debug("addr=%08llx\n", (unsigned long long)addr);
126         }
127
128         return addr;
129 }
130
131 fdt_addr_t fdtdec_get_addr_size_auto_parent(const void *blob, int parent,
132                                             int node, const char *prop_name,
133                                             int index, fdt_size_t *sizep,
134                                             bool translate)
135 {
136         int na, ns;
137
138         debug("%s: ", __func__);
139
140         na = fdt_address_cells(blob, parent);
141         if (na < 1) {
142                 debug("(bad #address-cells)\n");
143                 return FDT_ADDR_T_NONE;
144         }
145
146         ns = fdt_size_cells(blob, parent);
147         if (ns < 0) {
148                 debug("(bad #size-cells)\n");
149                 return FDT_ADDR_T_NONE;
150         }
151
152         debug("na=%d, ns=%d, ", na, ns);
153
154         return fdtdec_get_addr_size_fixed(blob, node, prop_name, index, na,
155                                           ns, sizep, translate);
156 }
157
158 fdt_addr_t fdtdec_get_addr_size_auto_noparent(const void *blob, int node,
159                                               const char *prop_name, int index,
160                                               fdt_size_t *sizep,
161                                               bool translate)
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, translate);
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, false);
185 }
186
187 fdt_addr_t fdtdec_get_addr(const void *blob, int node, const char *prop_name)
188 {
189         return fdtdec_get_addr_size(blob, node, prop_name, NULL);
190 }
191
192 #if CONFIG_IS_ENABLED(PCI) && defined(CONFIG_DM_PCI)
193 int fdtdec_get_pci_vendev(const void *blob, int node, u16 *vendor, u16 *device)
194 {
195         const char *list, *end;
196         int len;
197
198         list = fdt_getprop(blob, node, "compatible", &len);
199         if (!list)
200                 return -ENOENT;
201
202         end = list + len;
203         while (list < end) {
204                 len = strlen(list);
205                 if (len >= strlen("pciVVVV,DDDD")) {
206                         char *s = strstr(list, "pci");
207
208                         /*
209                          * check if the string is something like pciVVVV,DDDD.RR
210                          * or just pciVVVV,DDDD
211                          */
212                         if (s && s[7] == ',' &&
213                             (s[12] == '.' || s[12] == 0)) {
214                                 s += 3;
215                                 *vendor = simple_strtol(s, NULL, 16);
216
217                                 s += 5;
218                                 *device = simple_strtol(s, NULL, 16);
219
220                                 return 0;
221                         }
222                 }
223                 list += (len + 1);
224         }
225
226         return -ENOENT;
227 }
228
229 int fdtdec_get_pci_bar32(const struct udevice *dev, struct fdt_pci_addr *addr,
230                          u32 *bar)
231 {
232         int barnum;
233
234         /* extract the bar number from fdt_pci_addr */
235         barnum = addr->phys_hi & 0xff;
236         if (barnum < PCI_BASE_ADDRESS_0 || barnum > PCI_CARDBUS_CIS)
237                 return -EINVAL;
238
239         barnum = (barnum - PCI_BASE_ADDRESS_0) / 4;
240         *bar = dm_pci_read_bar32(dev, barnum);
241
242         return 0;
243 }
244 #endif
245
246 uint64_t fdtdec_get_uint64(const void *blob, int node, const char *prop_name,
247                            uint64_t default_val)
248 {
249         const unaligned_fdt64_t *cell64;
250         int length;
251
252         cell64 = fdt_getprop(blob, node, prop_name, &length);
253         if (!cell64 || length < sizeof(*cell64))
254                 return default_val;
255
256         return fdt64_to_cpu(*cell64);
257 }
258
259 int fdtdec_get_is_enabled(const void *blob, int node)
260 {
261         const char *cell;
262
263         /*
264          * It should say "okay", so only allow that. Some fdts use "ok" but
265          * this is a bug. Please fix your device tree source file. See here
266          * for discussion:
267          *
268          * http://www.mail-archive.com/u-boot@lists.denx.de/msg71598.html
269          */
270         cell = fdt_getprop(blob, node, "status", NULL);
271         if (cell)
272                 return strcmp(cell, "okay") == 0;
273         return 1;
274 }
275
276 enum fdt_compat_id fdtdec_lookup(const void *blob, int node)
277 {
278         enum fdt_compat_id id;
279
280         /* Search our drivers */
281         for (id = COMPAT_UNKNOWN; id < COMPAT_COUNT; id++)
282                 if (fdt_node_check_compatible(blob, node,
283                                               compat_names[id]) == 0)
284                         return id;
285         return COMPAT_UNKNOWN;
286 }
287
288 int fdtdec_next_compatible(const void *blob, int node, enum fdt_compat_id id)
289 {
290         return fdt_node_offset_by_compatible(blob, node, compat_names[id]);
291 }
292
293 int fdtdec_next_compatible_subnode(const void *blob, int node,
294                                    enum fdt_compat_id id, int *depthp)
295 {
296         do {
297                 node = fdt_next_node(blob, node, depthp);
298         } while (*depthp > 1);
299
300         /* If this is a direct subnode, and compatible, return it */
301         if (*depthp == 1 && 0 == fdt_node_check_compatible(
302                                                 blob, node, compat_names[id]))
303                 return node;
304
305         return -FDT_ERR_NOTFOUND;
306 }
307
308 int fdtdec_next_alias(const void *blob, const char *name, enum fdt_compat_id id,
309                       int *upto)
310 {
311 #define MAX_STR_LEN 20
312         char str[MAX_STR_LEN + 20];
313         int node, err;
314
315         /* snprintf() is not available */
316         assert(strlen(name) < MAX_STR_LEN);
317         sprintf(str, "%.*s%d", MAX_STR_LEN, name, *upto);
318         node = fdt_path_offset(blob, str);
319         if (node < 0)
320                 return node;
321         err = fdt_node_check_compatible(blob, node, compat_names[id]);
322         if (err < 0)
323                 return err;
324         if (err)
325                 return -FDT_ERR_NOTFOUND;
326         (*upto)++;
327         return node;
328 }
329
330 int fdtdec_find_aliases_for_id(const void *blob, const char *name,
331                                enum fdt_compat_id id, int *node_list,
332                                int maxcount)
333 {
334         memset(node_list, '\0', sizeof(*node_list) * maxcount);
335
336         return fdtdec_add_aliases_for_id(blob, name, id, node_list, maxcount);
337 }
338
339 /* TODO: Can we tighten this code up a little? */
340 int fdtdec_add_aliases_for_id(const void *blob, const char *name,
341                               enum fdt_compat_id id, int *node_list,
342                               int maxcount)
343 {
344         int name_len = strlen(name);
345         int nodes[maxcount];
346         int num_found = 0;
347         int offset, node;
348         int alias_node;
349         int count;
350         int i, j;
351
352         /* find the alias node if present */
353         alias_node = fdt_path_offset(blob, "/aliases");
354
355         /*
356          * start with nothing, and we can assume that the root node can't
357          * match
358          */
359         memset(nodes, '\0', sizeof(nodes));
360
361         /* First find all the compatible nodes */
362         for (node = count = 0; node >= 0 && count < maxcount;) {
363                 node = fdtdec_next_compatible(blob, node, id);
364                 if (node >= 0)
365                         nodes[count++] = node;
366         }
367         if (node >= 0)
368                 debug("%s: warning: maxcount exceeded with alias '%s'\n",
369                       __func__, name);
370
371         /* Now find all the aliases */
372         for (offset = fdt_first_property_offset(blob, alias_node);
373                         offset > 0;
374                         offset = fdt_next_property_offset(blob, offset)) {
375                 const struct fdt_property *prop;
376                 const char *path;
377                 int number;
378                 int found;
379
380                 node = 0;
381                 prop = fdt_get_property_by_offset(blob, offset, NULL);
382                 path = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
383                 if (prop->len && 0 == strncmp(path, name, name_len))
384                         node = fdt_path_offset(blob, prop->data);
385                 if (node <= 0)
386                         continue;
387
388                 /* Get the alias number */
389                 number = simple_strtoul(path + name_len, NULL, 10);
390                 if (number < 0 || number >= maxcount) {
391                         debug("%s: warning: alias '%s' is out of range\n",
392                               __func__, path);
393                         continue;
394                 }
395
396                 /* Make sure the node we found is actually in our list! */
397                 found = -1;
398                 for (j = 0; j < count; j++)
399                         if (nodes[j] == node) {
400                                 found = j;
401                                 break;
402                         }
403
404                 if (found == -1) {
405                         debug("%s: warning: alias '%s' points to a node "
406                                 "'%s' that is missing or is not compatible "
407                                 " with '%s'\n", __func__, path,
408                                 fdt_get_name(blob, node, NULL),
409                                compat_names[id]);
410                         continue;
411                 }
412
413                 /*
414                  * Add this node to our list in the right place, and mark
415                  * it as done.
416                  */
417                 if (fdtdec_get_is_enabled(blob, node)) {
418                         if (node_list[number]) {
419                                 debug("%s: warning: alias '%s' requires that "
420                                       "a node be placed in the list in a "
421                                       "position which is already filled by "
422                                       "node '%s'\n", __func__, path,
423                                       fdt_get_name(blob, node, NULL));
424                                 continue;
425                         }
426                         node_list[number] = node;
427                         if (number >= num_found)
428                                 num_found = number + 1;
429                 }
430                 nodes[found] = 0;
431         }
432
433         /* Add any nodes not mentioned by an alias */
434         for (i = j = 0; i < maxcount; i++) {
435                 if (!node_list[i]) {
436                         for (; j < maxcount; j++)
437                                 if (nodes[j] &&
438                                     fdtdec_get_is_enabled(blob, nodes[j]))
439                                         break;
440
441                         /* Have we run out of nodes to add? */
442                         if (j == maxcount)
443                                 break;
444
445                         assert(!node_list[i]);
446                         node_list[i] = nodes[j++];
447                         if (i >= num_found)
448                                 num_found = i + 1;
449                 }
450         }
451
452         return num_found;
453 }
454
455 int fdtdec_get_alias_seq(const void *blob, const char *base, int offset,
456                          int *seqp)
457 {
458         int base_len = strlen(base);
459         const char *find_name;
460         int find_namelen;
461         int prop_offset;
462         int aliases;
463
464         find_name = fdt_get_name(blob, offset, &find_namelen);
465         debug("Looking for '%s' at %d, name %s\n", base, offset, find_name);
466
467         aliases = fdt_path_offset(blob, "/aliases");
468         for (prop_offset = fdt_first_property_offset(blob, aliases);
469              prop_offset > 0;
470              prop_offset = fdt_next_property_offset(blob, prop_offset)) {
471                 const char *prop;
472                 const char *name;
473                 const char *slash;
474                 int len, val;
475
476                 prop = fdt_getprop_by_offset(blob, prop_offset, &name, &len);
477                 debug("   - %s, %s\n", name, prop);
478                 if (len < find_namelen || *prop != '/' || prop[len - 1] ||
479                     strncmp(name, base, base_len))
480                         continue;
481
482                 slash = strrchr(prop, '/');
483                 if (strcmp(slash + 1, find_name))
484                         continue;
485                 val = trailing_strtol(name);
486                 if (val != -1) {
487                         *seqp = val;
488                         debug("Found seq %d\n", *seqp);
489                         return 0;
490                 }
491         }
492
493         debug("Not found\n");
494         return -ENOENT;
495 }
496
497 int fdtdec_get_alias_highest_id(const void *blob, const char *base)
498 {
499         int base_len = strlen(base);
500         int prop_offset;
501         int aliases;
502         int max = -1;
503
504         debug("Looking for highest alias id for '%s'\n", base);
505
506         aliases = fdt_path_offset(blob, "/aliases");
507         for (prop_offset = fdt_first_property_offset(blob, aliases);
508              prop_offset > 0;
509              prop_offset = fdt_next_property_offset(blob, prop_offset)) {
510                 const char *prop;
511                 const char *name;
512                 int len, val;
513
514                 prop = fdt_getprop_by_offset(blob, prop_offset, &name, &len);
515                 debug("   - %s, %s\n", name, prop);
516                 if (*prop != '/' || prop[len - 1] ||
517                     strncmp(name, base, base_len))
518                         continue;
519
520                 val = trailing_strtol(name);
521                 if (val > max) {
522                         debug("Found seq %d\n", val);
523                         max = val;
524                 }
525         }
526
527         return max;
528 }
529
530 const char *fdtdec_get_chosen_prop(const void *blob, const char *name)
531 {
532         int chosen_node;
533
534         if (!blob)
535                 return NULL;
536         chosen_node = fdt_path_offset(blob, "/chosen");
537         return fdt_getprop(blob, chosen_node, name, NULL);
538 }
539
540 int fdtdec_get_chosen_node(const void *blob, const char *name)
541 {
542         const char *prop;
543
544         prop = fdtdec_get_chosen_prop(blob, name);
545         if (!prop)
546                 return -FDT_ERR_NOTFOUND;
547         return fdt_path_offset(blob, prop);
548 }
549
550 int fdtdec_check_fdt(void)
551 {
552         /*
553          * We must have an FDT, but we cannot panic() yet since the console
554          * is not ready. So for now, just assert(). Boards which need an early
555          * FDT (prior to console ready) will need to make their own
556          * arrangements and do their own checks.
557          */
558         assert(!fdtdec_prepare_fdt());
559         return 0;
560 }
561
562 /*
563  * This function is a little odd in that it accesses global data. At some
564  * point if the architecture board.c files merge this will make more sense.
565  * Even now, it is common code.
566  */
567 int fdtdec_prepare_fdt(void)
568 {
569         if (!gd->fdt_blob || ((uintptr_t)gd->fdt_blob & 3) ||
570             fdt_check_header(gd->fdt_blob)) {
571 #ifdef CONFIG_SPL_BUILD
572                 puts("Missing DTB\n");
573 #else
574                 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");
575 # ifdef DEBUG
576                 if (gd->fdt_blob) {
577                         printf("fdt_blob=%p\n", gd->fdt_blob);
578                         print_buffer((ulong)gd->fdt_blob, gd->fdt_blob, 4,
579                                      32, 0);
580                 }
581 # endif
582 #endif
583                 return -1;
584         }
585         return 0;
586 }
587
588 int fdtdec_lookup_phandle(const void *blob, int node, const char *prop_name)
589 {
590         const u32 *phandle;
591         int lookup;
592
593         debug("%s: %s\n", __func__, prop_name);
594         phandle = fdt_getprop(blob, node, prop_name, NULL);
595         if (!phandle)
596                 return -FDT_ERR_NOTFOUND;
597
598         lookup = fdt_node_offset_by_phandle(blob, fdt32_to_cpu(*phandle));
599         return lookup;
600 }
601
602 /**
603  * Look up a property in a node and check that it has a minimum length.
604  *
605  * @param blob          FDT blob
606  * @param node          node to examine
607  * @param prop_name     name of property to find
608  * @param min_len       minimum property length in bytes
609  * @param err           0 if ok, or -FDT_ERR_NOTFOUND if the property is not
610                         found, or -FDT_ERR_BADLAYOUT if not enough data
611  * @return pointer to cell, which is only valid if err == 0
612  */
613 static const void *get_prop_check_min_len(const void *blob, int node,
614                                           const char *prop_name, int min_len,
615                                           int *err)
616 {
617         const void *cell;
618         int len;
619
620         debug("%s: %s\n", __func__, prop_name);
621         cell = fdt_getprop(blob, node, prop_name, &len);
622         if (!cell)
623                 *err = -FDT_ERR_NOTFOUND;
624         else if (len < min_len)
625                 *err = -FDT_ERR_BADLAYOUT;
626         else
627                 *err = 0;
628         return cell;
629 }
630
631 int fdtdec_get_int_array(const void *blob, int node, const char *prop_name,
632                          u32 *array, int count)
633 {
634         const u32 *cell;
635         int err = 0;
636
637         debug("%s: %s\n", __func__, prop_name);
638         cell = get_prop_check_min_len(blob, node, prop_name,
639                                       sizeof(u32) * count, &err);
640         if (!err) {
641                 int i;
642
643                 for (i = 0; i < count; i++)
644                         array[i] = fdt32_to_cpu(cell[i]);
645         }
646         return err;
647 }
648
649 int fdtdec_get_int_array_count(const void *blob, int node,
650                                const char *prop_name, u32 *array, int count)
651 {
652         const u32 *cell;
653         int len, elems;
654         int i;
655
656         debug("%s: %s\n", __func__, prop_name);
657         cell = fdt_getprop(blob, node, prop_name, &len);
658         if (!cell)
659                 return -FDT_ERR_NOTFOUND;
660         elems = len / sizeof(u32);
661         if (count > elems)
662                 count = elems;
663         for (i = 0; i < count; i++)
664                 array[i] = fdt32_to_cpu(cell[i]);
665
666         return count;
667 }
668
669 const u32 *fdtdec_locate_array(const void *blob, int node,
670                                const char *prop_name, int count)
671 {
672         const u32 *cell;
673         int err;
674
675         cell = get_prop_check_min_len(blob, node, prop_name,
676                                       sizeof(u32) * count, &err);
677         return err ? NULL : cell;
678 }
679
680 int fdtdec_get_bool(const void *blob, int node, const char *prop_name)
681 {
682         const s32 *cell;
683         int len;
684
685         debug("%s: %s\n", __func__, prop_name);
686         cell = fdt_getprop(blob, node, prop_name, &len);
687         return cell != NULL;
688 }
689
690 int fdtdec_parse_phandle_with_args(const void *blob, int src_node,
691                                    const char *list_name,
692                                    const char *cells_name,
693                                    int cell_count, int index,
694                                    struct fdtdec_phandle_args *out_args)
695 {
696         const __be32 *list, *list_end;
697         int rc = 0, size, cur_index = 0;
698         uint32_t count = 0;
699         int node = -1;
700         int phandle;
701
702         /* Retrieve the phandle list property */
703         list = fdt_getprop(blob, src_node, list_name, &size);
704         if (!list)
705                 return -ENOENT;
706         list_end = list + size / sizeof(*list);
707
708         /* Loop over the phandles until all the requested entry is found */
709         while (list < list_end) {
710                 rc = -EINVAL;
711                 count = 0;
712
713                 /*
714                  * If phandle is 0, then it is an empty entry with no
715                  * arguments.  Skip forward to the next entry.
716                  */
717                 phandle = be32_to_cpup(list++);
718                 if (phandle) {
719                         /*
720                          * Find the provider node and parse the #*-cells
721                          * property to determine the argument length.
722                          *
723                          * This is not needed if the cell count is hard-coded
724                          * (i.e. cells_name not set, but cell_count is set),
725                          * except when we're going to return the found node
726                          * below.
727                          */
728                         if (cells_name || cur_index == index) {
729                                 node = fdt_node_offset_by_phandle(blob,
730                                                                   phandle);
731                                 if (!node) {
732                                         debug("%s: could not find phandle\n",
733                                               fdt_get_name(blob, src_node,
734                                                            NULL));
735                                         goto err;
736                                 }
737                         }
738
739                         if (cells_name) {
740                                 count = fdtdec_get_int(blob, node, cells_name,
741                                                        -1);
742                                 if (count == -1) {
743                                         debug("%s: could not get %s for %s\n",
744                                               fdt_get_name(blob, src_node,
745                                                            NULL),
746                                               cells_name,
747                                               fdt_get_name(blob, node,
748                                                            NULL));
749                                         goto err;
750                                 }
751                         } else {
752                                 count = cell_count;
753                         }
754
755                         /*
756                          * Make sure that the arguments actually fit in the
757                          * remaining property data length
758                          */
759                         if (list + count > list_end) {
760                                 debug("%s: arguments longer than property\n",
761                                       fdt_get_name(blob, src_node, NULL));
762                                 goto err;
763                         }
764                 }
765
766                 /*
767                  * All of the error cases above bail out of the loop, so at
768                  * this point, the parsing is successful. If the requested
769                  * index matches, then fill the out_args structure and return,
770                  * or return -ENOENT for an empty entry.
771                  */
772                 rc = -ENOENT;
773                 if (cur_index == index) {
774                         if (!phandle)
775                                 goto err;
776
777                         if (out_args) {
778                                 int i;
779
780                                 if (count > MAX_PHANDLE_ARGS) {
781                                         debug("%s: too many arguments %d\n",
782                                               fdt_get_name(blob, src_node,
783                                                            NULL), count);
784                                         count = MAX_PHANDLE_ARGS;
785                                 }
786                                 out_args->node = node;
787                                 out_args->args_count = count;
788                                 for (i = 0; i < count; i++) {
789                                         out_args->args[i] =
790                                                         be32_to_cpup(list++);
791                                 }
792                         }
793
794                         /* Found it! return success */
795                         return 0;
796                 }
797
798                 node = -1;
799                 list += count;
800                 cur_index++;
801         }
802
803         /*
804          * Result will be one of:
805          * -ENOENT : index is for empty phandle
806          * -EINVAL : parsing error on data
807          * [1..n]  : Number of phandle (count mode; when index = -1)
808          */
809         rc = index < 0 ? cur_index : -ENOENT;
810  err:
811         return rc;
812 }
813
814 int fdtdec_get_byte_array(const void *blob, int node, const char *prop_name,
815                           u8 *array, int count)
816 {
817         const u8 *cell;
818         int err;
819
820         cell = get_prop_check_min_len(blob, node, prop_name, count, &err);
821         if (!err)
822                 memcpy(array, cell, count);
823         return err;
824 }
825
826 const u8 *fdtdec_locate_byte_array(const void *blob, int node,
827                                    const char *prop_name, int count)
828 {
829         const u8 *cell;
830         int err;
831
832         cell = get_prop_check_min_len(blob, node, prop_name, count, &err);
833         if (err)
834                 return NULL;
835         return cell;
836 }
837
838 int fdtdec_get_config_int(const void *blob, const char *prop_name,
839                           int default_val)
840 {
841         int config_node;
842
843         debug("%s: %s\n", __func__, prop_name);
844         config_node = fdt_path_offset(blob, "/config");
845         if (config_node < 0)
846                 return default_val;
847         return fdtdec_get_int(blob, config_node, prop_name, default_val);
848 }
849
850 int fdtdec_get_config_bool(const void *blob, const char *prop_name)
851 {
852         int config_node;
853         const void *prop;
854
855         debug("%s: %s\n", __func__, prop_name);
856         config_node = fdt_path_offset(blob, "/config");
857         if (config_node < 0)
858                 return 0;
859         prop = fdt_get_property(blob, config_node, prop_name, NULL);
860
861         return prop != NULL;
862 }
863
864 char *fdtdec_get_config_string(const void *blob, const char *prop_name)
865 {
866         const char *nodep;
867         int nodeoffset;
868         int len;
869
870         debug("%s: %s\n", __func__, prop_name);
871         nodeoffset = fdt_path_offset(blob, "/config");
872         if (nodeoffset < 0)
873                 return NULL;
874
875         nodep = fdt_getprop(blob, nodeoffset, prop_name, &len);
876         if (!nodep)
877                 return NULL;
878
879         return (char *)nodep;
880 }
881
882 u64 fdtdec_get_number(const fdt32_t *ptr, unsigned int cells)
883 {
884         u64 number = 0;
885
886         while (cells--)
887                 number = (number << 32) | fdt32_to_cpu(*ptr++);
888
889         return number;
890 }
891
892 int fdt_get_resource(const void *fdt, int node, const char *property,
893                      unsigned int index, struct fdt_resource *res)
894 {
895         const fdt32_t *ptr, *end;
896         int na, ns, len, parent;
897         unsigned int i = 0;
898
899         parent = fdt_parent_offset(fdt, node);
900         if (parent < 0)
901                 return parent;
902
903         na = fdt_address_cells(fdt, parent);
904         ns = fdt_size_cells(fdt, parent);
905
906         ptr = fdt_getprop(fdt, node, property, &len);
907         if (!ptr)
908                 return len;
909
910         end = ptr + len / sizeof(*ptr);
911
912         while (ptr + na + ns <= end) {
913                 if (i == index) {
914                         res->start = fdtdec_get_number(ptr, na);
915                         res->end = res->start;
916                         res->end += fdtdec_get_number(&ptr[na], ns) - 1;
917                         return 0;
918                 }
919
920                 ptr += na + ns;
921                 i++;
922         }
923
924         return -FDT_ERR_NOTFOUND;
925 }
926
927 int fdt_get_named_resource(const void *fdt, int node, const char *property,
928                            const char *prop_names, const char *name,
929                            struct fdt_resource *res)
930 {
931         int index;
932
933         index = fdt_stringlist_search(fdt, node, prop_names, name);
934         if (index < 0)
935                 return index;
936
937         return fdt_get_resource(fdt, node, property, index, res);
938 }
939
940 static int decode_timing_property(const void *blob, int node, const char *name,
941                                   struct timing_entry *result)
942 {
943         int length, ret = 0;
944         const u32 *prop;
945
946         prop = fdt_getprop(blob, node, name, &length);
947         if (!prop) {
948                 debug("%s: could not find property %s\n",
949                       fdt_get_name(blob, node, NULL), name);
950                 return length;
951         }
952
953         if (length == sizeof(u32)) {
954                 result->typ = fdtdec_get_int(blob, node, name, 0);
955                 result->min = result->typ;
956                 result->max = result->typ;
957         } else {
958                 ret = fdtdec_get_int_array(blob, node, name, &result->min, 3);
959         }
960
961         return ret;
962 }
963
964 int fdtdec_decode_display_timing(const void *blob, int parent, int index,
965                                  struct display_timing *dt)
966 {
967         int i, node, timings_node;
968         u32 val = 0;
969         int ret = 0;
970
971         timings_node = fdt_subnode_offset(blob, parent, "display-timings");
972         if (timings_node < 0)
973                 return timings_node;
974
975         for (i = 0, node = fdt_first_subnode(blob, timings_node);
976              node > 0 && i != index;
977              node = fdt_next_subnode(blob, node))
978                 i++;
979
980         if (node < 0)
981                 return node;
982
983         memset(dt, 0, sizeof(*dt));
984
985         ret |= decode_timing_property(blob, node, "hback-porch",
986                                       &dt->hback_porch);
987         ret |= decode_timing_property(blob, node, "hfront-porch",
988                                       &dt->hfront_porch);
989         ret |= decode_timing_property(blob, node, "hactive", &dt->hactive);
990         ret |= decode_timing_property(blob, node, "hsync-len", &dt->hsync_len);
991         ret |= decode_timing_property(blob, node, "vback-porch",
992                                       &dt->vback_porch);
993         ret |= decode_timing_property(blob, node, "vfront-porch",
994                                       &dt->vfront_porch);
995         ret |= decode_timing_property(blob, node, "vactive", &dt->vactive);
996         ret |= decode_timing_property(blob, node, "vsync-len", &dt->vsync_len);
997         ret |= decode_timing_property(blob, node, "clock-frequency",
998                                       &dt->pixelclock);
999
1000         dt->flags = 0;
1001         val = fdtdec_get_int(blob, node, "vsync-active", -1);
1002         if (val != -1) {
1003                 dt->flags |= val ? DISPLAY_FLAGS_VSYNC_HIGH :
1004                                 DISPLAY_FLAGS_VSYNC_LOW;
1005         }
1006         val = fdtdec_get_int(blob, node, "hsync-active", -1);
1007         if (val != -1) {
1008                 dt->flags |= val ? DISPLAY_FLAGS_HSYNC_HIGH :
1009                                 DISPLAY_FLAGS_HSYNC_LOW;
1010         }
1011         val = fdtdec_get_int(blob, node, "de-active", -1);
1012         if (val != -1) {
1013                 dt->flags |= val ? DISPLAY_FLAGS_DE_HIGH :
1014                                 DISPLAY_FLAGS_DE_LOW;
1015         }
1016         val = fdtdec_get_int(blob, node, "pixelclk-active", -1);
1017         if (val != -1) {
1018                 dt->flags |= val ? DISPLAY_FLAGS_PIXDATA_POSEDGE :
1019                                 DISPLAY_FLAGS_PIXDATA_NEGEDGE;
1020         }
1021
1022         if (fdtdec_get_bool(blob, node, "interlaced"))
1023                 dt->flags |= DISPLAY_FLAGS_INTERLACED;
1024         if (fdtdec_get_bool(blob, node, "doublescan"))
1025                 dt->flags |= DISPLAY_FLAGS_DOUBLESCAN;
1026         if (fdtdec_get_bool(blob, node, "doubleclk"))
1027                 dt->flags |= DISPLAY_FLAGS_DOUBLECLK;
1028
1029         return ret;
1030 }
1031
1032 int fdtdec_setup_mem_size_base_fdt(const void *blob)
1033 {
1034         int ret, mem;
1035         struct fdt_resource res;
1036
1037         mem = fdt_path_offset(blob, "/memory");
1038         if (mem < 0) {
1039                 debug("%s: Missing /memory node\n", __func__);
1040                 return -EINVAL;
1041         }
1042
1043         ret = fdt_get_resource(blob, mem, "reg", 0, &res);
1044         if (ret != 0) {
1045                 debug("%s: Unable to decode first memory bank\n", __func__);
1046                 return -EINVAL;
1047         }
1048
1049         gd->ram_size = (phys_size_t)(res.end - res.start + 1);
1050         gd->ram_base = (unsigned long)res.start;
1051         debug("%s: Initial DRAM size %llx\n", __func__,
1052               (unsigned long long)gd->ram_size);
1053
1054         return 0;
1055 }
1056
1057 int fdtdec_setup_mem_size_base(void)
1058 {
1059         return fdtdec_setup_mem_size_base_fdt(gd->fdt_blob);
1060 }
1061
1062 #if defined(CONFIG_NR_DRAM_BANKS)
1063
1064 static int get_next_memory_node(const void *blob, int mem)
1065 {
1066         do {
1067                 mem = fdt_node_offset_by_prop_value(blob, mem,
1068                                                     "device_type", "memory", 7);
1069         } while (!fdtdec_get_is_enabled(blob, mem));
1070
1071         return mem;
1072 }
1073
1074 int fdtdec_setup_memory_banksize_fdt(const void *blob)
1075 {
1076         int bank, ret, mem, reg = 0;
1077         struct fdt_resource res;
1078
1079         mem = get_next_memory_node(blob, -1);
1080         if (mem < 0) {
1081                 debug("%s: Missing /memory node\n", __func__);
1082                 return -EINVAL;
1083         }
1084
1085         for (bank = 0; bank < CONFIG_NR_DRAM_BANKS; bank++) {
1086                 ret = fdt_get_resource(blob, mem, "reg", reg++, &res);
1087                 if (ret == -FDT_ERR_NOTFOUND) {
1088                         reg = 0;
1089                         mem = get_next_memory_node(blob, mem);
1090                         if (mem == -FDT_ERR_NOTFOUND)
1091                                 break;
1092
1093                         ret = fdt_get_resource(blob, mem, "reg", reg++, &res);
1094                         if (ret == -FDT_ERR_NOTFOUND)
1095                                 break;
1096                 }
1097                 if (ret != 0) {
1098                         return -EINVAL;
1099                 }
1100
1101                 gd->bd->bi_dram[bank].start = (phys_addr_t)res.start;
1102                 gd->bd->bi_dram[bank].size =
1103                         (phys_size_t)(res.end - res.start + 1);
1104
1105                 debug("%s: DRAM Bank #%d: start = 0x%llx, size = 0x%llx\n",
1106                       __func__, bank,
1107                       (unsigned long long)gd->bd->bi_dram[bank].start,
1108                       (unsigned long long)gd->bd->bi_dram[bank].size);
1109         }
1110
1111         return 0;
1112 }
1113
1114 int fdtdec_setup_memory_banksize(void)
1115 {
1116         return fdtdec_setup_memory_banksize_fdt(gd->fdt_blob);
1117
1118 }
1119 #endif
1120
1121 #if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1122 # if CONFIG_IS_ENABLED(MULTI_DTB_FIT_GZIP) ||\
1123         CONFIG_IS_ENABLED(MULTI_DTB_FIT_LZO)
1124 static int uncompress_blob(const void *src, ulong sz_src, void **dstp)
1125 {
1126         size_t sz_out = CONFIG_VAL(MULTI_DTB_FIT_UNCOMPRESS_SZ);
1127         bool gzip = 0, lzo = 0;
1128         ulong sz_in = sz_src;
1129         void *dst;
1130         int rc;
1131
1132         if (CONFIG_IS_ENABLED(GZIP))
1133                 if (gzip_parse_header(src, sz_in) >= 0)
1134                         gzip = 1;
1135         if (CONFIG_IS_ENABLED(LZO))
1136                 if (!gzip && lzop_is_valid_header(src))
1137                         lzo = 1;
1138
1139         if (!gzip && !lzo)
1140                 return -EBADMSG;
1141
1142
1143         if (CONFIG_IS_ENABLED(MULTI_DTB_FIT_DYN_ALLOC)) {
1144                 dst = malloc(sz_out);
1145                 if (!dst) {
1146                         puts("uncompress_blob: Unable to allocate memory\n");
1147                         return -ENOMEM;
1148                 }
1149         } else  {
1150 #  if CONFIG_IS_ENABLED(MULTI_DTB_FIT_USER_DEFINED_AREA)
1151                 dst = (void *)CONFIG_VAL(MULTI_DTB_FIT_USER_DEF_ADDR);
1152 #  else
1153                 return -ENOTSUPP;
1154 #  endif
1155         }
1156
1157         if (CONFIG_IS_ENABLED(GZIP) && gzip)
1158                 rc = gunzip(dst, sz_out, (u8 *)src, &sz_in);
1159         else if (CONFIG_IS_ENABLED(LZO) && lzo)
1160                 rc = lzop_decompress(src, sz_in, dst, &sz_out);
1161         else
1162                 hang();
1163
1164         if (rc < 0) {
1165                 /* not a valid compressed blob */
1166                 puts("uncompress_blob: Unable to uncompress\n");
1167                 if (CONFIG_IS_ENABLED(MULTI_DTB_FIT_DYN_ALLOC))
1168                         free(dst);
1169                 return -EBADMSG;
1170         }
1171         *dstp = dst;
1172         return 0;
1173 }
1174 # else
1175 static int uncompress_blob(const void *src, ulong sz_src, void **dstp)
1176 {
1177         *dstp = (void *)src;
1178         return 0;
1179 }
1180 # endif
1181 #endif
1182
1183 #if defined(CONFIG_OF_BOARD) || defined(CONFIG_OF_SEPARATE)
1184 /*
1185  * For CONFIG_OF_SEPARATE, the board may optionally implement this to
1186  * provide and/or fixup the fdt.
1187  */
1188 __weak void *board_fdt_blob_setup(void)
1189 {
1190         void *fdt_blob = NULL;
1191 #ifdef CONFIG_SPL_BUILD
1192         /* FDT is at end of BSS unless it is in a different memory region */
1193         if (IS_ENABLED(CONFIG_SPL_SEPARATE_BSS))
1194                 fdt_blob = (ulong *)&_image_binary_end;
1195         else
1196                 fdt_blob = (ulong *)&__bss_end;
1197 #else
1198         /* FDT is at end of image */
1199         fdt_blob = (ulong *)&_end;
1200 #endif
1201         return fdt_blob;
1202 }
1203 #endif
1204
1205 int fdtdec_set_ethernet_mac_address(void *fdt, const u8 *mac, size_t size)
1206 {
1207         const char *path;
1208         int offset, err;
1209
1210         if (!is_valid_ethaddr(mac))
1211                 return -EINVAL;
1212
1213         path = fdt_get_alias(fdt, "ethernet");
1214         if (!path)
1215                 return 0;
1216
1217         debug("ethernet alias found: %s\n", path);
1218
1219         offset = fdt_path_offset(fdt, path);
1220         if (offset < 0) {
1221                 debug("ethernet alias points to absent node %s\n", path);
1222                 return -ENOENT;
1223         }
1224
1225         err = fdt_setprop_inplace(fdt, offset, "local-mac-address", mac, size);
1226         if (err < 0)
1227                 return err;
1228
1229         debug("MAC address: %pM\n", mac);
1230
1231         return 0;
1232 }
1233
1234 static int fdtdec_init_reserved_memory(void *blob)
1235 {
1236         int na, ns, node, err;
1237         fdt32_t value;
1238
1239         /* inherit #address-cells and #size-cells from the root node */
1240         na = fdt_address_cells(blob, 0);
1241         ns = fdt_size_cells(blob, 0);
1242
1243         node = fdt_add_subnode(blob, 0, "reserved-memory");
1244         if (node < 0)
1245                 return node;
1246
1247         err = fdt_setprop(blob, node, "ranges", NULL, 0);
1248         if (err < 0)
1249                 return err;
1250
1251         value = cpu_to_fdt32(ns);
1252
1253         err = fdt_setprop(blob, node, "#size-cells", &value, sizeof(value));
1254         if (err < 0)
1255                 return err;
1256
1257         value = cpu_to_fdt32(na);
1258
1259         err = fdt_setprop(blob, node, "#address-cells", &value, sizeof(value));
1260         if (err < 0)
1261                 return err;
1262
1263         return node;
1264 }
1265
1266 int fdtdec_add_reserved_memory(void *blob, const char *basename,
1267                                const struct fdt_memory *carveout,
1268                                uint32_t *phandlep)
1269 {
1270         fdt32_t cells[4] = {}, *ptr = cells;
1271         uint32_t upper, lower, phandle;
1272         int parent, node, na, ns, err;
1273         fdt_size_t size;
1274         char name[64];
1275
1276         /* create an empty /reserved-memory node if one doesn't exist */
1277         parent = fdt_path_offset(blob, "/reserved-memory");
1278         if (parent < 0) {
1279                 parent = fdtdec_init_reserved_memory(blob);
1280                 if (parent < 0)
1281                         return parent;
1282         }
1283
1284         /* only 1 or 2 #address-cells and #size-cells are supported */
1285         na = fdt_address_cells(blob, parent);
1286         if (na < 1 || na > 2)
1287                 return -FDT_ERR_BADNCELLS;
1288
1289         ns = fdt_size_cells(blob, parent);
1290         if (ns < 1 || ns > 2)
1291                 return -FDT_ERR_BADNCELLS;
1292
1293         /* find a matching node and return the phandle to that */
1294         fdt_for_each_subnode(node, blob, parent) {
1295                 const char *name = fdt_get_name(blob, node, NULL);
1296                 phys_addr_t addr, size;
1297
1298                 addr = fdtdec_get_addr_size(blob, node, "reg", &size);
1299                 if (addr == FDT_ADDR_T_NONE) {
1300                         debug("failed to read address/size for %s\n", name);
1301                         continue;
1302                 }
1303
1304                 if (addr == carveout->start && (addr + size - 1) ==
1305                                                 carveout->end) {
1306                         if (phandlep)
1307                                 *phandlep = fdt_get_phandle(blob, node);
1308                         return 0;
1309                 }
1310         }
1311
1312         /*
1313          * Unpack the start address and generate the name of the new node
1314          * base on the basename and the unit-address.
1315          */
1316         upper = upper_32_bits(carveout->start);
1317         lower = lower_32_bits(carveout->start);
1318
1319         if (na > 1 && upper > 0)
1320                 snprintf(name, sizeof(name), "%s@%x,%x", basename, upper,
1321                          lower);
1322         else {
1323                 if (upper > 0) {
1324                         debug("address %08x:%08x exceeds addressable space\n",
1325                               upper, lower);
1326                         return -FDT_ERR_BADVALUE;
1327                 }
1328
1329                 snprintf(name, sizeof(name), "%s@%x", basename, lower);
1330         }
1331
1332         node = fdt_add_subnode(blob, parent, name);
1333         if (node < 0)
1334                 return node;
1335
1336         if (phandlep) {
1337                 err = fdt_generate_phandle(blob, &phandle);
1338                 if (err < 0)
1339                         return err;
1340
1341                 err = fdtdec_set_phandle(blob, node, phandle);
1342                 if (err < 0)
1343                         return err;
1344         }
1345
1346         /* store one or two address cells */
1347         if (na > 1)
1348                 *ptr++ = cpu_to_fdt32(upper);
1349
1350         *ptr++ = cpu_to_fdt32(lower);
1351
1352         /* store one or two size cells */
1353         size = carveout->end - carveout->start + 1;
1354         upper = upper_32_bits(size);
1355         lower = lower_32_bits(size);
1356
1357         if (ns > 1)
1358                 *ptr++ = cpu_to_fdt32(upper);
1359
1360         *ptr++ = cpu_to_fdt32(lower);
1361
1362         err = fdt_setprop(blob, node, "reg", cells, (na + ns) * sizeof(*cells));
1363         if (err < 0)
1364                 return err;
1365
1366         /* return the phandle for the new node for the caller to use */
1367         if (phandlep)
1368                 *phandlep = phandle;
1369
1370         return 0;
1371 }
1372
1373 int fdtdec_get_carveout(const void *blob, const char *node, const char *name,
1374                         unsigned int index, struct fdt_memory *carveout)
1375 {
1376         const fdt32_t *prop;
1377         uint32_t phandle;
1378         int offset, len;
1379         fdt_size_t size;
1380
1381         offset = fdt_path_offset(blob, node);
1382         if (offset < 0)
1383                 return offset;
1384
1385         prop = fdt_getprop(blob, offset, name, &len);
1386         if (!prop) {
1387                 debug("failed to get %s for %s\n", name, node);
1388                 return -FDT_ERR_NOTFOUND;
1389         }
1390
1391         if ((len % sizeof(phandle)) != 0) {
1392                 debug("invalid phandle property\n");
1393                 return -FDT_ERR_BADPHANDLE;
1394         }
1395
1396         if (len < (sizeof(phandle) * (index + 1))) {
1397                 debug("invalid phandle index\n");
1398                 return -FDT_ERR_BADPHANDLE;
1399         }
1400
1401         phandle = fdt32_to_cpu(prop[index]);
1402
1403         offset = fdt_node_offset_by_phandle(blob, phandle);
1404         if (offset < 0) {
1405                 debug("failed to find node for phandle %u\n", phandle);
1406                 return offset;
1407         }
1408
1409         carveout->start = fdtdec_get_addr_size_auto_noparent(blob, offset,
1410                                                              "reg", 0, &size,
1411                                                              true);
1412         if (carveout->start == FDT_ADDR_T_NONE) {
1413                 debug("failed to read address/size from \"reg\" property\n");
1414                 return -FDT_ERR_NOTFOUND;
1415         }
1416
1417         carveout->end = carveout->start + size - 1;
1418
1419         return 0;
1420 }
1421
1422 int fdtdec_set_carveout(void *blob, const char *node, const char *prop_name,
1423                         unsigned int index, const char *name,
1424                         const struct fdt_memory *carveout)
1425 {
1426         uint32_t phandle;
1427         int err, offset, len;
1428         fdt32_t value;
1429         void *prop;
1430
1431         err = fdtdec_add_reserved_memory(blob, name, carveout, &phandle);
1432         if (err < 0) {
1433                 debug("failed to add reserved memory: %d\n", err);
1434                 return err;
1435         }
1436
1437         offset = fdt_path_offset(blob, node);
1438         if (offset < 0) {
1439                 debug("failed to find offset for node %s: %d\n", node, offset);
1440                 return offset;
1441         }
1442
1443         value = cpu_to_fdt32(phandle);
1444
1445         if (!fdt_getprop(blob, offset, prop_name, &len)) {
1446                 if (len == -FDT_ERR_NOTFOUND)
1447                         len = 0;
1448                 else
1449                         return len;
1450         }
1451
1452         if ((index + 1) * sizeof(value) > len) {
1453                 err = fdt_setprop_placeholder(blob, offset, prop_name,
1454                                               (index + 1) * sizeof(value),
1455                                               &prop);
1456                 if (err < 0) {
1457                         debug("failed to resize reserved memory property: %s\n",
1458                               fdt_strerror(err));
1459                         return err;
1460                 }
1461         }
1462
1463         err = fdt_setprop_inplace_namelen_partial(blob, offset, prop_name,
1464                                                   strlen(prop_name),
1465                                                   index * sizeof(value),
1466                                                   &value, sizeof(value));
1467         if (err < 0) {
1468                 debug("failed to update %s property for node %s: %s\n",
1469                       prop_name, node, fdt_strerror(err));
1470                 return err;
1471         }
1472
1473         return 0;
1474 }
1475
1476 int fdtdec_setup(void)
1477 {
1478 #if CONFIG_IS_ENABLED(OF_CONTROL)
1479 # if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1480         void *fdt_blob;
1481 # endif
1482 # ifdef CONFIG_OF_EMBED
1483         /* Get a pointer to the FDT */
1484 #  ifdef CONFIG_SPL_BUILD
1485         gd->fdt_blob = __dtb_dt_spl_begin;
1486 #  else
1487         gd->fdt_blob = __dtb_dt_begin;
1488 #  endif
1489 # elif defined(CONFIG_OF_BOARD) || defined(CONFIG_OF_SEPARATE)
1490         /* Allow the board to override the fdt address. */
1491         gd->fdt_blob = board_fdt_blob_setup();
1492 # elif defined(CONFIG_OF_HOSTFILE)
1493         if (sandbox_read_fdt_from_file()) {
1494                 puts("Failed to read control FDT\n");
1495                 return -1;
1496         }
1497 # elif defined(CONFIG_OF_PRIOR_STAGE)
1498         gd->fdt_blob = (void *)prior_stage_fdt_address;
1499 # endif
1500 # ifndef CONFIG_SPL_BUILD
1501         /* Allow the early environment to override the fdt address */
1502         gd->fdt_blob = map_sysmem
1503                 (env_get_ulong("fdtcontroladdr", 16,
1504                                (unsigned long)map_to_sysmem(gd->fdt_blob)), 0);
1505 # endif
1506
1507 # if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1508         /*
1509          * Try and uncompress the blob.
1510          * Unfortunately there is no way to know how big the input blob really
1511          * is. So let us set the maximum input size arbitrarily high. 16MB
1512          * ought to be more than enough for packed DTBs.
1513          */
1514         if (uncompress_blob(gd->fdt_blob, 0x1000000, &fdt_blob) == 0)
1515                 gd->fdt_blob = fdt_blob;
1516
1517         /*
1518          * Check if blob is a FIT images containings DTBs.
1519          * If so, pick the most relevant
1520          */
1521         fdt_blob = locate_dtb_in_fit(gd->fdt_blob);
1522         if (fdt_blob) {
1523                 gd->multi_dtb_fit = gd->fdt_blob;
1524                 gd->fdt_blob = fdt_blob;
1525         }
1526
1527 # endif
1528 #endif
1529
1530         return fdtdec_prepare_fdt();
1531 }
1532
1533 #if CONFIG_IS_ENABLED(MULTI_DTB_FIT)
1534 int fdtdec_resetup(int *rescan)
1535 {
1536         void *fdt_blob;
1537
1538         /*
1539          * If the current DTB is part of a compressed FIT image,
1540          * try to locate the best match from the uncompressed
1541          * FIT image stillpresent there. Save the time and space
1542          * required to uncompress it again.
1543          */
1544         if (gd->multi_dtb_fit) {
1545                 fdt_blob = locate_dtb_in_fit(gd->multi_dtb_fit);
1546
1547                 if (fdt_blob == gd->fdt_blob) {
1548                         /*
1549                          * The best match did not change. no need to tear down
1550                          * the DM and rescan the fdt.
1551                          */
1552                         *rescan = 0;
1553                         return 0;
1554                 }
1555
1556                 *rescan = 1;
1557                 gd->fdt_blob = fdt_blob;
1558                 return fdtdec_prepare_fdt();
1559         }
1560
1561         /*
1562          * If multi_dtb_fit is NULL, it means that blob appended to u-boot is
1563          * not a FIT image containings DTB, but a single DTB. There is no need
1564          * to teard down DM and rescan the DT in this case.
1565          */
1566         *rescan = 0;
1567         return 0;
1568 }
1569 #endif
1570
1571 #ifdef CONFIG_NR_DRAM_BANKS
1572 int fdtdec_decode_ram_size(const void *blob, const char *area, int board_id,
1573                            phys_addr_t *basep, phys_size_t *sizep, bd_t *bd)
1574 {
1575         int addr_cells, size_cells;
1576         const u32 *cell, *end;
1577         u64 total_size, size, addr;
1578         int node, child;
1579         bool auto_size;
1580         int bank;
1581         int len;
1582
1583         debug("%s: board_id=%d\n", __func__, board_id);
1584         if (!area)
1585                 area = "/memory";
1586         node = fdt_path_offset(blob, area);
1587         if (node < 0) {
1588                 debug("No %s node found\n", area);
1589                 return -ENOENT;
1590         }
1591
1592         cell = fdt_getprop(blob, node, "reg", &len);
1593         if (!cell) {
1594                 debug("No reg property found\n");
1595                 return -ENOENT;
1596         }
1597
1598         addr_cells = fdt_address_cells(blob, node);
1599         size_cells = fdt_size_cells(blob, node);
1600
1601         /* Check the board id and mask */
1602         for (child = fdt_first_subnode(blob, node);
1603              child >= 0;
1604              child = fdt_next_subnode(blob, child)) {
1605                 int match_mask, match_value;
1606
1607                 match_mask = fdtdec_get_int(blob, child, "match-mask", -1);
1608                 match_value = fdtdec_get_int(blob, child, "match-value", -1);
1609
1610                 if (match_value >= 0 &&
1611                     ((board_id & match_mask) == match_value)) {
1612                         /* Found matching mask */
1613                         debug("Found matching mask %d\n", match_mask);
1614                         node = child;
1615                         cell = fdt_getprop(blob, node, "reg", &len);
1616                         if (!cell) {
1617                                 debug("No memory-banks property found\n");
1618                                 return -EINVAL;
1619                         }
1620                         break;
1621                 }
1622         }
1623         /* Note: if no matching subnode was found we use the parent node */
1624
1625         if (bd) {
1626                 memset(bd->bi_dram, '\0', sizeof(bd->bi_dram[0]) *
1627                                                 CONFIG_NR_DRAM_BANKS);
1628         }
1629
1630         auto_size = fdtdec_get_bool(blob, node, "auto-size");
1631
1632         total_size = 0;
1633         end = cell + len / 4 - addr_cells - size_cells;
1634         debug("cell at %p, end %p\n", cell, end);
1635         for (bank = 0; bank < CONFIG_NR_DRAM_BANKS; bank++) {
1636                 if (cell > end)
1637                         break;
1638                 addr = 0;
1639                 if (addr_cells == 2)
1640                         addr += (u64)fdt32_to_cpu(*cell++) << 32UL;
1641                 addr += fdt32_to_cpu(*cell++);
1642                 if (bd)
1643                         bd->bi_dram[bank].start = addr;
1644                 if (basep && !bank)
1645                         *basep = (phys_addr_t)addr;
1646
1647                 size = 0;
1648                 if (size_cells == 2)
1649                         size += (u64)fdt32_to_cpu(*cell++) << 32UL;
1650                 size += fdt32_to_cpu(*cell++);
1651
1652                 if (auto_size) {
1653                         u64 new_size;
1654
1655                         debug("Auto-sizing %llx, size %llx: ", addr, size);
1656                         new_size = get_ram_size((long *)(uintptr_t)addr, size);
1657                         if (new_size == size) {
1658                                 debug("OK\n");
1659                         } else {
1660                                 debug("sized to %llx\n", new_size);
1661                                 size = new_size;
1662                         }
1663                 }
1664
1665                 if (bd)
1666                         bd->bi_dram[bank].size = size;
1667                 total_size += size;
1668         }
1669
1670         debug("Memory size %llu\n", total_size);
1671         if (sizep)
1672                 *sizep = (phys_size_t)total_size;
1673
1674         return 0;
1675 }
1676 #endif /* CONFIG_NR_DRAM_BANKS */
1677
1678 #endif /* !USE_HOSTCC */