Skip to contentSkip to conversation

alist: Implement a pointer list / array of structs

PATCH Superseded Simon Glass 2 participants 8 messages Jul 26, 2024 – Jul 29, 2024 Library code

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v4 cover alist: Implement a pointer list / array of structs

This data structure provides a list of pointers / array of structures. I was planning to use it for the lmb restructure, to allow it to support any number of entries, but then I gave up on it.

There are quite a few places in U-Boot where such a list would be useful, since it supports growing the array.

The series includes a patch to convert an existing function to use this.

It adds a little under 300 bytes of code with Thumb2.

With this version, use of realloc() is option and off by default. This reduces the size growth on xilinx_versal_mini_emmc0 (aarch64) from 1765 bytes to 636, for the str_to_list() patch.

The str_to_list() patch is marked as RFC since I beleive we have decided not to apply it.

Example:

struct my_struct obj;
struct my_struct *ptr = alist_add(&lst, &obj, struct my_struct);

// now ptr is in the list

[1] https://patchwork.ozlabs.org/project/uboot/list/?series=371258&state=*

Changes in v4:
- Avoid using realloc() unless specifically enabled by Kconfig

Changes in v3:
- Add prototype for alist_expand_by()
- Update for alist_add() API change

Changes in v2:
- Fix 'typeee' typo
- Make alist_get_ptr() take a const alist *
- Make alist_add() take a struct rather than a pointer
- Declare alist_expand_by() as static

Simon Glass (4):
malloc: Support testing with realloc()
lib: Handle a special case with str_to_list()
alist: Add support for an allocated pointer list
RFC: lib: Convert str_to_list() to use alist

 common/dlmalloc.c |   4 +
 include/alist.h   | 214 ++++++++++++++++++++++++++++++++++++++++++++++
 lib/Kconfig       |  10 +++
 lib/Makefile      |   1 +
 lib/alist.c       | 157 ++++++++++++++++++++++++++++++++++
 lib/strto.c       |  33 ++++---
 test/lib/Makefile |   1 +
 test/lib/alist.c  | 197 ++++++++++++++++++++++++++++++++++++++++++
 test/str_ut.c     |   4 +-
 9 files changed, 604 insertions(+), 17 deletions(-)
 create mode 100644 include/alist.h
 create mode 100644 lib/alist.c
 create mode 100644 test/lib/alist.c
Signature · 1 line
2.34.1
#1 lore raw

PATCH v4 1/4 malloc: Support testing with realloc()

At present in tests it is possible to cause an out-of-memory condition with malloc() but not realloc(). Add support to realloc() too, so code which uses that function can be tested.

---

(no changes since v1)

 common/dlmalloc.c | 4 ++++
 1 file changed, 4 insertions(+)
common/dlmalloc.c +4 -0
index 62e8557daa7..1e1602a24de 100644
@@ -1698,6 +1698,10 @@ Void_t* rEALLOc_impl(oldmem, bytes) Void_t* oldmem; size_t bytes;
 		panic("pre-reloc realloc() is not supported");
 	}
 #endif
+  if (CONFIG_IS_ENABLED(UNIT_TEST) && malloc_testing) {
+    if (--malloc_max_allocs < 0)
+      return NULL;
+  }
 
   newp    = oldp    = mem2chunk(oldmem);
   newsize = oldsize = chunksize(oldp);
Signature · 1 line
2.34.1
#2 lore raw

PATCH v4 2/4 lib: Handle a special case with str_to_list()

In reply to Simon Glass

The current implementation can return an extra result at the end when the string ends with a space. Fix this by adding a special case.

---

(no changes since v1)

 lib/strto.c   | 4 +++-
 test/str_ut.c | 4 +---
 2 files changed, 4 insertions(+), 4 deletions(-)
lib/strto.c +3 -1
index 5157332d6c1..f83ac67c666 100644
@@ -236,12 +236,14 @@ const char **str_to_list(const char *instr)
 		return NULL;
 
 	/* count the number of space-separated strings */
-	for (count = *str != '\0', p = str; *p; p++) {
+	for (count = 0, p = str; *p; p++) {
 		if (*p == ' ') {
 			count++;
 			*p = '\0';
 		}
 	}
+	if (p != str && p[-1])
+		count++;
 
 	/* allocate the pointer array, allowing for a NULL terminator */
 	ptr = calloc(count + 1, sizeof(char *));
test/str_ut.c +1 -3
index 389779859a3..96e048975d8 100644
@@ -342,9 +342,7 @@ static int test_str_to_list(struct unit_test_state *uts)
 	ut_asserteq_str("space", ptr[3]);
 	ut_assertnonnull(ptr[4]);
 	ut_asserteq_str("", ptr[4]);
-	ut_assertnonnull(ptr[5]);
-	ut_asserteq_str("", ptr[5]);
-	ut_assertnull(ptr[6]);
+	ut_assertnull(ptr[5]);
 	str_free_list(ptr);
 	ut_assertok(ut_check_delta(start));
 
Signature · 1 line
2.34.1
#3 lore raw

PATCH v4 3/4 alist: Add support for an allocated pointer list

In reply to Simon Glass

In various places it is useful to have an array of structures, but allow it to grow. In some cases we work around it by setting maximum number of entries, using a Kconfig option. In other places we use a linked list, which does not provide for random access and can complicate the code.

Introduce a new data structure, which is a variable-sized list of structs each of the same, pre-set size. It provides O(1) access and is reasonably efficient at expanding linearly, since it doubles in size when it runs out of space.

---

Changes in v4:
- Avoid using realloc() unless specifically enabled by Kconfig

Changes in v3:
- Add prototype for alist_expand_by()

Changes in v2:
- Fix 'typeee' typo
- Make alist_get_ptr() take a const alist *
- Make alist_add() take a struct rather than a pointer
- Declare alist_expand_by() as static

 include/alist.h   | 214 ++++++++++++++++++++++++++++++++++++++++++++++
 lib/Kconfig       |  10 +++
 lib/Makefile      |   1 +
 lib/alist.c       | 157 ++++++++++++++++++++++++++++++++++
 test/lib/Makefile |   1 +
 test/lib/alist.c  | 197 ++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 580 insertions(+)
 create mode 100644 include/alist.h
 create mode 100644 lib/alist.c
 create mode 100644 test/lib/alist.c
include/alist.h new file +214 -0
new file mode 100644
index 00000000000..6cc3161dcda
@@ -0,0 +1,214 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/*
+ * Handles a contiguous list of pointers which be allocated and freed
+ *
+ * Copyright 2023 Google LLC
+ * Written by Simon Glass <[email protected]>
+ */
+
+#ifndef __ALIST_H
+#define __ALIST_H
+
+#include <stdbool.h>
+#include <linux/bitops.h>
+#include <linux/types.h>
+
+/**
+ * struct alist - object list that can be allocated and freed
+ *
+ * Holds a list of objects, each of the same size. The object is typically a
+ * C struct. The array is alloced in memory can change in size.
+ *
+ * The list rememebers the size of the list, but has a separate count of how
+ * much space is allocated, This allows it increase in size in steps as more
+ * elements are added, which is more efficient that reallocating the list every
+ * time a single item is added
+ *
+ * Two types of access are provided:
+ *
+ * alist_get...(index)
+ *	gets an existing element, if its index is less that size
+ *
+ * alist_ensure(index)
+ *	address an existing element, or creates a new one if not present
+ *
+ * @data: object data of size `@obj_size * @alloc`. The list can grow as
+ * needed but never shrinks
+ * @obj_size: Size of each object in bytes
+ * @count: number of objects in array
+ * @alloc: allocated length of array, to which @count can grow
+ * @flags: flags for the alist (ALISTF_...)
+ */
+struct alist {
+	void *data;
+	u16 obj_size;
+	u16 count;
+	u16 alloc;
+	u16 flags;
+};
+
+/**
+ * enum alist_flags - Flags for the alist
+ *
+ * @ALIST_FAIL: true if any allocation has failed. Once this has happened, the
+ * alist is dead and cannot grow further
+ */
+enum alist_flags {
+	ALISTF_FAIL	= BIT(0),
+};
+
+/**
+ * alist_has() - Check if an index is within the list range
+ *
+ * Checks if index is within the current alist count
+ *
+ * @lst: alist to check
+ * @index: Index to check
+ * Returns: true if value, else false
+ */
+static inline bool alist_has(struct alist *lst, uint index)
+{
+	return index < lst->count;
+}
+
+/**
+ * alist_err() - Check if the alist is still valid
+ *
+ * @lst: List to check
+ * Return: false if OK, true if any previous allocation failed
+ */
+static inline bool alist_err(struct alist *lst)
+{
+	return lst->flags & ALISTF_FAIL;
+}
+
+/**
+ * alist_get_ptr() - Get the value of a pointer
+ *
+ * @lst: alist to check
+ * @index: Index to read from
+ * Returns: pointer, if present, else NULL
+ */
+const void *alist_get_ptr(const struct alist *lst, uint index);
+
+/**
+ * alist_getd() - Get the value of a pointer directly, with no checking
+ *
+ * This must only be called on indexes for which alist_has() returns true
+ *
+ * @lst: alist to check
+ * @index: Index to read from
+ * Returns: pointer value (may be NULL)
+ */
+static inline const void *alist_getd(struct alist *lst, uint index)
+{
+	return lst->data + index * lst->obj_size;
+}
+
+#define alist_get(_lst, _index, _struct)	\
+	((const _struct *)alist_get_ptr(_lst, _index))
+
+/**
+ * alist_ensure_ptr() - Ensure an object exists at a given index
+ *
+ * This provides read/write access to an array element. If it does not exist,
+ * it is allocated, reading for the caller to store the object into
+ *
+ * Allocates a object at the given index if needed
+ *
+ * @lst: alist to check
+ * @index: Index to address
+ * Returns: pointer where struct can be read/written, or NULL if out of memory
+ */
+void *alist_ensure_ptr(struct alist *lst, uint index);
+
+/**
+ * alist_ensure() - Address a struct, the correct object type
+ *
+ * Use as:
+ *	struct my_struct *ptr = alist_ensure(&lst, 4, struct my_struct);
+ */
+#define alist_ensure(_lst, _index, _struct)	\
+	((_struct *)alist_ensure_ptr(_lst, _index))
+
+/**
+ * alist_add_ptr() - Ad a new object to the list
+ *
+ * @lst: alist to add to
+ * @obj: Pointer to object to copy in
+ * Returns: pointer to where the object was copied, or NULL if out of memory
+ */
+void *alist_add_ptr(struct alist *lst, void *obj);
+
+/**
+ * alist_expand_by() - Expand a list by the given amount
+ *
+ * @lst: alist to expand
+ * @inc_by: Amount to expand by
+ * Return: true if OK, false if out of memory
+ */
+bool alist_expand_by(struct alist *lst, uint inc_by);
+
+/**
+ * alist_add() - Used to add an object type with the correct type
+ *
+ * Use as:
+ *	struct my_struct obj;
+ *	struct my_struct *ptr = alist_add(&lst, &obj, struct my_struct);
+ */
+#define alist_add(_lst, _obj, _struct)	\
+	((_struct *)alist_add_ptr(_lst, (_struct *)&(_obj)))
+
+/**
+ * alist_init() - Set up a new object list
+ *
+ * Sets up a list of objects, initially empty
+ *
+ * @lst: alist to set up
+ * @obj_size: Size of each element in bytes
+ * @alloc_size: Number of items to allowed to start, before reallocation is
+ * needed (0 to start with no space)
+ * Return: true if OK, false if out of memory
+ */
+bool alist_init(struct alist *lst, uint obj_size, uint alloc_size);
+
+#define alist_init_struct(_lst, _struct)	\
+	alist_init(_lst, sizeof(_struct), 0)
+
+/**
+ * alist_uninit_move_ptr() - Return the allocated contents and uninit the alist
+ *
+ * This returns the alist data to the caller, so that the caller receives data
+ * that it can be sure will hang around. The caller is responsible for freeing
+ * the data.
+ *
+ * If the alist size is 0, this returns NULL
+ *
+ * The alist is uninited as part of this.
+ *
+ * The alist must be inited before this can be called.
+ *
+ * @alist: alist to uninit
+ * @countp: if non-NULL, returns the number of objects in the returned data
+ * (which is @alist->size)
+ * Return: data contents, allocated with malloc(), or NULL if the data could not
+ *	be allocated, or the data size is 0
+ */
+void *alist_uninit_move_ptr(struct alist *alist, size_t *countp);
+
+/**
+ * alist_uninit_move() - Typed version of alist_uninit_move_ptr()
+ */
+#define alist_uninit_move(_lst, _countp, _struct)	\
+	(_struct *)alist_uninit_move_ptr(_lst, _countp)
+
+/**
+ * alist_uninit() - Free any memory used by an alist
+ *
+ * The alist must be inited before this can be called.
+ *
+ * @alist: alist to uninit
+ */
+void alist_uninit(struct alist *alist);
+
+#endif /* __ALIST_H */
lib/Kconfig +10 -0
index 2059219a120..40b59adbefc 100644
@@ -8,6 +8,16 @@ config ADDR_MAP
 
 	  This library only works in the post-relocation phase.
 
+config ALIST_REALLOC
+	bool "Use realloc() in the alist implementation"
+	help
+	  An alist must expand when it runs out of space. It is more efficient
+	  to use realloc() for this, but for boards which don't otherwise use
+	  this function it can add 1KB of code space, so separate malloc() and
+	  free are normally used instead.
+
+	  Enable this to use realloc() in alist
+
 config SYS_NUM_ADDR_MAP
 	int "Size of the address-map table"
 	depends on ADDR_MAP
lib/Makefile +1 -0
index e389ad014f8..81b503ab526 100644
@@ -147,6 +147,7 @@ endif
 obj-$(CONFIG_$(SPL_)OID_REGISTRY) += oid_registry.o
 
 obj-y += abuf.o
+obj-y += alist.o
 obj-y += date.o
 obj-y += rtc-lib.o
 obj-$(CONFIG_LIB_ELF) += elf.o
lib/alist.c new file +157 -0

157 lines not on this page · raw message

test/lib/Makefile +1 -0
index e75a263e6a4..70f14c46b1e 100644
@@ -5,6 +5,7 @@
 ifeq ($(CONFIG_SPL_BUILD),)
 obj-y += cmd_ut_lib.o
 obj-y += abuf.o
+obj-y += alist.o
 obj-$(CONFIG_EFI_LOADER) += efi_device_path.o
 obj-$(CONFIG_EFI_SECURE_BOOT) += efi_image_region.o
 obj-y += hexdump.o
test/lib/alist.c new file +197 -0

197 lines not on this page · raw message

Signature · 1 line
2.34.1
#4 lore raw

Re: [PATCH v4 3/4] alist: Add support for an allocated pointer list

Quoted 10 lines · Simon Glass

In various places it is useful to have an array of structures, but allow it to grow. In some cases we work around it by setting maximum number of entries, using a Kconfig option. In other places we use a linked list, which does not provide for random access and can complicate the code.

Introduce a new data structure, which is a variable-sized list of structs each of the same, pre-set size. It provides O(1) access and is reasonably efficient at expanding linearly, since it doubles in size when it runs out of space.

Quoted 5 lines

---

Changes in v4:
- Avoid using realloc() unless specifically enabled by Kconfig

Is this really so performance critical that we can't always just use malloc/free here?

Signature · 1 line
Tom
#5 lore raw

Re: [PATCH v4 3/4] alist: Add support for an allocated pointer list

Hi Tom,

Quoted 12 lines · Tom Rini
Quoted 10 lines · Simon Glass

In various places it is useful to have an array of structures, but allow it to grow. In some cases we work around it by setting maximum number of entries, using a Kconfig option. In other places we use a linked list, which does not provide for random access and can complicate the code.

Introduce a new data structure, which is a variable-sized list of structs each of the same, pre-set size. It provides O(1) access and is reasonably efficient at expanding linearly, since it doubles in size when it runs out of space.

Quoted 8 lines
Quoted 5 lines

---

Changes in v4:
- Avoid using realloc() unless specifically enabled by Kconfig

Is this really so performance critical that we can't always just use malloc/free here?

I would have to write some sort of test suite to get a better feel for that. The realloc() can be instant if there is space above the current item, whereas the malloc() approach always does a copy.

It is certainly odd to use malloc()/free() when realloc() is there, so I think it makes sense to provide the option.

Regards,
SImon

#6 lore raw

Re: [PATCH v4 3/4] alist: Add support for an allocated pointer list

Quoted 24 lines · Simon Glass

Hi Tom,

Quoted 12 lines · Tom Rini
Quoted 10 lines · Simon Glass

In various places it is useful to have an array of structures, but allow it to grow. In some cases we work around it by setting maximum number of entries, using a Kconfig option. In other places we use a linked list, which does not provide for random access and can complicate the code.

Introduce a new data structure, which is a variable-sized list of structs each of the same, pre-set size. It provides O(1) access and is reasonably efficient at expanding linearly, since it doubles in size when it runs out of space.

Quoted 8 lines
Quoted 5 lines

---

Changes in v4:
- Avoid using realloc() unless specifically enabled by Kconfig

Is this really so performance critical that we can't always just use malloc/free here?

Quoted 6 lines

I would have to write some sort of test suite to get a better feel for that. The realloc() can be instant if there is space above the current item, whereas the malloc() approach always does a copy.

It is certainly odd to use malloc()/free() when realloc() is there, so I think it makes sense to provide the option.

Well, we have realloc but generally don't use it. After a quick grep I'm inclined to suggest we just go without it.

Signature · 1 line
Tom
#7 lore raw

PATCH v4 4/4 RFC: lib: Convert str_to_list() to use alist

In reply to Simon Glass

Use this new data structure in the utility function.

---

(no changes since v3)

Changes in v3:
- Update for alist_add() API change

 lib/strto.c | 35 +++++++++++++++++++----------------
 1 file changed, 19 insertions(+), 16 deletions(-)
lib/strto.c +19 -16
index f83ac67c666..277e83b20fd 100644
@@ -9,6 +9,7 @@
  * Wirzenius wrote this portably, Torvalds fucked it up :-)
  */
 
+#include <alist.h>
 #include <errno.h>
 #include <malloc.h>
 #include <vsprintf.h>
@@ -226,37 +227,39 @@ void str_to_upper(const char *in, char *out, size_t len)
 
 const char **str_to_list(const char *instr)
 {
-	const char **ptr;
-	char *str, *p;
-	int count, i;
+	struct alist alist;
+	char *str, *p, *start;
 
 	/* don't allocate if the string is empty */
 	str = *instr ? strdup(instr) : (char *)instr;
 	if (!str)
 		return NULL;
 
-	/* count the number of space-separated strings */
-	for (count = 0, p = str; *p; p++) {
+	alist_init_struct(&alist, char *);
+
+	if (*str)
+		alist_add(&alist, str, char *);
+	for (start = str, p = str; *p; p++) {
 		if (*p == ' ') {
-			count++;
 			*p = '\0';
+			start = p + 1;
+			if (*start)
+				alist_add(&alist, start, char *);
 		}
 	}
-	if (p != str && p[-1])
-		count++;
 
-	/* allocate the pointer array, allowing for a NULL terminator */
-	ptr = calloc(count + 1, sizeof(char *));
-	if (!ptr) {
-		if (*str)
+	/* terminate list */
+	p = NULL;
+	alist_add(&alist, p, char *);
+	if (alist_err(&alist)) {
+		alist_uninit(&alist);
+
+		if (*instr)
 			free(str);
 		return NULL;
 	}
 
-	for (i = 0, p = str; i < count; p += strlen(p) + 1, i++)
-		ptr[i] = p;
-
-	return ptr;
+	return alist_uninit_move(&alist, NULL, const char *);
 }
 
 void str_free_list(const char **ptr)
Signature · 1 line
2.34.1