diff mbox series

[U-Boot,v2,03/11] fdtdec: Implement fdtdec_generate_phandle()

Message ID 20190312130104.8221-3-thierry.reding@gmail.com
State Superseded
Delegated to: Simon Glass
Headers show
Series [U-Boot,v2,01/11] fdtdec: Add cpu_to_fdt_{addr, size}() macros | expand

Commit Message

Thierry Reding March 12, 2019, 1 p.m. UTC
From: Thierry Reding <treding@nvidia.com>

This function generates a new, unused phandle by looking up the highest
phandle value stored in a device tree and adding one.

Signed-off-by: Thierry Reding <treding@nvidia.com>
---
Changes in v2:
- rename to fdtdec_generate_phandle()

 include/fdtdec.h | 12 ++++++++++++
 lib/fdtdec.c     | 28 ++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+)
diff mbox series

Patch

diff --git a/include/fdtdec.h b/include/fdtdec.h
index a0ba57c6318b..b593c562584d 100644
--- a/include/fdtdec.h
+++ b/include/fdtdec.h
@@ -981,6 +981,18 @@  int fdtdec_setup_mem_size_base(void);
  */
 int fdtdec_setup_memory_banksize(void);
 
+/**
+ * fdtdec_generate_phandle() - return a new, unused phandle for an FDT blob
+ *
+ * Returns a phandle that can be used to refer to a new device tree node. It
+ * is one higher than the currently highest phandle in the given FDT blob.
+ *
+ * @param blob	FDT blob
+ * @param maxp	return location for the new phandle
+ * @return 0 on success or a negative error code on failure
+ */
+int fdtdec_generate_phandle(const void *blob, uint32_t *phandle);
+
 /**
  * Set up the device tree ready for use
  */
diff --git a/lib/fdtdec.c b/lib/fdtdec.c
index 09a7e133a539..d384c84feb33 100644
--- a/lib/fdtdec.c
+++ b/lib/fdtdec.c
@@ -1243,6 +1243,34 @@  __weak void *board_fdt_blob_setup(void)
 }
 #endif
 
+int fdtdec_generate_phandle(const void *blob, uint32_t *phandle)
+{
+	uint32_t max = 0;
+	int offset = -1;
+
+	while (true) {
+		uint32_t value;
+
+		offset = fdt_next_node(blob, offset, NULL);
+		if (offset < 0) {
+			if (offset == -FDT_ERR_NOTFOUND)
+				break;
+
+			return offset;
+		}
+
+		value = fdt_get_phandle(blob, offset);
+
+		if (value > max)
+			max = value;
+	}
+
+	if (phandle)
+		*phandle = max + 1;
+
+	return 0;
+}
+
 int fdtdec_setup(void)
 {
 #if CONFIG_IS_ENABLED(OF_CONTROL)