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