[PATCH 12/12] lib: tlv_eeprom: add function for reading one entry into a C string

Josua Mayer josua at solid-run.com
Mon May 2 16:18:38 CEST 2022


This solves the potentially common problem of getting a specific tlv
entry from an eeprom in board-files, without having to introduce several
variables, error handling, memcpy and 0-terminating the string.

Signed-off-by: Josua Mayer <josua at solid-run.com>
---
 include/tlv_eeprom.h | 12 ++++++++++++
 lib/tlv/tlv_eeprom.c | 25 +++++++++++++++++++++++++
 2 files changed, 37 insertions(+)

diff --git a/include/tlv_eeprom.h b/include/tlv_eeprom.h
index c81c58837d..5989c611f5 100644
--- a/include/tlv_eeprom.h
+++ b/include/tlv_eeprom.h
@@ -166,6 +166,18 @@ bool tlvinfo_add_tlv(u8 *eeprom, int code, char *strval);
  */
 bool tlvinfo_delete_tlv(u8 *eeprom, u8 code);
 
+/**
+ * Read the TLV entry with specified code to a buffer as terminated C string.
+ * @eeprom: Pointer to buffer holding the TLV EEPROM binary data.
+ * @code:   The TLV Code of the entry to read.
+ * @buffer: Pointer to buffer where the value will be stored. Must have capacity
+ *          for the string representation of the data including null terminator.
+ * @length: size of the buffer where the value will be stored.
+ *
+ * Return length of string on success, -1 on error.
+ */
+ssize_t tlvinfo_read_tlv(u8 *eeprom, u8 code, u8 *buffer, size_t length);
+
 /**
  *  tlvinfo_update_crc
  *
diff --git a/lib/tlv/tlv_eeprom.c b/lib/tlv/tlv_eeprom.c
index 464f0aa1fa..205960e8f2 100644
--- a/lib/tlv/tlv_eeprom.c
+++ b/lib/tlv/tlv_eeprom.c
@@ -350,6 +350,31 @@ bool tlvinfo_add_tlv(u8 *eeprom, int tcode, char *strval)
 	return true;
 }
 
+/**
+ * Read the TLV entry with specified code to a buffer as terminated C string.
+ */
+ssize_t tlvinfo_read_tlv(u8 *eeprom, u8 code, u8 *buffer, size_t length)
+{
+	int index;
+	struct tlvinfo_tlv *tlv;
+
+	// read sku from part-number field
+	if (tlvinfo_find_tlv(eeprom, code, &index)) {
+		tlv = (struct tlvinfo_tlv *)&eeprom[index];
+		if (tlv->length > length) {
+			pr_err("%s: tlv value (%d) larger than buffer (%zu)!\n",
+			       __func__, tlv->length + 1, length);
+			return -1;
+		}
+		memcpy(buffer, tlv->value, tlv->length);
+		buffer[tlv->length] = 0;
+
+		return tlv->length;
+	}
+
+	return -1;
+}
+
 /**
  *  set_mac
  *
-- 
2.34.1



More information about the U-Boot mailing list