From 40355952340169930bfbd03a6ea4de3041c39754 Mon Sep 17 00:00:00 2001
From: Josua Mayer <josua@solid-run.com>
Date: Sun, 20 Mar 2022 12:07:38 +0200
Subject: [PATCH] lib: tlv_eeprom: add function for reading one entry into a C
 string

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

diff --git a/include/tlv_eeprom.h b/include/tlv_eeprom.h
index ee9f035c8c..c91618e480 100644
--- a/include/tlv_eeprom.h
+++ b/include/tlv_eeprom.h
@@ -167,6 +167,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 fe164cabe6..e2c7a0d664 100644
--- a/lib/tlv/tlv_eeprom.c
+++ b/lib/tlv/tlv_eeprom.c
@@ -349,6 +349,29 @@ bool tlvinfo_add_tlv(u8 *eeprom, int code, 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
  *
