util/sconfig: Refactor and fix add_register()

add_register() contained a duplicate check but only compared the new
key to the first (smallest in order) list member. Fix that and factor
the list handling out so it can be used by other functions.

Change-Id: I5a8346f36fa024351e1282c9681868ecf451b283
Signed-off-by: Nico Huber <nico.h@gmx.de>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/41743
Reviewed-by: Angel Pons <th3fanbus@gmail.com>
Reviewed-by: Aaron Durbin <adurbin@chromium.org>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
diff --git a/util/sconfig/main.c b/util/sconfig/main.c
index 6676bae..3e3bd17 100644
--- a/util/sconfig/main.c
+++ b/util/sconfig/main.c
@@ -528,33 +528,34 @@
 	new_resource(bus->dev, type, index, base);
 }
 
-void add_register(struct chip_instance *chip_instance, char *name, char *val)
+static void add_reg(struct reg **const head, char *const name, char *const val)
 {
-	struct reg *r = S_ALLOC(sizeof(struct reg));
+	struct reg *const r = S_ALLOC(sizeof(struct reg));
+	struct reg *prev = NULL;
+	struct reg *cur;
 
 	r->key = name;
 	r->value = val;
-	if (chip_instance->reg) {
-		struct reg *head = chip_instance->reg;
-		// sorting to be equal to sconfig's behaviour
-		int sort = strcmp(r->key, head->key);
+
+	for (cur = *head; cur != NULL; prev = cur, cur = cur->next) {
+		const int sort = strcmp(r->key, cur->key);
 		if (sort == 0) {
 			printf("ERROR: duplicate 'register' key.\n");
 			exit(1);
 		}
-		if (sort < 0) {
-			r->next = head;
-			chip_instance->reg = r;
-		} else {
-			while ((head->next)
-			       && (strcmp(head->next->key, r->key) < 0))
-				head = head->next;
-			r->next = head->next;
-			head->next = r;
-		}
-	} else {
-		chip_instance->reg = r;
+		if (sort < 0)
+			break;
 	}
+	r->next = cur;
+	if (prev)
+		prev->next = r;
+	else
+		*head = r;
+}
+
+void add_register(struct chip_instance *chip_instance, char *name, char *val)
+{
+	add_reg(&chip_instance->reg, name, val);
 }
 
 void add_slot_desc(struct bus *bus, char *type, char *length, char *designation,