[PATCH 3/3] parted: implement mkpart_size command

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


This creates a command which creates a partition with specified size.
The command finds a suitable place for the partition itself.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 commands/parted.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 55 insertions(+)

diff --git a/commands/parted.c b/commands/parted.c
index 221c6fc98601f1532ea85e000d1e2147f7a5af63..6872a8414c79e8e116c9ecce864888cec542ad18 100644
--- a/commands/parted.c
+++ b/commands/parted.c
@@ -192,6 +192,57 @@ static int do_mkpart(struct block_device *blk, int argc, char *argv[])
 	return ret < 0 ? ret : 5;
 }
 
+static int do_mkpart_size(struct block_device *blk, int argc, char *argv[])
+{
+	struct partition_desc *pdesc;
+	uint64_t size, start;
+	const char *name, *fs_type;
+	int ret;
+	uint64_t mult;
+
+	if (argc < 4) {
+		printf("Error: Missing required arguments\n");
+		return -EINVAL;
+	}
+
+	name = argv[1];
+	fs_type = argv[2];
+
+	ret = parted_strtoull(argv[3], &size, &mult);
+	if (ret)
+		return ret;
+
+	if (!mult)
+		mult = gunit;
+
+	size *= mult;
+
+	/* If not on sector boundaries move start up and end down */
+	size = ALIGN(size, PARTITION_ALIGN_SIZE);
+
+	/* convert to LBA */
+	size >>= SECTOR_SHIFT;
+
+	pdesc = pdesc_get(blk);
+	if (!pdesc)
+		return -EINVAL;
+
+	ret = partition_find_free_space(pdesc, size, &start);
+	if (ret) {
+		printf("No free space for %llu sectors found\n", size);
+		return ret;
+	}
+
+	printf("%s: creating partition with %llu blocks at %llu\n", __func__, size, start);
+
+	ret = partition_create(pdesc, name, fs_type, start, start + size - 1);
+
+	if (!ret)
+		table_needs_write = true;
+
+	return ret < 0 ? ret : 4;
+}
+
 static int do_rmpart(struct block_device *blk, int argc, char *argv[])
 {
 	struct partition_desc *pdesc;
@@ -267,6 +318,9 @@ struct parted_command parted_commands[] = {
 		.name = "mkpart",
 		.command = do_mkpart,
 	}, {
+		.name = "mkpart_size",
+		.command = do_mkpart_size,
+	},  {
 		.name = "print",
 		.command = do_print,
 	}, {
@@ -360,6 +414,7 @@ BAREBOX_CMD_HELP_OPT ("print", "print partitions")
 BAREBOX_CMD_HELP_OPT ("mklabel <type>", "create a new partition table")
 BAREBOX_CMD_HELP_OPT ("rm <num>", "remove a partition")
 BAREBOX_CMD_HELP_OPT ("mkpart <name> <fstype> <start> <end>", "create a new partition")
+BAREBOX_CMD_HELP_OPT ("mkpart_size <name> <fstype> <size>", "create a new partition")
 BAREBOX_CMD_HELP_OPT ("unit <unit>", "change display/input units")
 BAREBOX_CMD_HELP_OPT ("refresh", "refresh a partition table")
 BAREBOX_CMD_HELP_TEXT("")

-- 
2.39.5




More information about the barebox mailing list