[coreboot-gerrit] Change in coreboot[master]: [WIP]src/lib: Add uImage support
Patrick Rudolph (Code Review)
gerrit at coreboot.org
Wed Mar 7 13:48:25 CET 2018
Patrick Rudolph has uploaded this change for review. ( https://review.coreboot.org/25019
Change subject: [WIP]src/lib: Add uImage support
......................................................................
[WIP]src/lib: Add uImage support
Add support for parsing and booting FIT uImage.
Copy loader code from depthcharge.
Add architecture code to boot a kernel on armv8.
Add payloadtype raw, as uImage is not executable.
Add Kconfig option to select image type:
* uImage
* bzImage
Tested on Cavium SoC: Parses and loads a kernel.
Change-Id: I0f27b92a5e074966f893399eb401eb97d784850d
Signed-off-by: Patrick Rudolph <patrick.rudolph at 9elements.com>
---
M payloads/Kconfig
M payloads/external/Makefile.inc
M payloads/external/linux/Kconfig
M src/arch/arm64/boot.c
A src/include/device_tree.h
A src/include/fit.h
A src/include/list.h
A src/include/ranges.h
M src/include/string.h
M src/lib/Makefile.inc
A src/lib/device_tree.c
A src/lib/fit.c
A src/lib/list.c
M src/lib/prog_loaders.c
A src/lib/ranges.c
A src/lib/uImage.c
16 files changed, 2,459 insertions(+), 3 deletions(-)
git pull ssh://review.coreboot.org:29418/coreboot refs/changes/19/25019/1
diff --git a/payloads/Kconfig b/payloads/Kconfig
index 2a329ac..9e9a7cb 100644
--- a/payloads/Kconfig
+++ b/payloads/Kconfig
@@ -3,6 +3,9 @@
config NO_DEFAULT_PAYLOAD
bool
+config PAYLOAD_TYPE_RAW
+ bool
+
choice
prompt "Add a payload"
default PAYLOAD_NONE if NO_DEFAULT_PAYLOAD || !ARCH_X86
diff --git a/payloads/external/Makefile.inc b/payloads/external/Makefile.inc
index ec7d9a8..e65d7e4 100644
--- a/payloads/external/Makefile.inc
+++ b/payloads/external/Makefile.inc
@@ -47,6 +47,8 @@
$(CONFIG_CBFS_PREFIX)/payload-file := $(CONFIG_PAYLOAD_FILE)
ifeq ($(CONFIG_PAYLOAD_IS_FLAT_BINARY),y)
$(CONFIG_CBFS_PREFIX)/payload-type := flat-binary
+else if ($(CONFIG_PAYLOAD_TYPE_RAW),y)
+$(CONFIG_CBFS_PREFIX)/payload-type := raw
else
$(CONFIG_CBFS_PREFIX)/payload-type := payload
endif
diff --git a/payloads/external/linux/Kconfig b/payloads/external/linux/Kconfig
index 8b15f99..13718a2 100644
--- a/payloads/external/linux/Kconfig
+++ b/payloads/external/linux/Kconfig
@@ -1,5 +1,23 @@
if PAYLOAD_LINUX
+config PAYLOAD_SPECIFIC_OPTIONS # dummy
+ def_bool y
+
+choice
+ prompt "Image type"
+ default PAYLOAD_LINUX_BZIMAGE if X86
+
+config PAYLOAD_LINUX_BZIMAGE
+ bool "bzImage"
+ depends on ARCH_X86
+
+config PAYLOAD_LINUX_UIMAGE
+ select PAYLOAD_TYPE_RAW
+ bool "uImage"
+
+endchoice
+
+
config PAYLOAD_FILE
string "Linux path and filename"
default "bzImage"
diff --git a/src/arch/arm64/boot.c b/src/arch/arm64/boot.c
index d498cd9..f49b66c 100644
--- a/src/arch/arm64/boot.c
+++ b/src/arch/arm64/boot.c
@@ -23,6 +23,13 @@
#include <program_loading.h>
#include <rules.h>
#include <string.h>
+#include <assert.h>
+#include <console/console.h>
+#include <boot/coreboot_tables.h>
+#include <symbols.h>
+
+#define OVERLAPS(s,e,x) (((uintptr_t)_##x > (s) && (s) < (uintptr_t)_e##x) || \
+ ((uintptr_t)_##x > (e) && (e) < (uintptr_t)_e##x))
static void run_payload(struct prog *prog)
{
@@ -82,3 +89,105 @@
{
main();
}
+
+static int overlaps_coreboot(uintptr_t start, uintptr_t end)
+{
+ return OVERLAPS(start, end, program) ||
+ OVERLAPS(start, end, stack) ||
+ OVERLAPS(start, end, ttb) ||
+ OVERLAPS(start, end, preram_cbfs_cache) ||
+ OVERLAPS(start, end, postram_cbfs_cache) ||
+ OVERLAPS(start, end, cbfs_cache);
+}
+
+static struct lb_memory *lb_memory(void)
+{
+ const struct lb_header *head;
+ const struct lb_record *rec;
+ size_t i;
+
+ head = cbmem_find(CBMEM_ID_CBTABLE);
+ if (!head)
+ return NULL;
+
+ i = head->table_entries;
+ rec = (struct lb_record *)(((uint8_t *)head) + head->header_bytes);
+
+ while (i--) {
+ if (rec->tag == LB_TAG_FORWARD) {
+ struct lb_forward *forward = (struct lb_forward *)rec;
+ head = (void *)forward->forward;
+ break;
+ }
+ rec = (struct lb_record *)(((uint8_t *)rec) + rec->size);
+ }
+
+ i = head->table_entries;
+ rec = (struct lb_record *)(((uint8_t *)head) + head->header_bytes);
+ while (i--) {
+ if (rec->tag == LB_TAG_MEMORY)
+ return (struct lb_memory *)rec;
+ rec = (struct lb_record *)(((uint8_t *)rec) + rec->size);
+ }
+
+ return NULL;
+}
+
+/*
+ * Override weak implementation for ARCH specific uImage load support.
+ * Return kernel and fdt load address.
+ */
+size_t
+arch_get_kernel_fdt_load_addr(uint32_t load_offset,
+ size_t kernel_size,
+ uint32_t fdt_size,
+ void **kernel_load_addr,
+ void **fdt_load_addr)
+{
+ struct lb_memory *lb_mem = lb_memory();
+ size_t i, nentries;
+
+ assert ((fdt_size > 0) && (fdt_size < 2 * MiB));
+
+ nentries = (lb_mem->size - sizeof(*lb_mem)) / sizeof(lb_mem->map[0]);
+ for (i = 0; i < nentries; i++) {
+ struct lb_memory_range *range = &lb_mem->map[i];
+ uint64_t kstart, kend, fdtstart;
+
+ if (range->type != LB_MEM_RAM)
+ continue;
+
+ uint64_t start = unpack_lb64(range->start);
+ uint64_t end = start + unpack_lb64(range->size);
+
+ do {
+ fdtstart = ALIGN_DOWN(start, 2*MiB) < start
+ ? ALIGN_UP(start, 2 * MiB)
+ : ALIGN_DOWN(start, 2 * MiB);
+
+ kstart = fdtstart + load_offset;
+ if (fdt_size > load_offset)
+ kstart += 2 * MiB;
+ kend = kstart + kernel_size;
+
+ if (!overlaps_coreboot(fdtstart, kend))
+ break;
+ start += 2 * MiB;
+ } while (kend <= end);
+
+ if (kend <= end) {
+ *fdt_load_addr = (void *)fdtstart;
+ *kernel_load_addr = (void *)kstart;
+ return 0;
+ }
+
+ // Should be avoided in practice, that memory might be wasted.
+ printk(BIOS_WARNING,
+ "WARNING: Skipping low memory range [%p:%p]!\n",
+ (void *)start, (void *)end);
+ }
+
+ printk(BIOS_ERR,
+ "ERROR: Cannot find enough continuous memory for kernel!\n");
+ return 1;
+}
diff --git a/src/include/device_tree.h b/src/include/device_tree.h
new file mode 100644
index 0000000..03af77a
--- /dev/null
+++ b/src/include/device_tree.h
@@ -0,0 +1,219 @@
+/*
+ * Copyright 2013 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#ifndef __BASE_DEVICE_TREE_H__
+#define __BASE_DEVICE_TREE_H__
+
+#include <stdint.h>
+
+#include "list.h"
+
+/*
+ * Flattened device tree structures/constants.
+ */
+
+typedef struct FdtHeader {
+ uint32_t magic;
+ uint32_t totalsize;
+ uint32_t structure_offset;
+ uint32_t strings_offset;
+ uint32_t reserve_map_offset;
+
+ uint32_t version;
+ uint32_t last_compatible_version;
+
+ uint32_t boot_cpuid_phys;
+
+ uint32_t strings_size;
+ uint32_t structure_size;
+} FdtHeader;
+
+static const uint32_t FdtMagic = 0xd00dfeed;
+
+static const uint32_t TokenBeginNode = 1;
+static const uint32_t TokenEndNode = 2;
+static const uint32_t TokenProperty = 3;
+static const uint32_t TokenEnd = 9;
+
+typedef struct FdtProperty
+{
+ const char *name;
+ void *data;
+ uint32_t size;
+} FdtProperty;
+
+
+
+/*
+ * Unflattened device tree structures.
+ */
+
+typedef struct DeviceTreeProperty
+{
+ FdtProperty prop;
+
+ ListNode list_node;
+} DeviceTreeProperty;
+
+typedef struct DeviceTreeNode
+{
+ const char *name;
+ // List of DeviceTreeProperty-s.
+ ListNode properties;
+ // List of DeviceTreeNodes.
+ ListNode children;
+
+ ListNode list_node;
+} DeviceTreeNode;
+
+typedef struct DeviceTreeReserveMapEntry
+{
+ uint64_t start;
+ uint64_t size;
+
+ ListNode list_node;
+} DeviceTreeReserveMapEntry;
+
+typedef struct DeviceTree
+{
+ void *header;
+ uint32_t header_size;
+
+ ListNode reserve_map;
+
+ DeviceTreeNode *root;
+} DeviceTree;
+
+
+
+/*
+ * Flattened device tree functions. These generally return the number of bytes
+ * which were consumed reading the requested value.
+ */
+
+// Read the property, if any, at offset offset.
+int fdt_next_property(void *blob, uint32_t offset, FdtProperty *prop);
+// Read the name of the node, if any, at offset offset.
+int fdt_node_name(void *blob, uint32_t offset, const char **name);
+
+void fdt_print_node(void *blob, uint32_t offset);
+int fdt_skip_node(void *blob, uint32_t offset);
+
+// Read a flattened device tree into a heirarchical structure which refers to
+// the contents of the flattened tree in place. Modifying the flat tree
+// invalidates the unflattened one.
+DeviceTree *fdt_unflatten(void *blob);
+
+
+
+/*
+ * Unflattened device tree functions.
+ */
+
+// Figure out how big a device tree would be if it were flattened.
+uint32_t dt_flat_size(DeviceTree *tree);
+// Flatten a device tree into the buffer pointed to by dest.
+void dt_flatten(DeviceTree *tree, void *dest);
+void dt_print_node(DeviceTreeNode *node);
+// Read #address-cells and #size-cells properties from a node.
+void dt_read_cell_props(DeviceTreeNode *node, u32 *addrcp, u32 *sizecp);
+// Look up or create a node relative to a parent node, through its path
+// represented as an array of strings.
+DeviceTreeNode *dt_find_node(DeviceTreeNode *parent, const char **path,
+ u32 *addrcp, u32 *sizecp, int create);
+// Look up or create a node relative to a parent node, through its path
+// represented as a string of '/' separated node names.
+DeviceTreeNode *dt_find_node_by_path(DeviceTreeNode *parent, const char *path,
+ u32 *addrcp, u32 *sizecp, int create);
+// Look up a node relative to a parent node, through its compatible string.
+DeviceTreeNode *dt_find_compat(DeviceTreeNode *parent, const char *compatible);
+// Look up the next child of a parent node, through its compatible string. It
+// uses child pointer as the marker to find next.
+DeviceTreeNode *dt_find_next_compat_child(DeviceTreeNode *parent,
+ DeviceTreeNode *child,
+ const char *compat);
+// Look up a node relative to a parent node, through its property value.
+DeviceTreeNode *dt_find_prop_value(DeviceTreeNode *parent, const char *name,
+ void *data, size_t size);
+// Write src into *dest as a 'length'-byte big-endian integer.
+void dt_write_int(u8 *dest, u64 src, size_t length);
+// Add different kinds of properties to a node, or update existing ones.
+void dt_add_bin_prop(DeviceTreeNode *node, char *name, void *data, size_t size);
+void dt_add_string_prop(DeviceTreeNode *node, char *name, char *str);
+void dt_add_u32_prop(DeviceTreeNode *node, char *name, u32 val);
+void dt_add_reg_prop(DeviceTreeNode *node, u64 *addrs, u64 *sizes,
+ int count, u32 addr_cells, u32 size_cells);
+int dt_set_bin_prop_by_path(DeviceTree *tree, const char *path,
+ void *data, size_t size, int create);
+
+void dt_find_bin_prop(DeviceTreeNode *node, const char *name, void **data,
+ size_t *size);
+const char *dt_find_string_prop(DeviceTreeNode *node, const char *name);
+
+/*
+ * Fixups to apply to a kernel's device tree before booting it.
+ */
+
+typedef struct DeviceTreeFixup
+{
+ // The function which does the fixing.
+ int (*fixup)(struct DeviceTreeFixup *fixup, DeviceTree *tree);
+
+ ListNode list_node;
+} DeviceTreeFixup;
+
+extern ListNode device_tree_fixups;
+
+int dt_apply_fixups(DeviceTree *tree);
+
+/*
+ * Structure defining mapping between arbitrary objects and the device tree
+ * path to the property corresponding to the object.
+ */
+typedef struct {
+ int force_create; /* If false - do not create a new node. */
+ const char *dt_path;
+ const char *key;
+} DtPathMap;
+
+/*
+ * Copy mac addresses from sysinfo table into the device tree. The mapping
+ * between the dt_maps entries and sysinfo mac address table elements is
+ * implicit, i.e. the device tree node found in the maps entry, gets assinged
+ * the mac address found in the sysinfo table, in the same order.
+ */
+int dt_set_mac_addresses(DeviceTree *tree, const DtPathMap *dt_maps);
+
+/*
+ * Copy WIFI calibration data from sysinfo table into the device tree. Each
+ * WIFI calibration blob stored the sysinfo table contains key and data. The
+ * key is used for mapping into the device tree path. The data becomes the
+ * contents of the device tree property at that path.
+ */
+int dt_set_wifi_calibration(DeviceTree *tree, const DtPathMap *maps);
+
+/*
+ * Retrieve Country Code data from VPD and add it into the device tree.
+ */
+int dt_set_wifi_country_code(DeviceTree *tree, const DtPathMap *maps);
+
+/*
+ * Init/retrieve the /reserved-memory/ node.
+ */
+DeviceTreeNode *dt_init_reserved_memory_node(DeviceTree *tree);
+
+#endif /* __BASE_DEVICE_TREE_H__ */
diff --git a/src/include/fit.h b/src/include/fit.h
new file mode 100644
index 0000000..22939be
--- /dev/null
+++ b/src/include/fit.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2013 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#ifndef __BOOT_FIT_H__
+#define __BOOT_FIT_H__
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "device_tree.h"
+#include "list.h"
+
+struct FitImageNode
+{
+ const char *name;
+ void *data;
+ uint32_t size;
+ int compression;
+
+ struct ListNode list_node;
+};
+
+struct FitConfigNode
+{
+ const char *name;
+ const char *kernel;
+ struct FitImageNode *kernel_node;
+ const char *fdt;
+ struct FitImageNode *fdt_node;
+ const char *ramdisk;
+ struct FitImageNode *ramdisk_node;
+ struct FdtProperty compat;
+ int compat_rank;
+ int compat_pos;
+
+ struct ListNode list_node;
+};
+
+/*
+ * Weak function to get the list of compat names.
+ * Has to be implemented on every board, that wants to use uImage FIT.
+ */
+void
+fit_get_compats_strings(char *fit_kernel_compat[10],
+ int *num_fit_kernel_compat);
+
+/*
+ * Unpack a FIT image into memory, choosing the right configuration through the
+ * compatible string set by fit_add_compat() and unflattening the corresponding
+ * kernel device tree.
+ */
+struct FitImageNode *fit_load(void *fit, struct DeviceTree **dt);
+
+/*
+ * Add a compatible string for the preferred kernel DT to the list for this
+ * platform. This should be called before the first fit_load() so it will be
+ * ranked as a better match than the default compatible strings. |compat| must
+ * stay accessible throughout depthcharge's runtime (i.e. not stack-allocated)!
+ */
+void fit_add_compat(const char *compat);
+
+void fit_add_ramdisk(struct DeviceTree *tree, void *ramdisk_addr, size_t ramdisk_size);
+
+#endif /* __BOOT_FIT_H__ */
diff --git a/src/include/list.h b/src/include/list.h
new file mode 100644
index 0000000..a541ce5
--- /dev/null
+++ b/src/include/list.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2012 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#ifndef __BASE_LIST_H__
+#define __BASE_LIST_H__
+
+#include <stddef.h>
+#include <stdint.h>
+
+//#include "container_of.h"
+
+typedef struct ListNode {
+ struct ListNode *next;
+ struct ListNode *prev;
+} ListNode;
+
+// Remove ListNode node from the doubly linked list it's a part of.
+void list_remove(ListNode *node);
+// Insert ListNode node after ListNode after in a doubly linked list.
+void list_insert_after(ListNode *node, ListNode *after);
+// Insert ListNode node before ListNode before in a doubly linked list.
+void list_insert_before(ListNode *node, ListNode *before);
+
+#define list_for_each(ptr, head, member) \
+ for ((ptr) = container_of((head).next, typeof(*(ptr)), member); \
+ &((ptr)->member); \
+ (ptr) = container_of((ptr)->member.next, \
+ typeof(*(ptr)), member))
+
+#endif /* __BASE_LIST_H__ */
diff --git a/src/include/ranges.h b/src/include/ranges.h
new file mode 100644
index 0000000..87b427d
--- /dev/null
+++ b/src/include/ranges.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2012 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#ifndef __BASE_RANGES_H__
+#define __BASE_RANGES_H__
+
+#include <stdint.h>
+
+/* A node in a linked list of edges, each at position "pos". */
+typedef struct RangesEdge {
+ struct RangesEdge *next;
+ uint64_t pos;
+} RangesEdge;
+
+/*
+ * Data describing ranges. Contains a linked list of edges between the ranges
+ * and the empty space between them.
+ */
+typedef struct Ranges {
+ RangesEdge head;
+} Ranges;
+
+/*
+ * Initializes the Ranges structure.
+ *
+ * @param ranges Ranges structure to initialize.
+ */
+void ranges_init(Ranges *ranges);
+
+/*
+ * Free memory associated with a Ranges structure, not including the structure
+ * itself.
+ *
+ * @param ranges Ranges structure to tear down.
+ */
+void ranges_teardown(Ranges *ranges);
+
+/*
+ * Adds a range to a collection of ranges.
+ *
+ * @param ranges Ranges structure to add the range to.
+ * @param start The start of the range.
+ * @param end The end of the range.
+ */
+void ranges_add(Ranges *ranges, uint64_t start, uint64_t end);
+
+/*
+ * Subtracts a range.
+ *
+ * @param ranges Ranges structure to subtract the range from.
+ * @param start The start of the region.
+ * @param end The end of the region.
+ */
+void ranges_sub(Ranges *ranges, uint64_t start, uint64_t end);
+
+typedef void (*RangesForEachFunc)(uint64_t start, uint64_t end, void *data);
+
+/*
+ * Runs a function on each range in Ranges.
+ *
+ * @param ranges Ranges structure to iterate over.
+ */
+void ranges_for_each(Ranges *ranges, RangesForEachFunc func, void *data);
+
+#endif /* __BASE_RANGES_H__ */
diff --git a/src/include/string.h b/src/include/string.h
index 7597323..2dd73a0 100644
--- a/src/include/string.h
+++ b/src/include/string.h
@@ -66,6 +66,26 @@
}
#endif
+/**
+ * Find a character in a string.
+ *
+ * @param s The string.
+ * @param c The character.
+ * @return A pointer to the last occurence of the character in the
+ * string, or NULL if the character was not encountered within the string.
+ */
+static inline char *strrchr(const char *s, int c)
+{
+ char *p = (char *)s + strlen(s);
+
+ for (; p >= s; p--) {
+ if (*p == c)
+ return p;
+ }
+
+ return NULL;
+}
+
static inline char *strncpy(char *to, const char *from, int count)
{
register char *ret = to;
diff --git a/src/lib/Makefile.inc b/src/lib/Makefile.inc
index 3ddf017..0bcef59 100644
--- a/src/lib/Makefile.inc
+++ b/src/lib/Makefile.inc
@@ -135,6 +135,13 @@
ramstage-y += b64_decode.c
ramstage-$(CONFIG_ACPI_NHLT) += nhlt.c
+ramstage-y += list.c
+ramstage-y += ranges.c
+ramstage-$(CONFIG_PAYLOAD_LINUX_UIMAGE) += device_tree.c
+ramstage-$(CONFIG_PAYLOAD_LINUX_UIMAGE) += fit.c
+ramstage-$(CONFIG_PAYLOAD_LINUX_UIMAGE) += uImage.c
+
+
romstage-y += cbmem_common.c
romstage-y += imd_cbmem.c
romstage-y += imd.c
diff --git a/src/lib/device_tree.c b/src/lib/device_tree.c
new file mode 100644
index 0000000..246d0f3
--- /dev/null
+++ b/src/lib/device_tree.c
@@ -0,0 +1,954 @@
+/*
+ * Copyright 2013 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <assert.h>
+#include <endian.h>
+#include <stdint.h>
+#include <console/console.h>
+#include <string.h>
+#include <endian.h>
+#include <stddef.h>
+#include <stdlib.h>
+
+#include "device_tree.h"
+
+/*
+ * Functions for picking apart flattened trees.
+ */
+
+static uint32_t size32(uint32_t val)
+{
+ return (val + sizeof(uint32_t) - 1) / sizeof(uint32_t);
+}
+
+int fdt_next_property(void *blob, uint32_t offset, FdtProperty *prop)
+{
+ FdtHeader *header = (FdtHeader *)blob;
+ uint32_t *ptr = (uint32_t *)(((uint8_t *)blob) + offset);
+
+ int index = 0;
+ if (be32toh(ptr[index++]) != TokenProperty)
+ return 0;
+
+ uint32_t size = be32toh(ptr[index++]);
+ uint32_t name_offset = be32toh(ptr[index++]);
+ name_offset += be32toh(header->strings_offset);
+
+ if (prop) {
+ prop->name = (char *)((uint8_t *)blob + name_offset);
+ prop->data = &ptr[index];
+ prop->size = size;
+ }
+
+ index += size32(size);
+
+ return index * 4;
+}
+
+int fdt_node_name(void *blob, uint32_t offset, const char **name)
+{
+ uint8_t *ptr = ((uint8_t *)blob) + offset;
+ if (be32toh(*(uint32_t *)ptr) != TokenBeginNode)
+ return 0;
+
+ ptr += 4;
+ if (name)
+ *name = (char *)ptr;
+ return size32(strlen((char *)ptr) + 1) * sizeof(uint32_t) + 4;
+}
+
+
+
+/*
+ * Functions for printing flattened trees.
+ */
+
+static void print_indent(int depth)
+{
+ while (depth--)
+ printk(BIOS_DEBUG, " ");
+}
+
+static void print_property(FdtProperty *prop, int depth)
+{
+ print_indent(depth);
+ printk(BIOS_DEBUG, "prop \"%s\" (%d bytes).\n", prop->name, prop->size);
+ print_indent(depth + 1);
+ for (int i = 0; i < MIN(25, prop->size); i++) {
+ printk(BIOS_DEBUG, "%02x ", ((uint8_t *)prop->data)[i]);
+ }
+ if (prop->size > 25)
+ printk(BIOS_DEBUG, "...");
+ printk(BIOS_DEBUG, "\n");
+}
+
+static int print_flat_node(void *blob, uint32_t start_offset, int depth)
+{
+ int offset = start_offset;
+ const char *name;
+ int size;
+
+ size = fdt_node_name(blob, offset, &name);
+ if (!size)
+ return 0;
+ offset += size;
+
+ print_indent(depth);
+ printk(BIOS_DEBUG, "name = %s\n", name);
+
+ FdtProperty prop;
+ while ((size = fdt_next_property(blob, offset, &prop))) {
+ print_property(&prop, depth + 1);
+
+ offset += size;
+ }
+
+ while ((size = print_flat_node(blob, offset, depth + 1)))
+ offset += size;
+
+ return offset - start_offset + sizeof(uint32_t);
+}
+
+void fdt_print_node(void *blob, uint32_t offset)
+{
+ print_flat_node(blob, offset, 0);
+}
+
+
+
+/*
+ * A utility function to skip past nodes in flattened trees.
+ */
+
+int fdt_skip_node(void *blob, uint32_t start_offset)
+{
+ int offset = start_offset;
+ int size;
+
+ const char *name;
+ size = fdt_node_name(blob, offset, &name);
+ if (!size)
+ return 0;
+ offset += size;
+
+ while ((size = fdt_next_property(blob, offset, NULL)))
+ offset += size;
+
+ while ((size = fdt_skip_node(blob, offset)))
+ offset += size;
+
+ return offset - start_offset + sizeof(uint32_t);
+}
+
+
+
+/*
+ * Functions to turn a flattened tree into an unflattened one.
+ */
+
+static DeviceTreeNode node_cache[1000];
+static int node_counter = 0;
+static DeviceTreeProperty prop_cache[5000];
+static int prop_counter = 0;
+
+/*
+ * Libpayload's malloc() has linear allocation complexity and goes completely
+ * mental after a few thousand small requests. This little hack will absorb
+ * the worst of it to avoid increasing boot time for no reason.
+ */
+static DeviceTreeNode *alloc_node(void)
+{
+ if (node_counter >= ARRAY_SIZE(node_cache)) {
+ DeviceTreeNode *buf = malloc(sizeof(DeviceTreeNode));
+ if (!buf)
+ return NULL;
+ memset(buf, 0, sizeof(*buf));
+ return buf;
+ }
+ return &node_cache[node_counter++];
+}
+
+static DeviceTreeProperty *alloc_prop(void)
+{
+ if (prop_counter >= ARRAY_SIZE(prop_cache)) {
+ DeviceTreeProperty *buf = malloc(sizeof(DeviceTreeProperty));
+ if (!buf)
+ return NULL;
+ memset(buf, 0, sizeof(*buf));
+ return buf;
+ }
+ return &prop_cache[prop_counter++];
+}
+
+static int fdt_unflatten_node(void *blob, uint32_t start_offset,
+ DeviceTreeNode **new_node)
+{
+ ListNode *last;
+ int offset = start_offset;
+ const char *name;
+ int size;
+
+ size = fdt_node_name(blob, offset, &name);
+ if (!size)
+ return 0;
+ offset += size;
+
+ DeviceTreeNode *node = alloc_node();
+ *new_node = node;
+ node->name = name;
+
+ FdtProperty fprop;
+ last = &node->properties;
+ while ((size = fdt_next_property(blob, offset, &fprop))) {
+ DeviceTreeProperty *prop = alloc_prop();
+ prop->prop = fprop;
+
+ list_insert_after(&prop->list_node, last);
+ last = &prop->list_node;
+
+ offset += size;
+ }
+
+ DeviceTreeNode *child;
+ last = &node->children;
+ while ((size = fdt_unflatten_node(blob, offset, &child))) {
+ list_insert_after(&child->list_node, last);
+ last = &child->list_node;
+
+ offset += size;
+ }
+
+ return offset - start_offset + sizeof(uint32_t);
+}
+
+static int fdt_unflatten_map_entry(void *blob, uint32_t offset,
+ DeviceTreeReserveMapEntry **new_entry)
+{
+ uint64_t *ptr = (uint64_t *)(((uint8_t *)blob) + offset);
+ uint64_t start = be64toh(ptr[0]);
+ uint64_t size = be64toh(ptr[1]);
+
+ if (!size)
+ return 0;
+
+ DeviceTreeReserveMapEntry *entry = malloc(sizeof(*entry));
+ memset(entry, 0, sizeof(*entry));
+ *new_entry = entry;
+ entry->start = start;
+ entry->size = size;
+
+ return sizeof(uint64_t) * 2;
+}
+
+DeviceTree *fdt_unflatten(void *blob)
+{
+ DeviceTree *tree = malloc(sizeof(*tree));
+ FdtHeader *header = (FdtHeader *)blob;
+
+ memset(tree, 0, sizeof(*tree));
+ tree->header = header;
+
+ uint32_t struct_offset = be32toh(header->structure_offset);
+ uint32_t strings_offset = be32toh(header->strings_offset);
+ uint32_t reserve_offset = be32toh(header->reserve_map_offset);
+ uint32_t min_offset = 0;
+ min_offset = MIN(struct_offset, strings_offset);
+ min_offset = MIN(min_offset, reserve_offset);
+ // Assume everything up to the first non-header component is part of
+ // the header and needs to be preserved. This will protect us against
+ // new elements being added in the future.
+ tree->header_size = min_offset;
+
+ DeviceTreeReserveMapEntry *entry;
+ uint32_t offset = reserve_offset;
+ int size;
+ ListNode *last = &tree->reserve_map;
+ while ((size = fdt_unflatten_map_entry(blob, offset, &entry))) {
+ list_insert_after(&entry->list_node, last);
+ last = &entry->list_node;
+
+ offset += size;
+ }
+
+ fdt_unflatten_node(blob, struct_offset, &tree->root);
+
+ return tree;
+}
+
+
+
+/*
+ * Functions to find the size of device tree would take if it was flattened.
+ */
+
+static void dt_flat_prop_size(DeviceTreeProperty *prop, uint32_t *struct_size,
+ uint32_t *strings_size)
+{
+ // Starting token.
+ *struct_size += sizeof(uint32_t);
+ // Size.
+ *struct_size += sizeof(uint32_t);
+ // Name offset.
+ *struct_size += sizeof(uint32_t);
+ // Property value.
+ *struct_size += size32(prop->prop.size) * sizeof(uint32_t);
+
+ // Property name.
+ *strings_size += strlen(prop->prop.name) + 1;
+}
+
+static void dt_flat_node_size(DeviceTreeNode *node, uint32_t *struct_size,
+ uint32_t *strings_size)
+{
+ // Starting token.
+ *struct_size += sizeof(uint32_t);
+ // Node name.
+ *struct_size += size32(strlen(node->name) + 1) * sizeof(uint32_t);
+
+ DeviceTreeProperty *prop;
+ list_for_each(prop, node->properties, list_node)
+ dt_flat_prop_size(prop, struct_size, strings_size);
+
+ DeviceTreeNode *child;
+ list_for_each(child, node->children, list_node)
+ dt_flat_node_size(child, struct_size, strings_size);
+
+ // End token.
+ *struct_size += sizeof(uint32_t);
+}
+
+uint32_t dt_flat_size(DeviceTree *tree)
+{
+ uint32_t size = tree->header_size;
+ DeviceTreeReserveMapEntry *entry;
+ list_for_each(entry, tree->reserve_map, list_node)
+ size += sizeof(uint64_t) * 2;
+ size += sizeof(uint64_t) * 2;
+
+ uint32_t struct_size = 0;
+ uint32_t strings_size = 0;
+ dt_flat_node_size(tree->root, &struct_size, &strings_size);
+
+ size += struct_size;
+ // End token.
+ size += sizeof(uint32_t);
+
+ size += strings_size;
+
+ return size;
+}
+
+
+
+/*
+ * Functions to flatten a device tree.
+ */
+
+static void dt_flatten_map_entry(DeviceTreeReserveMapEntry *entry,
+ void **map_start)
+{
+ ((uint64_t *)*map_start)[0] = htobe64(entry->start);
+ ((uint64_t *)*map_start)[1] = htobe64(entry->size);
+ *map_start = ((uint8_t *)*map_start) + sizeof(uint64_t) * 2;
+}
+
+static void dt_flatten_prop(DeviceTreeProperty *prop, void **struct_start,
+ void *strings_base, void **strings_start)
+{
+ uint8_t *dstruct = (uint8_t *)*struct_start;
+ uint8_t *dstrings = (uint8_t *)*strings_start;
+
+ *((uint32_t *)dstruct) = htobe32(TokenProperty);
+ dstruct += sizeof(uint32_t);
+
+ *((uint32_t *)dstruct) = htobe32(prop->prop.size);
+ dstruct += sizeof(uint32_t);
+
+ uint32_t name_offset = (uintptr_t)dstrings - (uintptr_t)strings_base;
+ *((uint32_t *)dstruct) = htobe32(name_offset);
+ dstruct += sizeof(uint32_t);
+
+ strcpy((char *)dstrings, prop->prop.name);
+ dstrings += strlen(prop->prop.name) + 1;
+
+ memcpy(dstruct, prop->prop.data, prop->prop.size);
+ dstruct += size32(prop->prop.size) * 4;
+
+ *struct_start = dstruct;
+ *strings_start = dstrings;
+}
+
+static void dt_flatten_node(DeviceTreeNode *node, void **struct_start,
+ void *strings_base, void **strings_start)
+{
+ uint8_t *dstruct = (uint8_t *)*struct_start;
+ uint8_t *dstrings = (uint8_t *)*strings_start;
+
+ *((uint32_t *)dstruct) = htobe32(TokenBeginNode);
+ dstruct += sizeof(uint32_t);
+
+ strcpy((char *)dstruct, node->name);
+ dstruct += size32(strlen(node->name) + 1) * 4;
+
+ DeviceTreeProperty *prop;
+ list_for_each(prop, node->properties, list_node)
+ dt_flatten_prop(prop, (void **)&dstruct, strings_base,
+ (void **)&dstrings);
+
+ DeviceTreeNode *child;
+ list_for_each(child, node->children, list_node)
+ dt_flatten_node(child, (void **)&dstruct, strings_base,
+ (void **)&dstrings);
+
+ *((uint32_t *)dstruct) = htobe32(TokenEndNode);
+ dstruct += sizeof(uint32_t);
+
+ *struct_start = dstruct;
+ *strings_start = dstrings;
+}
+
+void dt_flatten(DeviceTree *tree, void *start_dest)
+{
+ uint8_t *dest = (uint8_t *)start_dest;
+
+ memcpy(dest, tree->header, tree->header_size);
+ FdtHeader *header = (FdtHeader *)dest;
+ dest += tree->header_size;
+
+ DeviceTreeReserveMapEntry *entry;
+ list_for_each(entry, tree->reserve_map, list_node)
+ dt_flatten_map_entry(entry, (void **)&dest);
+ ((uint64_t *)dest)[0] = ((uint64_t *)dest)[1] = 0;
+ dest += sizeof(uint64_t) * 2;
+
+ uint32_t struct_size = 0;
+ uint32_t strings_size = 0;
+ dt_flat_node_size(tree->root, &struct_size, &strings_size);
+
+ uint8_t *struct_start = dest;
+ header->structure_offset = htobe32(dest - (uint8_t *)start_dest);
+ header->structure_size = htobe32(struct_size);
+ dest += struct_size;
+
+ *((uint32_t *)dest) = htobe32(TokenEnd);
+ dest += sizeof(uint32_t);
+
+ uint8_t *strings_start = dest;
+ header->strings_offset = htobe32(dest - (uint8_t *)start_dest);
+ header->strings_size = htobe32(strings_size);
+ dest += strings_size;
+
+ dt_flatten_node(tree->root, (void **)&struct_start, strings_start,
+ (void **)&strings_start);
+
+ header->totalsize = htobe32(dest - (uint8_t *)start_dest);
+}
+
+
+
+/*
+ * Functions for printing a non-flattened device tree.
+ */
+
+static void print_node(DeviceTreeNode *node, int depth)
+{
+ print_indent(depth);
+ printk(BIOS_DEBUG, "name = %s\n", node->name);
+
+ DeviceTreeProperty *prop;
+ list_for_each(prop, node->properties, list_node)
+ print_property(&prop->prop, depth + 1);
+
+ DeviceTreeNode *child;
+ list_for_each(child, node->children, list_node)
+ print_node(child, depth + 1);
+}
+
+void dt_print_node(DeviceTreeNode *node)
+{
+ print_node(node, 0);
+}
+
+
+
+/*
+ * Functions for reading and manipulating an unflattened device tree.
+ */
+
+/*
+ * Read #address-cells and #size-cells properties from a node.
+ *
+ * @param node The device tree node to read from.
+ * @param addrcp Pointer to store #address-cells in, skipped if NULL.
+ * @param sizecp Pointer to store #size-cells in, skipped if NULL.
+ */
+void dt_read_cell_props(DeviceTreeNode *node, u32 *addrcp, u32 *sizecp)
+{
+ DeviceTreeProperty *prop;
+ list_for_each(prop, node->properties, list_node) {
+ if (addrcp && !strcmp("#address-cells", prop->prop.name))
+ *addrcp = be32toh(*(u32 *)prop->prop.data);
+ if (sizecp && !strcmp("#size-cells", prop->prop.name))
+ *sizecp = be32toh(*(u32 *)prop->prop.data);
+ }
+}
+
+/*
+ * Find a node from a device tree path, relative to a parent node.
+ *
+ * @param parent The node from which to start the relative path lookup.
+ * @param path An array of path component strings that will be looked
+ * up in order to find the node. Must be terminated with
+ * a NULL pointer. Example: {'firmware', 'coreboot', NULL}
+ * @param addrcp Pointer that will be updated with any #address-cells
+ * value found in the path. May be NULL to ignore.
+ * @param sizecp Pointer that will be updated with any #size-cells
+ * value found in the path. May be NULL to ignore.
+ * @param create 1: Create node(s) if not found. 0: Return NULL instead.
+ * @return The found/created node, or NULL.
+ */
+DeviceTreeNode *dt_find_node(DeviceTreeNode *parent, const char **path,
+ u32 *addrcp, u32 *sizecp, int create)
+{
+ DeviceTreeNode *node, *found = NULL;
+
+ // Update #address-cells and #size-cells for this level.
+ dt_read_cell_props(parent, addrcp, sizecp);
+
+ if (!*path)
+ return parent;
+
+ // Find the next node in the path, if it exists.
+ list_for_each(node, parent->children, list_node) {
+ if (!strcmp(node->name, *path)) {
+ found = node;
+ break;
+ }
+ }
+
+ // Otherwise create it or return NULL.
+ if (!found) {
+ if (!create)
+ return NULL;
+
+ found = alloc_node();
+ found->name = strdup(*path);
+ if (!found->name)
+ return NULL;
+
+ list_insert_after(&found->list_node, &parent->children);
+ }
+
+ return dt_find_node(found, path + 1, addrcp, sizecp, create);
+}
+
+/*
+ * Find a node from a string device tree path, relative to a parent node.
+ *
+ * @param parent The node from which to start the relative path lookup.
+ * @param path A string representing a path in the device tree, with
+ * nodes separated by '/'. Example: "soc/firmware/coreboot"
+ * @param addrcp Pointer that will be updated with any #address-cells
+ * value found in the path. May be NULL to ignore.
+ * @param sizecp Pointer that will be updated with any #size-cells
+ * value found in the path. May be NULL to ignore.
+ * @param create 1: Create node(s) if not found. 0: Return NULL instead.
+ * @return The found/created node, or NULL.
+ *
+ * It is the caller responsibility to provide the correct path string, namely
+ * not starting or ending with a '/', and not having "//" anywhere in it.
+ */
+DeviceTreeNode *dt_find_node_by_path(DeviceTreeNode *parent, const char *path,
+ u32 *addrcp, u32 *sizecp, int create)
+{
+ char *dup_path = strdup(path);
+ /* Hopefully enough depth for any node. */
+ const char *path_array[15];
+ int i;
+ char *next_slash;
+ DeviceTreeNode *node = NULL;
+
+ if (!dup_path)
+ return NULL;
+
+ next_slash = dup_path;
+ path_array[0] = dup_path;
+ for (i = 1; i < (ARRAY_SIZE(path_array) - 1); i++) {
+
+ next_slash = strchr(next_slash, '/');
+ if (!next_slash)
+ break;
+
+ *next_slash++ = '\0';
+ path_array[i] = next_slash;
+ }
+
+ if (!next_slash) {
+ path_array[i] = NULL;
+ node = dt_find_node(parent, path_array,
+ addrcp, sizecp, create);
+ }
+
+ free(dup_path);
+ return node;
+}
+
+/*
+ * Check if given node is compatible.
+ *
+ * @param node The node which is to be checked for compatible property.
+ * @param compat The compatible string to match.
+ * @return 1 = compatible, 0 = not compatible.
+ */
+static int dt_check_compat_match(DeviceTreeNode *node, const char *compat)
+{
+ DeviceTreeProperty *prop;
+
+ list_for_each(prop, node->properties, list_node) {
+ if (!strcmp("compatible", prop->prop.name)) {
+ size_t bytes = prop->prop.size;
+ const char *str = prop->prop.data;
+ while (bytes > 0) {
+ if (!strncmp(compat, str, bytes))
+ return 1;
+ size_t len = strnlen(str, bytes) + 1;
+ if (bytes <= len)
+ break;
+ str += len;
+ bytes -= len;
+ }
+ break;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * Find a node from a compatible string, in the subtree of a parent node.
+ *
+ * @param parent The parent node under which to look.
+ * @param compat The compatible string to find.
+ * @return The found node, or NULL.
+ */
+DeviceTreeNode *dt_find_compat(DeviceTreeNode *parent, const char *compat)
+{
+ // Check if the parent node itself is compatible.
+ if (dt_check_compat_match(parent, compat))
+ return parent;
+
+ DeviceTreeNode *child;
+ list_for_each(child, parent->children, list_node) {
+ DeviceTreeNode *found = dt_find_compat(child, compat);
+ if (found)
+ return found;
+ }
+
+ return NULL;
+}
+
+/*
+ * Find the next compatible child of a given parent. All children upto the
+ * child passed in by caller are ignored. If child is NULL, it considers all the
+ * children to find the first child which is compatible.
+ *
+ * @param parent The parent node under which to look.
+ * @param child The child node to start search from (exclusive). If NULL
+ * consider all children.
+ * @param compat The compatible string to find.
+ * @return The found node, or NULL.
+ */
+DeviceTreeNode *dt_find_next_compat_child(DeviceTreeNode *parent,
+ DeviceTreeNode *child,
+ const char *compat)
+{
+ DeviceTreeNode *next;
+ int ignore = 0;
+
+ if (child)
+ ignore = 1;
+
+ list_for_each(next, parent->children, list_node) {
+ if (ignore) {
+ if (child == next)
+ ignore = 0;
+ continue;
+ }
+
+ if (dt_check_compat_match(next, compat))
+ return next;
+ }
+
+ return NULL;
+}
+
+/*
+ * Find a node with matching property value, in the subtree of a parent node.
+ *
+ * @param parent The parent node under which to look.
+ * @param name The property name to look for.
+ * @param data The property value to look for.
+ * @param size The property size.
+ */
+DeviceTreeNode *dt_find_prop_value(DeviceTreeNode *parent, const char *name,
+ void *data, size_t size)
+{
+ DeviceTreeProperty *prop;
+
+ /* Check if parent itself has the required property value. */
+ list_for_each(prop, parent->properties, list_node) {
+ if (!strcmp(name, prop->prop.name)) {
+ size_t bytes = prop->prop.size;
+ void *prop_data = prop->prop.data;
+ if (size != bytes)
+ break;
+ if (!memcmp(data, prop_data, size))
+ return parent;
+ break;
+ }
+ }
+
+ DeviceTreeNode *child;
+ list_for_each(child, parent->children, list_node) {
+ DeviceTreeNode *found = dt_find_prop_value(child, name, data,
+ size);
+ if (found)
+ return found;
+ }
+ return NULL;
+}
+
+/*
+ * Write an arbitrary sized big-endian integer into a pointer.
+ *
+ * @param dest Pointer to the DT property data buffer to write.
+ * @param src The integer to write (in CPU endianess).
+ * @param length the length of the destination integer in bytes.
+ */
+void dt_write_int(u8 *dest, u64 src, size_t length)
+{
+ while (length--) {
+ dest[length] = (u8)src;
+ src >>= 8;
+ }
+}
+
+/*
+ * Add an arbitrary property to a node, or update it if it already exists.
+ *
+ * @param node The device tree node to add to.
+ * @param name The name of the new property.
+ * @param data The raw data blob to be stored in the property.
+ * @param size The size of data in bytes.
+ */
+void dt_add_bin_prop(DeviceTreeNode *node, char *name, void *data, size_t size)
+{
+ DeviceTreeProperty *prop;
+
+ list_for_each(prop, node->properties, list_node) {
+ if (!strcmp(prop->prop.name, name)) {
+ prop->prop.data = data;
+ prop->prop.size = size;
+ return;
+ }
+ }
+
+ prop = alloc_prop();
+ list_insert_after(&prop->list_node, &node->properties);
+ prop->prop.name = name;
+ prop->prop.data = data;
+ prop->prop.size = size;
+}
+
+/*
+ * Find given string property in a node and return its content.
+ *
+ * @param node The device tree node to search.
+ * @param name The name of the property.
+ * @return The found string, or NULL.
+ */
+const char *dt_find_string_prop(DeviceTreeNode *node, const char *name)
+{
+ void *content;
+ size_t size;
+
+ dt_find_bin_prop(node, name, &content, &size);
+
+ return content;
+}
+
+/*
+ * Find given property in a node.
+ *
+ * @param node The device tree node to search.
+ * @param name The name of the property.
+ * @param data Pointer to return raw data blob in the property.
+ * @param size Pointer to return the size of data in bytes.
+ */
+void dt_find_bin_prop(DeviceTreeNode *node, const char *name, void **data,
+ size_t *size)
+{
+ DeviceTreeProperty *prop;
+
+ *data = NULL;
+ *size = 0;
+
+ list_for_each(prop, node->properties, list_node) {
+ if (!strcmp(prop->prop.name, name)) {
+ *data = prop->prop.data;
+ *size = prop->prop.size;
+ return;
+ }
+ }
+}
+
+/*
+ * Add a string property to a node, or update it if it already exists.
+ *
+ * @param node The device tree node to add to.
+ * @param name The name of the new property.
+ * @param str The zero-terminated string to be stored in the property.
+ */
+void dt_add_string_prop(DeviceTreeNode *node, char *name, char *str)
+{
+ dt_add_bin_prop(node, name, str, strlen(str) + 1);
+}
+
+/*
+ * Add a 32-bit integer property to a node, or update it if it already exists.
+ *
+ * @param node The device tree node to add to.
+ * @param name The name of the new property.
+ * @param val The integer to be stored in the property.
+ */
+void dt_add_u32_prop(DeviceTreeNode *node, char *name, u32 val)
+{
+ u32 *val_ptr = malloc(sizeof(val));
+ *val_ptr = htobe32(val);
+ dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
+}
+
+/*
+ * Add a 'reg' address list property to a node, or update it if it exists.
+ *
+ * @param node The device tree node to add to.
+ * @param addrs Array of address values to be stored in the property.
+ * @param sizes Array of corresponding size values to 'addrs'.
+ * @param count Number of values in 'addrs' and 'sizes' (must be equal).
+ * @param addr_cells Value of #address-cells property valid for this node.
+ * @param size_cells Value of #size-cells property valid for this node.
+ */
+void dt_add_reg_prop(DeviceTreeNode *node, u64 *addrs, u64 *sizes,
+ int count, u32 addr_cells, u32 size_cells)
+{
+ int i;
+ size_t length = (addr_cells + size_cells) * sizeof(u32) * count;
+ u8 *data = malloc(length);
+ u8 *cur = data;
+
+ for (i = 0; i < count; i++) {
+ dt_write_int(cur, addrs[i], addr_cells * sizeof(u32));
+ cur += addr_cells * sizeof(u32);
+ dt_write_int(cur, sizes[i], size_cells * sizeof(u32));
+ cur += size_cells * sizeof(u32);
+ }
+
+ dt_add_bin_prop(node, "reg", data, length);
+}
+
+/*
+ * Fixups to apply to a kernel's device tree before booting it.
+ */
+
+ListNode device_tree_fixups;
+
+int dt_apply_fixups(DeviceTree *tree)
+{
+ DeviceTreeFixup *fixup;
+ list_for_each(fixup, device_tree_fixups, list_node) {
+ assert(fixup->fixup);
+ if (fixup->fixup(fixup, tree))
+ return 1;
+ }
+ return 0;
+}
+
+int dt_set_bin_prop_by_path(DeviceTree *tree, const char *path,
+ void *data, size_t data_size, int create)
+{
+ char *path_copy, *prop_name;
+ DeviceTreeNode *dt_node;
+
+ path_copy = strdup(path);
+
+ if (!path_copy) {
+ printk(BIOS_ERR, "Failed to allocate a copy of path %s\n", path);
+ return 1;
+ }
+
+ prop_name = strrchr(path_copy, '/');
+ if (!prop_name) {
+ printk(BIOS_ERR, "Path %s does not include '/'\n", path);
+ free(path_copy);
+ return 1;
+ }
+
+ *prop_name++ = '\0'; /* Separate path from the property name. */
+
+ dt_node = dt_find_node_by_path(tree->root, path_copy, NULL,
+ NULL, create);
+
+ if (!dt_node) {
+ printk(BIOS_ERR, "Failed to %s %s in the device tree\n",
+ create ? "create" : "find", path_copy);
+ free(path_copy);
+ return 1;
+ }
+
+ dt_add_bin_prop(dt_node, prop_name, data, data_size);
+
+ return 0;
+}
+
+/*
+ * Prepare the /reserved-memory/ node.
+ *
+ * Technically, this can be called more than one time, to init and/or retrieve
+ * the node. But dt_add_u32_prop() may leak a bit of memory if you do.
+ *
+ * @tree: Device tree to add/retrieve from.
+ * @return: The /reserved-memory/ node (or NULL, if error).
+ */
+DeviceTreeNode *dt_init_reserved_memory_node(DeviceTree *tree)
+{
+ DeviceTreeNode *reserved;
+ u32 addr = 0, size = 0;
+
+ reserved = dt_find_node_by_path(tree->root, "reserved-memory", &addr,
+ &size, 1);
+ if (!reserved)
+ return NULL;
+
+ // Binding doc says this should have the same #{address,size}-cells as
+ // the root.
+ dt_add_u32_prop(reserved, "#address-cells", addr);
+ dt_add_u32_prop(reserved, "#size-cells", size);
+ // Binding doc says this should be empty (i.e., 1:1 mapping from root).
+ dt_add_bin_prop(reserved, "ranges", NULL, 0);
+
+ return reserved;
+}
diff --git a/src/lib/fit.c b/src/lib/fit.c
new file mode 100644
index 0000000..9d8dee5
--- /dev/null
+++ b/src/lib/fit.c
@@ -0,0 +1,529 @@
+/*
+ * Copyright 2013 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <assert.h>
+#include <endian.h>
+#include <stdint.h>
+#include <cbmem.h>
+#include <boot/coreboot_tables.h>
+#include <stdlib.h>
+#include <string.h>
+#include <cbfs.h>
+#include <program_loading.h>
+#include <timestamp.h>
+#include <ranges.h>
+#include <fit.h>
+
+static ListNode image_nodes;
+static ListNode config_nodes;
+
+__attribute__((weak)) void
+fit_get_compats_strings(char *fit_kernel_compat[10], int *num_fit_kernel_compat)
+{
+ *num_fit_kernel_compat = 0;
+}
+
+static void image_node(struct DeviceTreeNode *node)
+{
+ struct FitImageNode *image = malloc(sizeof(*image));
+ memset(image, 0, sizeof(*image));
+
+ image->compression = -1;
+
+ image->name = node->name;
+
+ struct DeviceTreeProperty *prop;
+ list_for_each(prop, node->properties, list_node) {
+ if (!strcmp("data", prop->prop.name)) {
+ image->data = prop->prop.data;
+ image->size = prop->prop.size;
+ } else if (!strcmp("compression", prop->prop.name)) {
+ if (!strcmp("none", prop->prop.data))
+ image->compression = CBFS_COMPRESS_NONE;
+ else if (!strcmp("lzma", prop->prop.data))
+ image->compression = CBFS_COMPRESS_LZMA;
+ else if (!strcmp("lz4", prop->prop.data))
+ image->compression = CBFS_COMPRESS_LZ4;
+ else
+ image->compression = -1;
+ }
+ }
+
+ list_insert_after(&image->list_node, &image_nodes);
+}
+
+static void config_node(struct DeviceTreeNode *node)
+{
+ struct FitConfigNode *config = malloc(sizeof(*config));
+ memset(config, 0, sizeof(*config));
+
+ config->name = node->name;
+
+ struct DeviceTreeProperty *prop;
+ list_for_each(prop, node->properties, list_node) {
+ if (!strcmp("kernel", prop->prop.name))
+ config->kernel = prop->prop.data;
+ else if (!strcmp("fdt", prop->prop.name))
+ config->fdt = prop->prop.data;
+ else if (!strcmp("ramdisk", prop->prop.name))
+ config->ramdisk = prop->prop.data;
+ }
+
+ list_insert_after(&config->list_node, &config_nodes);
+}
+
+static void fit_unpack(struct DeviceTree *tree, const char **default_config)
+{
+ assert(tree && tree->root);
+
+ struct DeviceTreeNode *top;
+ list_for_each(top, tree->root->children, list_node) {
+ struct DeviceTreeNode *child;
+ if (!strcmp("images", top->name)) {
+
+ list_for_each(child, top->children, list_node)
+ image_node(child);
+
+ } else if (!strcmp("configurations", top->name)) {
+
+ struct DeviceTreeProperty *prop;
+ list_for_each(prop, top->properties, list_node) {
+ if (!strcmp("default", prop->prop.name) &&
+ default_config)
+ *default_config = prop->prop.data;
+ }
+
+ list_for_each(child, top->children, list_node)
+ config_node(child);
+ }
+ }
+}
+
+static struct FitImageNode *find_image(const char *name)
+{
+ struct FitImageNode *image;
+ list_for_each(image, image_nodes, list_node) {
+ if (!strcmp(image->name, name))
+ return image;
+ }
+ return NULL;
+}
+
+static int fdt_find_compat(void *blob, uint32_t start_offset, struct FdtProperty *prop)
+{
+ int offset = start_offset;
+ int size;
+
+ size = fdt_node_name(blob, offset, NULL);
+ if (!size)
+ return -1;
+ offset += size;
+
+ while ((size = fdt_next_property(blob, offset, prop))) {
+ if (!strcmp("compatible", prop->name))
+ return 0;
+
+ offset += size;
+ }
+
+ prop->name = NULL;
+ return -1;
+}
+
+static int fit_check_compat(struct FdtProperty *compat_prop, const char *compat_name)
+{
+ int bytes = compat_prop->size;
+ const char *compat_str = compat_prop->data;
+
+ for (int pos = 0; bytes && compat_str[0]; pos++) {
+ if (!strncmp(compat_str, compat_name, bytes))
+ return pos;
+ int len = strlen(compat_str) + 1;
+ compat_str += len;
+ bytes -= len;
+ }
+ return -1;
+}
+
+static void update_chosen(struct DeviceTree *tree, char *cmd_line)
+{
+ const char *path[] = { "chosen", NULL };
+ struct DeviceTreeNode *node = dt_find_node(tree->root, path, NULL, NULL, 1);
+
+ dt_add_string_prop(node, "bootargs", cmd_line);
+}
+
+void fit_add_ramdisk(struct DeviceTree *tree, void *ramdisk_addr, size_t ramdisk_size)
+{
+ const char *path[] = { "chosen", NULL };
+ struct DeviceTreeNode *node = dt_find_node(tree->root, path, NULL, NULL, 1);
+
+ /* Warning: this assumes the ramdisk is currently located below 4GiB. */
+ u32 start = (uintptr_t)ramdisk_addr;
+ u32 end = start + ramdisk_size;
+
+ dt_add_u32_prop(node, "linux,initrd-start", start);
+ dt_add_u32_prop(node, "linux,initrd-end", end);
+}
+
+static void update_reserve_map(uint64_t start, uint64_t end, void *data)
+{
+ DeviceTree *tree = (DeviceTree *)data;
+
+ DeviceTreeReserveMapEntry *entry = malloc(sizeof(*entry));
+ memset(entry, 0, sizeof(*entry));
+
+ entry->start = start;
+ entry->size = end - start;
+
+ list_insert_after(&entry->list_node, &tree->reserve_map);
+}
+
+typedef struct EntryParams
+{
+ unsigned addr_cells;
+ unsigned size_cells;
+ void *data;
+} EntryParams;
+
+static uint64_t max_range(unsigned size_cells)
+{
+ // Split up ranges who's sizes are too large to fit in #size-cells.
+ // The largest value we can store isn't a power of two, so we'll round
+ // down to make the math easier.
+ return 0x1ULL << (size_cells * 32 - 1);
+}
+
+static void count_entries(u64 start, u64 end, void *pdata)
+{
+ EntryParams *params = (EntryParams *)pdata;
+ unsigned *count = (unsigned *)params->data;
+ u64 size = end - start;
+ u64 max_size = max_range(params->size_cells);
+ *count += ALIGN_UP(size, max_size) / max_size;
+}
+
+static void update_mem_property(u64 start, u64 end, void *pdata)
+{
+ EntryParams *params = (EntryParams *)pdata;
+ u8 *data = (u8 *)params->data;
+ u64 full_size = end - start;
+ while (full_size) {
+ const u64 max_size = max_range(params->size_cells);
+ const u64 size = MIN(max_size, full_size);
+
+ dt_write_int(data, start, params->addr_cells * sizeof(u32));
+ data += params->addr_cells * sizeof(uint32_t);
+ start += size;
+
+ dt_write_int(data, size, params->size_cells * sizeof(u32));
+ data += params->size_cells * sizeof(uint32_t);
+ full_size -= size;
+ }
+ params->data = data;
+}
+
+static struct lb_memory *lb_memory(void)
+{
+ const struct lb_header *head;
+ const struct lb_record *rec;
+ size_t i;
+
+ head = cbmem_find(CBMEM_ID_CBTABLE);
+ if (!head)
+ return NULL;
+
+ i = head->table_entries;
+ rec = (struct lb_record *)(((uint8_t *)head) + head->header_bytes);
+
+ while (i--) {
+ if (rec->tag == LB_TAG_FORWARD) {
+ struct lb_forward *forward = (struct lb_forward *)rec;
+ head = (void *)forward->forward;
+ break;
+ }
+ rec = (struct lb_record *)(((uint8_t *)rec) + rec->size);
+ }
+
+ i = head->table_entries;
+ rec = (struct lb_record *)(((uint8_t *)head) + head->header_bytes);
+ while (i--) {
+ if (rec->tag == LB_TAG_MEMORY)
+ return (struct lb_memory *)rec;
+ rec = (struct lb_record *)(((uint8_t *)rec) + rec->size);
+ }
+
+ return NULL;
+}
+
+static void update_memory(struct DeviceTree *tree)
+{
+ struct lb_memory *lb_mem;
+ struct Ranges mem;
+ struct Ranges reserved;
+ struct DeviceTreeNode *node;
+ u32 addr_cells = 1, size_cells = 1;
+ size_t nentries;
+
+ printk(BIOS_INFO, "Updating devicetree memory entries\n");
+
+ dt_read_cell_props(tree->root, &addr_cells, &size_cells);
+
+ // First remove all existing device_type="memory" nodes, then add ours.
+ list_for_each(node, tree->root->children, list_node) {
+ const char *devtype = dt_find_string_prop(node, "device_type");
+ if (devtype && !strcmp(devtype, "memory"))
+ list_remove(&node->list_node);
+ }
+
+ node = malloc(sizeof(*node));
+ memset(node, 0, sizeof(*node));
+
+ node->name = "memory";
+ list_insert_after(&node->list_node, &tree->root->children);
+ dt_add_string_prop(node, "device_type", "memory");
+
+ // Read memory info from coreboot (ranges are merged automatically).
+ ranges_init(&mem);
+ ranges_init(&reserved);
+
+#define MEMORY_ALIGNMENT (1 << 20)
+
+ lb_mem = lb_memory();
+
+ if (lb_mem)
+ nentries =
+ (lb_mem->size - sizeof(*lb_mem)) / sizeof(lb_mem->map[0]);
+ else
+ nentries = 0;
+
+ for (int i = 0; i < nentries; i++) {
+ struct lb_memory_range *range = &lb_mem->map[i];
+
+ uint64_t start = unpack_lb64(range->start);
+ uint64_t end = start + unpack_lb64(range->size);
+
+ /*
+ * Kernel likes its availabe memory areas at least 1MB
+ * aligned, let's trim the regions such that unaligned padding
+ * is added to reserved memory.
+ */
+ if (range->type == LB_MEM_RAM) {
+ uint64_t new_start = ALIGN_UP(start, MEMORY_ALIGNMENT);
+ uint64_t new_end = ALIGN_DOWN(end, MEMORY_ALIGNMENT);
+
+ if (new_start != start)
+ ranges_add(&reserved, start, new_start);
+
+ if (new_start != new_end)
+ ranges_add(&mem, new_start, new_end);
+
+ if (new_end != end)
+ ranges_add(&reserved, new_end, end);
+ } else {
+ ranges_add(&reserved, start, end);
+ }
+ }
+
+ // CBMEM regions are both carved out and explicitly reserved.
+ ranges_for_each(&reserved, &update_reserve_map, tree);
+
+ // Count the amount of 'reg' entries we need (account for size limits).
+ unsigned count = 0;
+ EntryParams count_params = { addr_cells, size_cells, &count };
+ ranges_for_each(&mem, &count_entries, &count_params);
+
+ // Allocate the right amount of space and fill up the entries.
+ size_t length = count * (addr_cells + size_cells) * sizeof(u32);
+
+ void *data = malloc(length);
+ memset(data, 0, length);
+ EntryParams add_params = { addr_cells, size_cells, data };
+ ranges_for_each(&mem, &update_mem_property, &add_params);
+ assert(add_params.data - data == length);
+
+ // Assemble the final property and add it to the device tree.
+ dt_add_bin_prop(node, "reg", data, length);
+}
+
+struct FitImageNode *fit_load(void *fit, struct DeviceTree **dt)
+{
+ struct FdtHeader *header = (struct FdtHeader *)fit;
+ struct FitImageNode *image;
+ struct FitConfigNode *config;
+ char *fit_kernel_compat[10] = { NULL };
+ int num_fit_kernel_compat = 0;
+ int i;
+
+ printk(BIOS_DEBUG, "Loading FIT.\n");
+
+ if (be32toh(header->magic) != FdtMagic) {
+ printk(BIOS_ERR, "Bad FIT header magic value 0x%08x.\n",
+ be32toh(header->magic));
+ return NULL;
+ }
+ printk(BIOS_DEBUG, "Found FIT\n");
+ printk(BIOS_DEBUG, " totalsize : %u\n",
+ be32toh(header->totalsize));
+ printk(BIOS_DEBUG, " version : %u\n",
+ be32toh(header->version));
+ printk(BIOS_DEBUG, " structure_size : %u\n",
+ be32toh(header->structure_size));
+
+ struct DeviceTree *tree = fdt_unflatten(fit);
+
+ const char *default_config_name = NULL;
+ struct FitConfigNode *default_config = NULL;
+ struct FitConfigNode *compat_config = NULL;
+
+ fit_unpack(tree, &default_config_name);
+
+ // List the images we found.
+ list_for_each(image, image_nodes, list_node)
+ printk(BIOS_DEBUG, "Image %s has %d bytes.\n", image->name,
+ image->size);
+
+ fit_get_compats_strings(fit_kernel_compat, &num_fit_kernel_compat);
+
+ printk(BIOS_DEBUG, "Compat preference:");
+ for (i = 0; i < num_fit_kernel_compat; i++)
+ printk(BIOS_DEBUG, " %s", fit_kernel_compat[i]);
+ printk(BIOS_DEBUG, "\n");
+ // Process and list the configs.
+ list_for_each(config, config_nodes, list_node) {
+ if (config->kernel)
+ config->kernel_node = find_image(config->kernel);
+ if (config->fdt)
+ config->fdt_node = find_image(config->fdt);
+ if (config->ramdisk)
+ config->ramdisk_node = find_image(config->ramdisk);
+
+ if (config->ramdisk_node &&
+ config->ramdisk_node->compression < 0) {
+ printk(BIOS_DEBUG, "Ramdisk compression not supported, "
+ "discarding config %s.\n", config->name);
+ list_remove(&config->list_node);
+ continue;
+ }
+
+ if (!config->kernel_node ||
+ (config->fdt && !config->fdt_node)) {
+ printk(BIOS_DEBUG,
+ "Missing image, discarding config %s.\n",
+ config->name);
+ list_remove(&config->list_node);
+ continue;
+ }
+
+ if (config->fdt_node) {
+ if (config->fdt_node->compression < 0) {
+ printk(BIOS_DEBUG,
+ "FDT compression not yet supported, "
+ "skipping config %s.\n", config->name);
+ list_remove(&config->list_node);
+ continue;
+ }
+
+ void *fdt_blob = config->fdt_node->data;
+ struct FdtHeader *fdt_header =
+ (struct FdtHeader *)fdt_blob;
+ uint32_t fdt_offset =
+ be32_to_cpu(fdt_header->structure_offset);
+ config->compat_pos = -1;
+ config->compat_rank = -1;
+ if (!fdt_find_compat(fdt_blob, fdt_offset,
+ &config->compat)) {
+ for (i = 0; i < num_fit_kernel_compat; i++) {
+ int pos = fit_check_compat(
+ &config->compat,
+ fit_kernel_compat[i]);
+ if (pos >= 0) {
+ config->compat_pos = pos;
+ config->compat_rank = i;
+ break;
+ }
+ }
+ }
+ }
+
+ //if (default_config_name &&
+ // !strcmp(config->name, default_config_name)) {
+ // printk(BIOS_DEBUG, " (default)");
+ default_config = config;
+ //}
+ if (config->fdt)
+ printk(BIOS_DEBUG, ", fdt %s", config->fdt);
+ if (config->ramdisk)
+ printk(BIOS_DEBUG, ", ramdisk %s", config->ramdisk);
+ if (config->compat.name) {
+ printk(BIOS_DEBUG, ", compat");
+ int bytes = config->compat.size;
+ const char *compat_str = config->compat.data;
+ for (int pos = 0; bytes && compat_str[0]; pos++) {
+ printk(BIOS_DEBUG, " %s", compat_str);
+ if (pos == config->compat_pos)
+ printk(BIOS_DEBUG, " (match)");
+ int len = strlen(compat_str) + 1;
+ compat_str += len;
+ bytes -= len;
+ }
+
+ if (config->compat_rank >= 0 && (!compat_config ||
+ config->compat_rank < compat_config->compat_rank))
+ compat_config = config;
+ }
+ printk(BIOS_DEBUG, "\n");
+ }
+
+ struct FitConfigNode *to_boot = NULL;
+ if (compat_config) {
+ to_boot = compat_config;
+ printk(BIOS_ERR, "Choosing best match %s for compat %s.\n",
+ to_boot->name, fit_kernel_compat[to_boot->compat_rank]);
+ } else if (default_config) {
+ to_boot = default_config;
+ printk(BIOS_ERR, "No match, choosing default %s.\n",
+ to_boot->name);
+ } else {
+ printk(BIOS_ERR,
+ "No compatible or default configs. Giving up.\n");
+ // We're leaking memory here, but at this point we're beyond
+ // saving anyway.
+ return NULL;
+ }
+
+ if (to_boot->fdt_node) {
+ *dt = fdt_unflatten(to_boot->fdt_node->data);
+ if (!*dt) {
+ printk(BIOS_ERR,
+ "Failed to unflatten the kernel's fdt.\n");
+ return NULL;
+ }
+
+ /* Update only if non-NULL cmd line */
+ if (strlen(CONFIG_LINUX_COMMAND_LINE) > 0)
+ update_chosen(*dt, CONFIG_LINUX_COMMAND_LINE);
+
+ update_memory(*dt);
+
+ if (to_boot->ramdisk_node)
+ fit_add_ramdisk(*dt, to_boot->ramdisk_node->data,
+ to_boot->ramdisk_node->size);
+ }
+
+ return to_boot->kernel_node;
+}
diff --git a/src/lib/list.c b/src/lib/list.c
new file mode 100644
index 0000000..581573e
--- /dev/null
+++ b/src/lib/list.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2012 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <list.h>
+
+void list_remove(ListNode *node)
+{
+ if (node->prev)
+ node->prev->next = node->next;
+ if (node->next)
+ node->next->prev = node->prev;
+}
+
+void list_insert_after(ListNode *node, ListNode *after)
+{
+ node->next = after->next;
+ node->prev = after;
+ after->next = node;
+ if (node->next)
+ node->next->prev = node;
+}
+
+void list_insert_before(ListNode *node, ListNode *before)
+{
+ node->prev = before->prev;
+ node->next = before;
+ before->prev = node;
+ if (node->prev)
+ node->prev->next = node;
+}
diff --git a/src/lib/prog_loaders.c b/src/lib/prog_loaders.c
index 128869b..cec9582 100644
--- a/src/lib/prog_loaders.c
+++ b/src/lib/prog_loaders.c
@@ -29,6 +29,7 @@
#include <stage_cache.h>
#include <symbols.h>
#include <timestamp.h>
+#include <uImage.h>
/* Only can represent up to 1 byte less than size_t. */
const struct mem_region_device addrspace_32bit =
@@ -179,9 +180,14 @@
mirror_payload(payload);
- /* Pass cbtables to payload if architecture desires it. */
- prog_set_entry(payload, selfload(payload, true),
- cbmem_find(CBMEM_ID_CBTABLE));
+ if (IS_ENABLED(CONFIG_PAYLOAD_LINUX_UIMAGE)) {
+ uImageLoad(payload);
+ /* Entry and argument have already been set up */
+ } else {
+ /* Pass cbtables to payload if architecture desires it. */
+ prog_set_entry(payload, selfload(payload, true),
+ cbmem_find(CBMEM_ID_CBTABLE));
+ }
out:
if (prog_entry(payload) == NULL)
diff --git a/src/lib/ranges.c b/src/lib/ranges.c
new file mode 100644
index 0000000..c141f94
--- /dev/null
+++ b/src/lib/ranges.c
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2012 Google Inc.
+ *
+ * See file CREDITS for list of people who contributed to this
+ * project.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of
+ * the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but without any warranty; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <stddef.h>
+#include <console/console.h>
+
+#include <ranges.h>
+
+/*
+ * This implementation tracks a collection of ranges by keeping a linked list
+ * of the edges between ranges in the collection and the space between them.
+ * New ranges take precedence over older ranges they overlap with.
+ */
+
+static void ranges_insert_between(RangesEdge *before, RangesEdge *after,
+ uint64_t pos)
+{
+ RangesEdge *new_edge = malloc(sizeof(*new_edge));
+
+ assert(before != after);
+
+ new_edge->next = after;
+ new_edge->pos = pos;
+ before->next = new_edge;
+}
+
+void ranges_init(Ranges *ranges)
+{
+ ranges->head.next = NULL;
+ ranges->head.pos = 0;
+}
+
+void ranges_teardown(Ranges *ranges)
+{
+ RangesEdge *edge = ranges->head.next;
+
+ while (edge) {
+ RangesEdge *next = edge->next;
+ free(edge);
+ edge = next;
+ }
+ ranges->head.next = NULL;
+}
+
+static void ranges_set_region_to(Ranges *ranges, uint64_t start,
+ uint64_t end, int new_included)
+{
+ /* whether the current region was originally going to be included. */
+ int included = 0;
+
+ assert(start != end);
+
+ /* prev is never NULL, but cur might be. */
+ RangesEdge *prev = &ranges->head;
+ RangesEdge *cur = prev->next;
+
+ /*
+ * Find the start of the new region. After this loop, prev will be
+ * before the start of the new region, and cur will be after it or
+ * overlapping start. If they overlap, this ensures that the existing
+ * edge is deleted and we don't end up with two edges in the same spot.
+ */
+ while (cur && cur->pos < start) {
+ prev = cur;
+ cur = cur->next;
+ included = !included;
+ }
+
+ /* Add the "start" edge between prev and cur, if needed. */
+ if (new_included != included) {
+ ranges_insert_between(prev, cur, start);
+ prev = prev->next;
+ }
+
+ /*
+ * Delete any edges obscured by the new region. After this loop, prev
+ * will be before the end of the new region or overlapping it, and cur
+ * will be after if, if there is a edge after it. For the same
+ * reason as above, we want to ensure that we end up with one edge if
+ * there's an overlap.
+ */
+ while (cur && cur->pos <= end) {
+ cur = cur->next;
+ free(prev->next);
+ prev->next = cur;
+ included = !included;
+ }
+
+ /* Add the "end" edge between prev and cur, if needed. */
+ if (included != new_included)
+ ranges_insert_between(prev, cur, end);
+}
+
+/* Add a range to a collection of ranges. */
+void ranges_add(Ranges *ranges, uint64_t start, uint64_t end)
+{
+ ranges_set_region_to(ranges, start, end, 1);
+}
+
+/* Subtract a range. */
+void ranges_sub(Ranges *ranges, uint64_t start, uint64_t end)
+{
+ ranges_set_region_to(ranges, start, end, 0);
+}
+
+/* Run a function on each range in Ranges. */
+void ranges_for_each(Ranges *ranges, RangesForEachFunc func, void *data)
+{
+ for (RangesEdge *cur = ranges->head.next; cur; cur = cur->next->next) {
+ if (!cur->next) {
+ printk(BIOS_ERR, "Odd number of range edges!\n");
+ return;
+ }
+
+ func(cur->pos, cur->next->pos, data);
+ }
+}
diff --git a/src/lib/uImage.c b/src/lib/uImage.c
new file mode 100644
index 0000000..1717a96
--- /dev/null
+++ b/src/lib/uImage.c
@@ -0,0 +1,211 @@
+/*
+ * This file is part of the coreboot project.
+ *
+ * Copyright (C) 2003-2004 Eric Biederman
+ * Copyright (C) 2005-2010 coresystems GmbH
+ * Copyright (C) 2014 Google Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <console/console.h>
+#include <bootmem.h>
+#include <cbmem.h>
+#include <device/resource.h>
+#include <stdlib.h>
+#include <uImage.h>
+#include <commonlib/region.h>
+#include <fit.h>
+#include <program_loading.h>
+#include <timestamp.h>
+#include <cbfs.h>
+#include <string.h>
+#include <commonlib/compression.h>
+#include <lib.h>
+#include <uImage.h>
+
+#define MAX_KERNEL_SIZE (64*MiB)
+
+typedef struct {
+ u32 code0;
+ u32 code1;
+ u64 text_offset;
+ u64 image_size;
+ u64 flags;
+ u64 res2;
+ u64 res3;
+ u64 res4;
+ u32 magic;
+#define KERNEL_HEADER_MAGIC 0x644d5241
+ u32 res5;
+} Arm64KernelHeader;
+
+struct {
+ union {
+ Arm64KernelHeader header;
+ u8 raw[sizeof(Arm64KernelHeader) + 0x100];
+ };
+#define SCRATCH_CANARY_VALUE 0xdeadbeef
+ u32 canary;
+} scratch;
+
+__attribute__((weak)) size_t
+arch_get_kernel_fdt_load_addr(uint32_t load_offset,
+ size_t kernel_size,
+ uint32_t fdt_size,
+ void **kernel_load_addr,
+ void **fdt_load_addr)
+{
+ printk(BIOS_ERR, "ERROR: Unsupported ARCH\n");
+ return 1;
+}
+
+static size_t extract_fit(struct prog *payload,
+ struct FitImageNode *kernel,
+ struct DeviceTree *dt)
+{
+ void *kernel_reloc, *fdt_reloc;
+ size_t kernel_max_size, dt_size;
+
+ printk(BIOS_INFO, "%s: %p, %p, %p\n", __func__, payload, kernel, dt);
+
+ // Partially decompress to get text_offset. Can't check for errors.
+ scratch.canary = SCRATCH_CANARY_VALUE;
+ switch (kernel->compression) {
+ case CBFS_COMPRESS_NONE:
+ memcpy(scratch.raw, kernel->data, sizeof(scratch.raw));
+ break;
+ case CBFS_COMPRESS_LZMA:
+ ulzman(kernel->data, kernel->size,
+ scratch.raw, sizeof(scratch.raw));
+ break;
+ case CBFS_COMPRESS_LZ4:
+ ulz4fn(kernel->data, kernel->size,
+ scratch.raw, sizeof(scratch.raw));
+ break;
+ default:
+ printk(BIOS_ERR, "ERROR: Unsupported compression algorithm!\n");
+ return 1;
+ }
+
+ // Should never happen, but if it does we'll want to know.
+ if (scratch.canary != SCRATCH_CANARY_VALUE) {
+ printk(BIOS_ERR,
+ "ERROR: Partial decompression ran over scratchbuf!\n");
+ return 1;
+ }
+
+ if (scratch.header.magic != KERNEL_HEADER_MAGIC) {
+ printk(BIOS_ERR,
+ "ERROR: Invalid kernel magic: %#.8x\n != %#.8x\n",
+ scratch.header.magic, KERNEL_HEADER_MAGIC);
+ return 1;
+ }
+
+ if (!scratch.header.image_size) {
+ kernel_max_size = MAX_KERNEL_SIZE;
+ printk(BIOS_WARNING, "Assuming %zd MiB kernel size\n",
+ kernel_max_size >> 20);
+ } else
+ kernel_max_size = scratch.header.image_size;
+
+ dt_size = dt ? dt_flat_size(dt) : 0;
+
+ if (arch_get_kernel_fdt_load_addr(scratch.header.text_offset,
+ kernel_max_size,
+ dt_size,
+ &kernel_reloc,
+ &fdt_reloc)) {
+ printk(BIOS_ERR, "ERROR: Failed to find free memory region\n");
+ return 1;
+ }
+
+ printk(BIOS_DEBUG, "Kernel load address %p\n", kernel_reloc);
+ printk(BIOS_DEBUG, "FDT load address %p\n", fdt_reloc);
+
+ // Flatten it.
+ if (dt) {
+ dt_flatten(dt, fdt_reloc);
+ prog_segment_loaded((uintptr_t)fdt_reloc, dt_size, 0);
+ }
+
+ timestamp_add_now(TS_KERNEL_DECOMPRESSION);
+
+ size_t true_size = kernel->size;
+ switch (kernel->compression) {
+ case CBFS_COMPRESS_NONE:
+ if (kernel->size > kernel_max_size) {
+ printk(BIOS_ERR,
+ "ERROR: Cannot relocate a kernel this large!\n");
+ return 1;
+ }
+ printk(BIOS_INFO, "Relocating kernel to %p\n", kernel_reloc);
+ memmove(kernel_reloc, kernel->data, kernel->size);
+ break;
+ case CBFS_COMPRESS_LZMA:
+ printk(BIOS_INFO, "Decompressing LZMA kernel to %p\n",
+ kernel_reloc);
+ timestamp_add_now(TS_START_ULZMA);
+ true_size = ulzman(kernel->data, kernel->size,
+ kernel_reloc, kernel_max_size);
+ timestamp_add_now(TS_END_ULZMA);
+ if (!true_size) {
+ printk(BIOS_ERR, "ERROR: LZMA decompression failed!\n");
+ return 1;
+ }
+ break;
+ case CBFS_COMPRESS_LZ4:
+ printk(BIOS_INFO, "Decompressing LZ4 kernel to %p\n",
+ kernel_reloc);
+ timestamp_add_now(TS_START_ULZ4F);
+ true_size = ulz4fn(kernel->data, kernel->size,
+ kernel_reloc, kernel_max_size);
+ timestamp_add_now(TS_END_ULZ4F);
+ if (!true_size) {
+ printk(BIOS_ERR, "ERROR: LZ4 decompression failed!\n");
+ return 1;
+ }
+ break;
+ default: // It's 2015 and GCC's reachability analyzer still sucks...
+ return 1;
+ }
+
+ prog_segment_loaded((uintptr_t)kernel_reloc, true_size, 0);
+
+ timestamp_add_now(TS_START_KERNEL);
+
+ printk(BIOS_INFO, "Set kernel entry\n");
+
+ prog_set_entry(payload, kernel_reloc, fdt_reloc);
+
+ return 0;
+}
+
+/*
+ * Parse and load a kernel, devicetree and config from uImage payload.
+ */
+void uImageLoad(struct prog *payload)
+{
+ struct DeviceTree *dt = NULL;
+ void *data;
+
+ data = rdev_mmap_full(prog_rdev(payload));
+
+ if (data == NULL)
+ return;
+
+ struct FitImageNode *fit = fit_load(data, &dt);
+ if (!fit)
+ printk(BIOS_ERR, "ERROR: Could not load FIT\n");
+ else
+ extract_fit(payload, fit, dt);
+
+ rdev_munmap(prog_rdev(payload), data);
+}
--
To view, visit https://review.coreboot.org/25019
To unsubscribe, or for help writing mail filters, visit https://review.coreboot.org/settings
Gerrit-Project: coreboot
Gerrit-Branch: master
Gerrit-MessageType: newchange
Gerrit-Change-Id: I0f27b92a5e074966f893399eb401eb97d784850d
Gerrit-Change-Number: 25019
Gerrit-PatchSet: 1
Gerrit-Owner: Patrick Rudolph <patrick.rudolph at 9elements.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.coreboot.org/pipermail/coreboot-gerrit/attachments/20180307/cf5bedfa/attachment-0001.html>
More information about the coreboot-gerrit
mailing list