[PATCH 1/3] partitions: add function to find free space on partition table

Sascha Hauer s.hauer at pengutronix.de
Thu May 22 06:40:22 PDT 2025


We currently only support creating partitions by specifying the exact
start and end position. Add some functions to find free space in a
partition table so that we can implement creating partitions with only
specifying the size.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 common/partitions.c  | 42 ++++++++++++++++++++++++++++++++++++++++++
 include/partitions.h |  3 ++-
 2 files changed, 44 insertions(+), 1 deletion(-)

diff --git a/common/partitions.c b/common/partitions.c
index bc90f51f611223a59a28812b0f9854b342b30ad3..25d5f15721fc5980c927863b2745c23d7149da92 100644
--- a/common/partitions.c
+++ b/common/partitions.c
@@ -163,6 +163,48 @@ int partition_table_write(struct partition_desc *pdesc)
 	return pdesc->parser->write(pdesc);
 }
 
+bool partition_is_free(struct partition_desc *pdesc, uint64_t start, uint64_t size)
+{
+	struct partition *p;
+
+	if (start < PARTITION_ALIGN_SECTORS)
+		return false;
+
+	if (start + size >= pdesc->blk->num_blocks)
+		return false;
+
+	list_for_each_entry(p, &pdesc->partitions, list) {
+		if (region_overlap_size(p->first_sec, p->size, start, size))
+			return false;
+	}
+
+	return true;
+}
+
+int partition_find_free_space(struct partition_desc *pdesc, uint64_t sectors, uint64_t *start)
+{
+	struct partition *p;
+	uint64_t min_sec = PARTITION_ALIGN_SECTORS;
+
+	min_sec = ALIGN(min_sec, PARTITION_ALIGN_SECTORS);
+
+	if (partition_is_free(pdesc, min_sec, sectors)) {
+		*start = min_sec;
+		return 0;
+	}
+
+	list_for_each_entry(p, &pdesc->partitions, list) {
+		uint64_t s = ALIGN(p->first_sec + p->size, PARTITION_ALIGN_SECTORS);
+
+		if (partition_is_free(pdesc, s, sectors)) {
+			*start = s;
+			return 0;
+		}
+	}
+
+	return -ENOSPC;
+}
+
 int partition_create(struct partition_desc *pdesc, const char *name,
 		     const char *fs_type, uint64_t lba_start, uint64_t lba_end)
 {
diff --git a/include/partitions.h b/include/partitions.h
index 785fb77ab1674d92fdbac5f5df03910b1e2196af..7fd6899bd3b88f691385c330bb7900d9ec1547ac 100644
--- a/include/partitions.h
+++ b/include/partitions.h
@@ -64,6 +64,7 @@ int partition_create(struct partition_desc *pdesc, const char *name,
 		     const char *fs_type, uint64_t lba_start, uint64_t lba_end);
 int partition_remove(struct partition_desc *pdesc, int num);
 void partition_table_free(struct partition_desc *pdesc);
-
+bool partition_is_free(struct partition_desc *pdesc, uint64_t start, uint64_t size);
+int partition_find_free_space(struct partition_desc *pdesc, uint64_t sectors, uint64_t *start);
 
 #endif /* __PARTITIONS_PARSER_H__ */

-- 
2.39.5




More information about the barebox mailing list