Skip to contentSkip to conversation

disk: Fix the GPT layout on media with large logical blocks

PATCH Superseded Alexey Charkov 3 participants 15 messages Sep 18 – Oct 10

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover disk: Fix the GPT layout on media with large logical blocks

The GPT partition entry array is sized in bytes by the spec, so the number of blocks it takes up depends on the block size of the device. U-Boot got that wrong in gpt_fill_header(), which reserved a fixed 34 blocks at each end of the disk. On a device with 4096-byte native sectors, such as UFS flash, the backup entry array ended up 28 blocks short of the backup GPT header instead of immediately before it, and roughly 114 KiB was wasted at each end of the disk.

Patch 1 calculates the count from the block size and makes the four places that need it share one helper, since they disagreed with each other in different ways. Note that it also changes the 512-byte layout for boards that do not use the default entry count:
CONFIG_EFI_PARTITION_ENTRIES_NUMBERS is "default 56 if ARCH_SUNXI" and is set to 64 by a number of Rockchip defconfigs, and on those first_usable_lba moves from 34 to 16 and 18 respectively. Existing tables stay readable, since the entry array is always located from the on-disk partition_entry_lba, and only newly written tables are affected. Partitions given without an explicit start= will be placed lower, though, and on sunxi first_usable_lba lands exactly on the 8 KiB SPL offset, so sunxi and Rockchip folks may want to look at patch 1 specifically (none of the devices I have override the default).

Patch 2 has grown since v1. It started as a big-endian correctness fix noticed while auditing the file, and once the new test in patch 4 could drive a real block device on a big-endian target it turned up two more problems in the same family, both of which make a table written on big-endian useless.

Patch 3 from v1 was dropped in favor of outright removal of the old MAC partition label support, as suggested by Heinrich (already in next).

Patches 3 and 4 add the C tests, which are complementary rather than alternatives. Patch 3 drives gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, which is the only practical way to sweep block sizes from 512 to 32768, but it can never reach anything that touches the medium. Patch 5 backs a blkmap device with plain memory and does a full write/verify/parse round trip, covering set_protective_mbr(), is_pmbr_valid(), gpt_verify_headers(), is_gpt_valid() and part_get_info_efi(). Both live in the lib suite rather than test/dm/, because UT_DM depends on SANDBOX and test/dm/part.c is built for sandbox only, whereas test/lib/ is built for every board with CONFIG_UNIT_TEST.

Patch 5 enables EFI_PARTITION and BLKMAP on malta64 so both tests are actually built and run on a big-endian target. malta64 already sets CONFIG_UNIT_TEST and already runs the full pytest suite in CI as the qemu_malta64 job, and ut subtests are collected from u-boot.sym, so no CI change is needed. malta64 rather than malta because hdr_start/pte_start in gpt_fill_pte() are size_t: on a 32-bit big-endian target an unconverted __le64 truncates to zero and the overlap check still happens to reject an overlap, while on MIPS64 it does not.

Patches 6 and 7 add the sandbox-side python test. Patch 6 is a
prerequisite: test_gpt_write_part_type() never binds its own disk image and has only worked because an earlier test left host 0 bound, so it breaks as soon as a test binding a different image is added above it.

One known gap: test_gpt_write and test_gpt_write_part_type hardcode the 128-entry 512-byte layout, so they fail if sandbox is configured with a different CONFIG_EFI_PARTITION_ENTRIES_NUMBERS. The new tests derive their expectations instead, and pass at 56 and 64 entries. No sandbox defconfig upstream uses anything but 128, so I have left the old tests alone.

Still not covered: gpt_verify_partitions() and friends now have big-endian coverage against a device U-Boot wrote itself, but nothing checks that U-Boot parses a spec-conformant table produced by someone else on big-endian. That needs a real disk image attached to the QEMU target, which means teaching u-boot-test-hooks to pass one and, for the 4Kn case, using virtio-blk rather than IDE, since drivers/block/ide.c hardcodes ATA_BLOCKSIZE. I am happy to look at that separately if it is wanted.

Tested by building sandbox (default, flattree, sandbox64, spl, vpl, gcc and clang), generic-rk3576, sonoff-ihost-rv1126, A20-OLinuXino_MICRO-eMMC, turris_mox, boston64r2, qemu-ppce500 and all four malta variants, with no new warnings on any commit of the series, and by running the full sandbox pytest suite plus 'ut lib' on malta64 under qemu-system-mips64.

CI passes all green: https://git.u-boot-project.org/u-boot/contributors/alchark/u-boot/-/pipelines/1326

---
Changes in v2:
- Rebased onto next
- Patch 1: reword the commit message only. The entry array is sized from num_partition_entries and sizeof_partition_entry rather than a fixed 128-byte entry, and the two counts that could disagree are now named. No code change.
- Patch 2: also convert the protective MBR fields and the GPT partition names, and fix print_efiname() to match. Both were found by running the new patch 4 test on big-endian, and both make a table written on big-endian unreadable. Dropped the v1 Reviewed-by tags from this patch, since it grew three hunks nobody has seen.
- Patch 3 (old): superseded by the removal of part_mac
- Patch 3: moved out of test/dm/part.c into test/lib/, so it is built and run on boards other than sandbox.
- Patch 4 is new: a GPT write/verify/parse round trip against a memory-backed blkmap device, which covers the paths a synthetic descriptor cannot reach.
- Patch 5 is new: enable EFI_PARTITION and BLKMAP on malta64 so both C tests run on a big-endian target in CI.
- Patch 6: unbind the 4096-byte device at the end of the new test, so it does not leak into whatever runs next.
- Link to v1: https://patch.msgid.link/[email protected]

To: [email protected]
To: Patrice Chotard <[email protected]>
To: Patrick Delaunay <[email protected]>
Cc: Tom Rini <[email protected]>
Cc: Alexey Charkov <[email protected]>
Cc: Ilias Apalodimas <[email protected]>
Cc: Denis Mukhin <[email protected]>
Cc: Simon Glass <[email protected]>
Cc: Paul Burton <[email protected]>
Cc: Heinrich Schuchardt <[email protected]>

---
Alexey Charkov (7):
disk: part_efi: Size the partition entry array from the block size
disk: part_efi: Add missing endianness conversions
test: lib: Check the GPT layout for large sector sizes
test: lib: Check the GPT round trip against a real block device
configs: malta64: Enable EFI_PARTITION and BLKMAP for big-endian tests
test: py: gpt: Bind the disk image in test_gpt_write_part_type()
test: py: gpt: Test the GPT layout on a device with 4096-byte blocks

 configs/malta64_defconfig |   2 +
 disk/part_efi.c           |  66 ++++++++----
 test/lib/Makefile         |   1 +
 test/lib/part_efi.c       | 257 ++++++++++++++++++++++++++++++++++++++++++++++
 test/py/tests/test_gpt.py | 120 ++++++++++++++++++++++
 5 files changed, 425 insertions(+), 21 deletions(-)

---
base-commit: b8e0086b585791a771416ce51b58ce0097bc0b28
change-id: 20260731-gpt-4k-f8b9e3fad474

Best regards,

Signature · 1 line
Alexey Charkov <[email protected]>
#1 lore raw

PATCH v2 1/7 disk: part_efi: Size the partition entry array from the block size

gpt_fill_header() computes last_usable_lba and first_usable_lba from hardcoded block counts that silently assume 512-byte sectors and the default number of partition entries.

The partition entry array holds num_partition_entries entries of sizeof_partition_entry bytes each, both of which the GPT header carries, so the number of blocks it needs depends on those two fields and on the block size. gpt_fill_header() reserves a fixed 34 blocks instead, while write_gpt_table() derives the real extent and writes the backup array at last_usable_lba + 1, so whenever the reserved count and the written extent differ the backup array no longer immediately precedes the backup GPT header. Furthermore, on a device with 4096-byte native sectors, such as UFS flash, and the default entry count, the array is 4 blocks rather than 32. Current code reserves 34 blocks at each end of the disk for any block size and wastes about 114 KiB at each end.

Add a new helper gpt_pte_blocks() and use it in all four places which currently calculate the number of blocks each in its own way, so the layout written by gpt_fill_header() and the extent written by write_gpt_table() cannot drift apart again. With this, first_usable_lba on 4096-byte sectors is 6, last_usable_lba is lba - 6, and the backup array occupies lba - 5 .. lba - 2, immediately preceding the backup header, as the UEFI specification describes.

Note that this changes the 512-byte layout too for boards that do not use the default entry count. CONFIG_EFI_PARTITION_ENTRIES_NUMBERS is "default 56 if ARCH_SUNXI" and is set to 64 by a number of Rockchip defconfigs:

  entries  array blocks  first_usable_lba  last_usable_lba
       56            14        34 -> 16    lba - 34 -> lba - 16
       64            16        34 -> 18    lba - 34 -> lba - 18
      128            32        34 -> 34    lba - 34 -> lba - 34

Existing partition tables stay readable either way, since is_gpt_valid() locates the entry array from the on-disk partition_entry_lba. Only newly written tables change. Partitions given without an explicit start= will now be placed lower on those boards; on sunxi first_usable_lba lands on the 8 KiB SPL offset, so such boards should keep specifying start= explicitly.

While here, report both LBAs when the requested layout does not fit, since the existing "Partitions layout exceeds disk size" debug message gives no clue as to by how much, making it less helpful in debugging.

---
 disk/part_efi.c | 47 +++++++++++++++++++++++++++++++++++------------
 1 file changed, 35 insertions(+), 12 deletions(-)
disk/part_efi.c +35 -12
index de7048639a6d..ede8bcddce1f 100644
@@ -391,10 +391,23 @@ static int set_protective_mbr(struct blk_desc *desc)
 	return 0;
 }
 
+/**
+ * gpt_pte_blocks() - number of blocks taken up by a partition entry array
+ *
+ * @desc:	block device descriptor
+ * @gpt_h:	GPT header describing the array
+ * Return: number of blocks the array occupies on @desc
+ */
+static u32 gpt_pte_blocks(struct blk_desc *desc, const gpt_header *gpt_h)
+{
+	return DIV_ROUND_UP(le32_to_cpu(gpt_h->num_partition_entries) *
+			    le32_to_cpu(gpt_h->sizeof_partition_entry),
+			    desc->blksz);
+}
+
 int write_gpt_table(struct blk_desc *desc, gpt_header *gpt_h, gpt_entry *gpt_e)
 {
-	const int pte_blk_cnt = BLOCK_CNT((gpt_h->num_partition_entries
-					   * sizeof(gpt_entry)), desc);
+	const int pte_blk_cnt = gpt_pte_blocks(desc, gpt_h);
 	u32 calc_crc32;
 
 	debug("max lba: %x\n", (u32)desc->lba);
@@ -456,9 +469,7 @@ int gpt_fill_pte(struct blk_desc *desc,
 	size_t hdr_end = hdr_start + 1;
 
 	size_t pte_start = gpt_h->partition_entry_lba;
-	size_t pte_end = pte_start +
-		gpt_h->num_partition_entries * gpt_h->sizeof_partition_entry /
-		desc->blksz;
+	size_t pte_end = pte_start + gpt_pte_blocks(desc, gpt_h);
 
 	for (i = 0; i < parts; i++) {
 		/* partition starting lba */
@@ -485,7 +496,9 @@ int gpt_fill_pte(struct blk_desc *desc,
 		gpt_e[i].starting_lba = cpu_to_le64(start);
 
 		if (offset > (last_usable_lba + 1)) {
-			log_debug("Partitions layout exceeds disk size\n");
+			log_debug("Partitions layout exceeds disk size: "
+				  LBAFU " > " LBAFU "\n",
+				  offset, last_usable_lba + 1);
 			return -E2BIG;
 		}
 		/* partition ending lba */
@@ -607,18 +620,29 @@ static uint32_t partition_entries_offset(struct blk_desc *desc)
 int gpt_fill_header(struct blk_desc *desc, gpt_header *gpt_h, char *str_guid,
 		    int parts_count)
 {
+	u32 pte_sectors;
+
 	gpt_h->signature = cpu_to_le64(GPT_HEADER_SIGNATURE_UBOOT);
 	gpt_h->revision = cpu_to_le32(GPT_HEADER_REVISION_V1);
 	gpt_h->header_size = cpu_to_le32(sizeof(gpt_header));
+	gpt_h->num_partition_entries = cpu_to_le32(GPT_ENTRY_NUMBERS);
+	gpt_h->sizeof_partition_entry = cpu_to_le32(sizeof(gpt_entry));
+
+	/*
+	 * Number of blocks occupied by the partition entry array. For the
+	 * default of 128 entries that is 32 blocks on 512-byte sectors, but
+	 * only 4 blocks on 4096-byte sectors.
+	 */
+	pte_sectors = gpt_pte_blocks(desc, gpt_h);
+
 	gpt_h->my_lba = cpu_to_le64(1);
 	gpt_h->alternate_lba = cpu_to_le64(desc->lba - 1);
-	gpt_h->last_usable_lba = cpu_to_le64(desc->lba - 34);
+	/* Reserve space for backup GPT header (1) + backup partition entries */
+	gpt_h->last_usable_lba = cpu_to_le64(desc->lba - pte_sectors - 2);
 	gpt_h->partition_entry_lba =
 		cpu_to_le64(partition_entries_offset(desc));
 	gpt_h->first_usable_lba =
-		cpu_to_le64(le64_to_cpu(gpt_h->partition_entry_lba) + 32);
-	gpt_h->num_partition_entries = cpu_to_le32(GPT_ENTRY_NUMBERS);
-	gpt_h->sizeof_partition_entry = cpu_to_le32(sizeof(gpt_entry));
+		cpu_to_le64(le64_to_cpu(gpt_h->partition_entry_lba) + pte_sectors);
 	gpt_h->header_crc32 = 0;
 	gpt_h->partition_entry_array_crc32 = 0;
 
@@ -750,8 +774,7 @@ static void restore_primary_gpt_header(gpt_header *gpt_h, struct blk_desc *desc)
 static int write_one_gpt_table(struct blk_desc *desc, gpt_header *gpt_h,
 			       gpt_entry *gpt_e)
 {
-	const int pte_blk_cnt = BLOCK_CNT((gpt_h->num_partition_entries
-					   * sizeof(gpt_entry)), desc);
+	const int pte_blk_cnt = gpt_pte_blocks(desc, gpt_h);
 	lbaint_t start;
 	int ret = 0;
 
Signature · 1 line
2.55.0
#2 lore raw

PATCH v2 2/7 disk: part_efi: Add missing endianness conversions

In reply to Alexey Charkov

Several GPT fields are read or written without converting to or from little-endian, which is wrong on big-endian hosts.

gpt_fill_pte() takes my_lba and partition_entry_lba raw when working out the region a partition must not overlap, so on a big-endian host both bounds are byte-swapped garbage and the overlap check does not do anything useful.

gpt_verify_partitions() compares the loop counter against num_partition_entries raw, so its "More partitions than allowed!" guard never triggers. It also swaps gpt_part_size, which is already in host order, having been computed from two le64_to_cpu() results a few lines above; drop that conversion rather than adding one. Left as it was, the size check on big-endian rejects a correct table with the memorable

Partition first size: 256 does not match 256!

set_protective_mbr() stores the MBR signature and the protective partition's start_sect and nr_sects straight into __le16 and __le32 fields. is_pmbr_valid() reads them back with le16_to_cpu() and get_unaligned_le32(), so on big-endian part_test_efi() rejects the table U-Boot has just written: 'part list' reports nothing and desc->part_type stays PART_TYPE_UNKNOWN. Linux and the UEFI specification expect the protective MBR little-endian too, so such a disk is useless everywhere.

gpt_fill_pte() writes partition names as native efi_char16_t, but the specification stores them as UTF-16LE. The two readers here then
disagree: print_efiname() takes the low byte of a native u16 and so matches what was written, while gpt_convert_efi_name_to_char() walks the raw bytes and follows the specification. gpt_verify_partitions() uses the latter, so on big-endian verifying a freshly written table fails with an empty name. Write the name little-endian and read it back the same way.

All of this is a no-op on little-endian targets.

---
 disk/part_efi.c | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)
disk/part_efi.c +10 -9
index ede8bcddce1f..d8751297fbe9 100644
@@ -67,7 +67,7 @@ static char *print_efiname(gpt_entry *pte)
 	int i;
 	for (i = 0; i < PARTNAME_SZ; i++) {
 		u8 c;
-		c = pte->partition_name[i] & 0xff;
+		c = le16_to_cpu(pte->partition_name[i]) & 0xff;
 		c = (c && !isprint(c)) ? '.' : c;
 		name[i] = c;
 	}
@@ -377,10 +377,10 @@ static int set_protective_mbr(struct blk_desc *desc)
 			MSDOS_MBR_BOOT_CODE_SIZE);
 
 	/* Append signature */
-	p_mbr->signature = MSDOS_MBR_SIGNATURE;
+	p_mbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
 	p_mbr->partition_record[0].sys_ind = EFI_PMBR_OSTYPE_EFI_GPT;
-	p_mbr->partition_record[0].start_sect = 1;
-	p_mbr->partition_record[0].nr_sects = (u32)desc->lba - 1;
+	p_mbr->partition_record[0].start_sect = cpu_to_le32(1);
+	p_mbr->partition_record[0].nr_sects = cpu_to_le32((u32)desc->lba - 1);
 
 	/* Write MBR sector to the MMC device */
 	if (blk_dwrite(desc, 0, 1, p_mbr) != 1) {
@@ -465,10 +465,10 @@ int gpt_fill_pte(struct blk_desc *desc,
 	char *str_type_guid;
 	unsigned char *bin_type_guid;
 #endif
-	size_t hdr_start = gpt_h->my_lba;
+	size_t hdr_start = le64_to_cpu(gpt_h->my_lba);
 	size_t hdr_end = hdr_start + 1;
 
-	size_t pte_start = gpt_h->partition_entry_lba;
+	size_t pte_start = le64_to_cpu(gpt_h->partition_entry_lba);
 	size_t pte_end = pte_start + gpt_pte_blocks(desc, gpt_h);
 
 	for (i = 0; i < parts; i++) {
@@ -560,7 +560,8 @@ int gpt_fill_pte(struct blk_desc *desc,
 
 		for (k = 0; k < min(dosname_len, efiname_len); k++)
 			gpt_e[i].partition_name[k] =
-				(efi_char16_t)(partitions[i].name[k]);
+				cpu_to_le16((efi_char16_t)
+					    (partitions[i].name[k]));
 
 		debug("%s: name: %s offset[%d]: 0x" LBAF
 		      " size[%d]: 0x" LBAF "\n",
@@ -854,7 +855,7 @@ int gpt_verify_partitions(struct blk_desc *desc,
 	gpt_e = *gpt_pte;
 
 	for (i = 0; i < parts; i++) {
-		if (i == gpt_head->num_partition_entries) {
+		if (i == le32_to_cpu(gpt_head->num_partition_entries)) {
 			pr_err("More partitions than allowed!\n");
 			return -1;
 		}
@@ -880,7 +881,7 @@ int gpt_verify_partitions(struct blk_desc *desc,
 		      (unsigned long long)gpt_part_size,
 		      (unsigned long long)partitions[i].size);
 
-		if (le64_to_cpu(gpt_part_size) != partitions[i].size) {
+		if (gpt_part_size != partitions[i].size) {
 			/* We do not check the extend partition size */
 			if ((i == parts - 1) && (partitions[i].size == 0))
 				continue;
Signature · 1 line
2.55.0
#3 lore raw

Re: [PATCH v2 2/7] disk: part_efi: Add missing endianness conversions

Am 18. September 2026 14:13:51 MESZ schrieb Alexey Charkov <[email protected]>:

Quoted 45 lines

Several GPT fields are read or written without converting to or from little-endian, which is wrong on big-endian hosts.

gpt_fill_pte() takes my_lba and partition_entry_lba raw when working out the region a partition must not overlap, so on a big-endian host both bounds are byte-swapped garbage and the overlap check does not do anything useful.

gpt_verify_partitions() compares the loop counter against num_partition_entries raw, so its "More partitions than allowed!" guard never triggers. It also swaps gpt_part_size, which is already in host order, having been computed from two le64_to_cpu() results a few lines above; drop that conversion rather than adding one. Left as it was, the size check on big-endian rejects a correct table with the memorable

Partition first size: 256 does not match 256!

set_protective_mbr() stores the MBR signature and the protective partition's start_sect and nr_sects straight into __le16 and __le32 fields. is_pmbr_valid() reads them back with le16_to_cpu() and get_unaligned_le32(), so on big-endian part_test_efi() rejects the table U-Boot has just written: 'part list' reports nothing and desc->part_type stays PART_TYPE_UNKNOWN. Linux and the UEFI specification expect the protective MBR little-endian too, so such a disk is useless everywhere.

gpt_fill_pte() writes partition names as native efi_char16_t, but the specification stores them as UTF-16LE. The two readers here then
disagree: print_efiname() takes the low byte of a native u16 and so matches what was written, while gpt_convert_efi_name_to_char() walks the raw bytes and follows the specification. gpt_verify_partitions() uses the latter, so on big-endian verifying a freshly written table fails with an empty name. Write the name little-endian and read it back the same way.

All of this is a no-op on little-endian targets.

---
disk/part_efi.c | 19 ++++++++++---------

1 file changed, 10 insertions(+), 9 deletions(-)
disk/part_efi.c +0 -0
index ede8bcddce1f..d8751297fbe9 100644

disk/part_efi.c static char *print_efiname(gpt_entry *pte) · line 70

Quoted 5 lines
disk/part_efi.c +1 -1
@@ -67,7 +67,7 @@ static char *print_efiname(gpt_entry *pte)
 	int i;
 	for (i = 0; i < PARTNAME_SZ; i++) {
 		u8 c;
-		c = pte->partition_name[i] & 0xff;
+		c = le16_to_cpu(pte->partition_name[i]) & 0xff;

Partition names are not restricted to ANSI characters. Please, convert to UTF-8. Look in charset.h for the right library function. Check if the library function works correctly on big-endian.

Quoted 31 lines
disk/part_efi.c +5 -5
 		c = (c && !isprint(c)) ? '.' : c;
 		name[i] = c;
 	}
@@ -377,10 +377,10 @@ static int set_protective_mbr(struct blk_desc *desc)
 			MSDOS_MBR_BOOT_CODE_SIZE);
 
 	/* Append signature */
-	p_mbr->signature = MSDOS_MBR_SIGNATURE;
+	p_mbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
 	p_mbr->partition_record[0].sys_ind = EFI_PMBR_OSTYPE_EFI_GPT;
-	p_mbr->partition_record[0].start_sect = 1;
-	p_mbr->partition_record[0].nr_sects = (u32)desc->lba - 1;
+	p_mbr->partition_record[0].start_sect = cpu_to_le32(1);
+	p_mbr->partition_record[0].nr_sects = cpu_to_le32((u32)desc->lba - 1);
 
 	/* Write MBR sector to the MMC device */
 	if (blk_dwrite(desc, 0, 1, p_mbr) != 1) {
@@ -465,10 +465,10 @@ int gpt_fill_pte(struct blk_desc *desc,
 	char *str_type_guid;
 	unsigned char *bin_type_guid;
 #endif
-	size_t hdr_start = gpt_h->my_lba;
+	size_t hdr_start = le64_to_cpu(gpt_h->my_lba);
 	size_t hdr_end = hdr_start + 1;
 
-	size_t pte_start = gpt_h->partition_entry_lba;
+	size_t pte_start = le64_to_cpu(gpt_h->partition_entry_lba);
 	size_t pte_end = pte_start + gpt_pte_blocks(desc, gpt_h);
 
 	for (i = 0; i < parts; i++) {

disk/part_efi.c int gpt_fill_pte(struct blk_desc *desc, · line 563

Quoted 5 lines
disk/part_efi.c +1 -1
@@ -560,7 +560,8 @@ int gpt_fill_pte(struct blk_desc *desc,
 
 		for (k = 0; k < min(dosname_len, efiname_len); k++)
 			gpt_e[i].partition_name[k] =
-				(efi_char16_t)(partitions[i].name[k]);
+				cpu_to_le16((efi_char16_t)

UTF-8 should be converted to UTF-16 here using a library function.

Best regards

Heinrich

Quoted 23 lines
disk/part_efi.c +3 -2
+					    (partitions[i].name[k]));
 
 		debug("%s: name: %s offset[%d]: 0x" LBAF
 		      " size[%d]: 0x" LBAF "\n",
@@ -854,7 +855,7 @@ int gpt_verify_partitions(struct blk_desc *desc,
 	gpt_e = *gpt_pte;
 
 	for (i = 0; i < parts; i++) {
-		if (i == gpt_head->num_partition_entries) {
+		if (i == le32_to_cpu(gpt_head->num_partition_entries)) {
 			pr_err("More partitions than allowed!\n");
 			return -1;
 		}
@@ -880,7 +881,7 @@ int gpt_verify_partitions(struct blk_desc *desc,
 		      (unsigned long long)gpt_part_size,
 		      (unsigned long long)partitions[i].size);
 
-		if (le64_to_cpu(gpt_part_size) != partitions[i].size) {
+		if (gpt_part_size != partitions[i].size) {
 			/* We do not check the extend partition size */
 			if ((i == parts - 1) && (partitions[i].size == 0))
 				continue;
#4 lore raw

Re: [PATCH v2 2/7] disk: part_efi: Add missing endianness conversions

Quoted 42 lines · Heinrich Schuchardt

Am 18. September 2026 14:13:51 MESZ schrieb Alexey Charkov <[email protected]>:

Quoted 40 lines

Several GPT fields are read or written without converting to or from little-endian, which is wrong on big-endian hosts.

gpt_fill_pte() takes my_lba and partition_entry_lba raw when working out the region a partition must not overlap, so on a big-endian host both bounds are byte-swapped garbage and the overlap check does not do anything useful.

gpt_verify_partitions() compares the loop counter against num_partition_entries raw, so its "More partitions than allowed!" guard never triggers. It also swaps gpt_part_size, which is already in host order, having been computed from two le64_to_cpu() results a few lines above; drop that conversion rather than adding one. Left as it was, the size check on big-endian rejects a correct table with the memorable

Partition first size: 256 does not match 256!

set_protective_mbr() stores the MBR signature and the protective partition's start_sect and nr_sects straight into __le16 and __le32 fields. is_pmbr_valid() reads them back with le16_to_cpu() and get_unaligned_le32(), so on big-endian part_test_efi() rejects the table U-Boot has just written: 'part list' reports nothing and desc->part_type stays PART_TYPE_UNKNOWN. Linux and the UEFI specification expect the protective MBR little-endian too, so such a disk is useless everywhere.

gpt_fill_pte() writes partition names as native efi_char16_t, but the specification stores them as UTF-16LE. The two readers here then
disagree: print_efiname() takes the low byte of a native u16 and so matches what was written, while gpt_convert_efi_name_to_char() walks the raw bytes and follows the specification. gpt_verify_partitions() uses the latter, so on big-endian verifying a freshly written table fails with an empty name. Write the name little-endian and read it back the same way.

All of this is a no-op on little-endian targets.

---
disk/part_efi.c | 19 ++++++++++---------

1 file changed, 10 insertions(+), 9 deletions(-)
Quoted 12 lines

disk/part_efi.c static char *print_efiname(gpt_entry *pte) · line 70

Quoted 10 lines
disk/part_efi.c +1 -1
index ede8bcddce1f..d8751297fbe9 100644
@@ -67,7 +67,7 @@ static char *print_efiname(gpt_entry *pte)
      int i;
      for (i = 0; i < PARTNAME_SZ; i++) {
              u8 c;
-              c = pte->partition_name[i] & 0xff;
+              c = le16_to_cpu(pte->partition_name[i]) & 0xff;

Partition names are not restricted to ANSI characters. Please, convert to UTF-8. Look in charset.h for the right library function. Check if the library function works correctly on big-endian.

This code is pulled into SPL on 405 boards, and some of them have really tight SPL size restrictions that won't tolerate the inclusion of charset.o in the build (e.g. stm32f746-disco_spl has CONFIG_SPL_SIZE_LIMIT=0x9000).

Adding non-ASCII support sounds like a new feature, whereas this series was meant to be fixes. I can look across the tree for lossy conversions to or from UTF16 strings as a follow-up if that's helpful.

[...]

Quoted 8 lines

disk/part_efi.c int gpt_fill_pte(struct blk_desc *desc, · line 563

Quoted 6 lines
disk/part_efi.c +1 -1
@@ -560,7 +560,8 @@ int gpt_fill_pte(struct blk_desc *desc,
 
              for (k = 0; k < min(dosname_len, efiname_len); k++)
                      gpt_e[i].partition_name[k] =
-                              (efi_char16_t)(partitions[i].name[k]);
+                              cpu_to_le16((efi_char16_t)

UTF-8 should be converted to UTF-16 here using a library function.

Ditto: size :(

Best regards,
Alexey

Reviewed-by on v2 2/7
#5 lore raw

Re: [PATCH v2 2/7] disk: part_efi: Add missing endianness conversions

In reply to Alexey Charkov
Quoted 35 lines · Alexey Charkov

disk: part_efi: Add missing endianness conversions

Several GPT fields are read or written without converting to or from little-endian, which is wrong on big-endian hosts.

gpt_fill_pte() takes my_lba and partition_entry_lba raw when working out the region a partition must not overlap, so on a big-endian host both bounds are byte-swapped garbage and the overlap check does not do anything useful.

gpt_verify_partitions() compares the loop counter against num_partition_entries raw, so its "More partitions than allowed!" guard never triggers. It also swaps gpt_part_size, which is already in host order, having been computed from two le64_to_cpu() results a few lines above; drop that conversion rather than adding one. Left as it was, the size check on big-endian rejects a correct table with the memorable

Partition first size: 256 does not match 256!

set_protective_mbr() stores the MBR signature and the protective partition's start_sect and nr_sects straight into __le16 and __le32 fields. is_pmbr_valid() reads them back with le16_to_cpu() and get_unaligned_le32(), so on big-endian part_test_efi() rejects the table U-Boot has just written: 'part list' reports nothing and desc->part_type stays PART_TYPE_UNKNOWN. Linux and the UEFI specification expect the protective MBR little-endian too, so such a disk is useless everywhere.

gpt_fill_pte() writes partition names as native efi_char16_t, but the specification stores them as UTF-16LE. The two readers here then
disagree: print_efiname() takes the low byte of a native u16 and so matches what was written, while gpt_convert_efi_name_to_char() walks the raw bytes and follows the specification. gpt_verify_partitions() uses the latter, so on big-endian verifying a freshly written table fails with an empty name. Write the name little-endian and read it back the same way.

Quoted 6 lines

All of this is a no-op on little-endian targets.

disk/part_efi.c | 19 ++++++++++---------

 1 file changed, 10 insertions(+), 9 deletions(-)
#6 lore raw

PATCH v2 3/7 test: lib: Check the GPT layout for large sector sizes

In reply to Alexey Charkov

Add a test that runs gpt_fill_header() and gpt_fill_pte() over a range of block sizes and checks that the partition entry array is sized and placed consistently, in particular that the backup array ends exactly where the backup GPT header begins.

Neither function performs any block I/O, so the test builds a synthetic struct blk_desc rather than needing a block device with a configurable block size. The expected array size is taken from the GPT header fields rather than from GPT_ENTRY_NUMBERS, so the test still holds for builds with a non-default CONFIG_EFI_PARTITION_ENTRIES_NUMBERS, such as ARCH_SUNXI with 56 entries.

Put it in the lib suite rather than alongside the other partition tests in test/dm/part.c. UT_DM depends on SANDBOX and test/dm/part.c is built for sandbox only, while test/lib/ is compiled for every board that enables CONFIG_UNIT_TEST, so the lib suite can also cover big-endian targets.

Without the preceding fixes this fails on the first block size other than 512:

test/lib/part_efi.c:78, lib_test_gpt_blksz():

      entry_lba + pte_blks == first_lba: Expected 0x12 (18), got 0x22 (34)
---
 test/lib/Makefile   |   1 +
 test/lib/part_efi.c | 113 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 114 insertions(+)
test/lib/Makefile +1 -0
index f25383a40e58..ed26afcc8a11 100644
@@ -20,6 +20,7 @@ obj-$(CONFIG_LMB) += lmb.o
 obj-$(CONFIG_HAVE_SETJMP) += longjmp.o
 obj-$(CONFIG_SANDBOX) += membuf.o
 obj-$(CONFIG_HAVE_INITJMP) += initjmp.o
+obj-$(CONFIG_EFI_PARTITION) += part_efi.o
 obj-$(CONFIG_CONSOLE_RECORD) += test_print.o
 obj-$(CONFIG_SSCANF) += sscanf.o
 obj-$(CONFIG_$(PHASE_)STRTO) += str.o
test/lib/part_efi.c new file +113 -0

113 lines not on this page · raw message

Signature · 1 line
2.55.0
#7 lore raw

PATCH v2 4/7 test: lib: Check the GPT round trip against a real block device

In reply to Alexey Charkov

lib_test_gpt_blksz() drives gpt_fill_header() and gpt_fill_pte() with a synthetic struct blk_desc. That is what lets it sweep block sizes no real device here can provide, but it also means it cannot reach anything that touches the medium, so the protective MBR, the header CRCs and every conversion behind them go unchecked.

Add a companion test that backs a blkmap device with plain memory, writes a table with gpt_restore(), reads it back with gpt_verify_partitions() and parses it with part_get_info(), then checks that the backup header really did land in the last block. That covers set_protective_mbr(), is_pmbr_valid(), gpt_verify_headers(), is_gpt_valid() and part_get_info_efi().

The two tests are complementary rather than alternatives: gpt_blksz covers the block size arithmetic across sizes a device cannot easily offer, gpt_blkmap covers the read and write paths a synthetic descriptor cannot reach. Neither replaces the sandbox tests in test/py/tests/test_gpt.py, which exercise the gpt command against images built by sgdisk.

A blkmap needs no host filesystem, so unlike 'host bind' this runs on QEMU and on real hardware, which is what makes big-endian coverage possible. Every blkmap is DEFAULT_BLKSZ today, so the block size stays a parameter of the case table with a single entry, ready for a second one should blkmap ever learn to be created with a block size.

---
 test/lib/part_efi.c | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 144 insertions(+)
test/lib/part_efi.c +144 -0
index 75de002278f3..d913ca701825 100644
@@ -4,6 +4,9 @@
  * Tests for the GPT layout helpers in disk/part_efi.c
  */
 
+#include <blk.h>
+#include <blkmap.h>
+#include <dm.h>
 #include <malloc.h>
 #include <memalign.h>
 #include <part.h>
@@ -111,3 +114,144 @@ static int lib_test_gpt_blksz(struct unit_test_state *uts)
 	return 0;
 }
 LIB_TEST(lib_test_gpt_blksz, 0);
+
+#if CONFIG_IS_ENABLED(BLKMAP)
+
+#define GPT_TEST_LABEL	"gpttest"
+
+/**
+ * gpt_blkmap_create() - back a blkmap device with freshly allocated memory
+ *
+ * @uts:	test state
+ * @blksz:	requested block size
+ * @lba:	size of the device in blocks
+ * @bufp:	returns the backing buffer, to be freed by the caller
+ * @devp:	returns the blkmap device
+ * Return: 0 if OK, other value on error
+ */
+static int gpt_blkmap_create(struct unit_test_state *uts, unsigned long blksz,
+			     lbaint_t lba, void **bufp, struct udevice **devp)
+{
+	struct udevice *dev;
+	void *buf;
+
+	/*
+	 * blkmap devices are fixed at DEFAULT_BLKSZ, so this is the only size
+	 * that can be asked for today. Once blkmap can be created with a block
+	 * size, pass it through here and the cases below cover 4096 as well.
+	 */
+	ut_asserteq(DEFAULT_BLKSZ, blksz);
+
+	buf = memalign(ARCH_DMA_MINALIGN, lba * blksz);
+	ut_assertnonnull(buf);
+	memset(buf, '\0', lba * blksz);
+
+	ut_assertok(blkmap_create(GPT_TEST_LABEL, &dev));
+	ut_assertok(blkmap_map_mem(dev, 0, lba, buf));
+
+	*bufp = buf;
+	*devp = dev;
+
+	return 0;
+}
+
+/*
+ * Write a GPT to a real block device, then read it back the way the rest of
+ * U-Boot does. gpt_verify_partitions() and part_get_info() both start by
+ * reading blocks, so neither is reachable from lib_test_gpt_blksz(), which has
+ * only a synthetic descriptor. Backing the device with memory through blkmap
+ * keeps this runnable anywhere rather than on sandbox alone.
+ */
+static int lib_test_gpt_blkmap(struct unit_test_state *uts)
+{
+	static const struct {
+		unsigned long blksz;
+		lbaint_t lba;
+	} cases[] = {
+		/*
+		 * Keep the disk small: the backing memory comes out of the
+		 * malloc pool, which is only a few MB on boards like malta.
+		 * Add a 4096-byte case here once blkmap can be created with a
+		 * block size.
+		 */
+		{ 512, 0x400 },
+	};
+
+	char str_disk_guid[UUID_STR_LEN + 1] =
+		"8d60b397-1bb6-4d33-80ee-b1587d24c2f8";
+	struct disk_partition parts[2], info;
+	struct udevice *dev, *blk;
+	struct blk_desc *desc;
+	gpt_header *gpt_head;
+	gpt_entry *gpt_pte;
+	void *buf;
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++) {
+		ut_assertok(gpt_blkmap_create(uts, cases[i].blksz,
+					      cases[i].lba, &buf, &dev));
+		ut_assertok(blk_get_from_parent(dev, &blk));
+		desc = dev_get_uclass_plat(blk);
+
+		ut_asserteq(cases[i].blksz, desc->blksz);
+		ut_asserteq_64(cases[i].lba, desc->lba);
+
+		gpt_head = malloc_cache_aligned(PAD_TO_BLOCKSIZE
+						(sizeof(gpt_header), desc));
+		ut_assertnonnull(gpt_head);
+
+		/* two partitions, the second one running to the end */
+		memset(parts, '\0', sizeof(parts));
+		strcpy((char *)parts[0].name, "first");
+		strcpy((char *)parts[1].name, "second");
+		parts[0].size = 0x100;
+		parts[1].size = 0x100;
+		disk_partition_set_uuid(&parts[0],
+					"a2a0d0eb-e5b9-3344-87c0-68b6b72699c7");
+		disk_partition_set_uuid(&parts[1],
+					"a2a0d0eb-e5b9-3344-87c0-68b6b72699c8");
+
+		ut_assertok(gpt_restore(desc, str_disk_guid, parts, 2));
+
+		/*
+		 * Read the table back and compare it against the layout it was
+		 * asked for. This walks gpt_verify_headers() and is_gpt_valid()
+		 * on the way, so it covers the header fields those two convert.
+		 */
+		gpt_pte = NULL;
+		ut_assertok(gpt_verify_partitions(desc, parts, 2, gpt_head,
+						  &gpt_pte));
+		free(gpt_pte);
+
+		/*
+		 * And parse it the way every other user of a disk does. Clear
+		 * the existing partition type to force part_init() to guess it
+		 * anew, otherwise whatever stale state remains sticks across
+		 * the part_init() call
+		 */
+		desc->part_type = PART_TYPE_UNKNOWN;
+		part_init(desc);
+		ut_asserteq(PART_TYPE_EFI, desc->part_type);
+		ut_assertok(part_get_info(desc, 1, &info));
+		ut_asserteq_64(parts[0].size, info.size);
+		ut_assertok(part_get_info(desc, 2, &info));
+		ut_asserteq_64(parts[1].size, info.size);
+
+		/* the backup header has to be in the very last block */
+		ut_asserteq(1, blk_dread(desc, cases[i].lba - 1, 1, gpt_head));
+		ut_asserteq_64(GPT_HEADER_SIGNATURE_UBOOT,
+			       le64_to_cpu(gpt_head->signature));
+		ut_asserteq_64(cases[i].lba - 1,
+			       le64_to_cpu(gpt_head->my_lba));
+		ut_asserteq_64(1, le64_to_cpu(gpt_head->alternate_lba));
+
+		free(gpt_head);
+		ut_assertok(blkmap_destroy(dev));
+		free(buf);
+	}
+
+	return 0;
+}
+LIB_TEST(lib_test_gpt_blkmap, 0);
+
+#endif /* BLKMAP */
Signature · 1 line
2.55.0
#8 lore raw

Re: [PATCH v2 4/7] test: lib: Check the GPT round trip against a real block device

Hi Alexey,

Quoted 27 lines · Alexey Charkov

test: lib: Check the GPT round trip against a real block device

lib_test_gpt_blksz() drives gpt_fill_header() and gpt_fill_pte() with a synthetic struct blk_desc. That is what lets it sweep block sizes no real device here can provide, but it also means it cannot reach anything that touches the medium, so the protective MBR, the header CRCs and every conversion behind them go unchecked.

Add a companion test that backs a blkmap device with plain memory, writes a table with gpt_restore(), reads it back with gpt_verify_partitions() and parses it with part_get_info(), then checks that the backup header really did land in the last block. That covers set_protective_mbr(), is_pmbr_valid(), gpt_verify_headers(), is_gpt_valid() and part_get_info_efi().

The two tests are complementary rather than alternatives: gpt_blksz covers the block size arithmetic across sizes a device cannot easily offer, gpt_blkmap covers the read and write paths a synthetic descriptor cannot reach. Neither replaces the sandbox tests in test/py/tests/test_gpt.py, which exercise the gpt command against images [...]

test/lib/part_efi.c | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++

 1 file changed, 144 insertions(+)

test/lib/part_efi.c static int lib_test_gpt_blksz(struct unit_test_state *uts) · line 118

Quoted 5 lines
test/lib/part_efi.c +5 -0
@@ -111,3 +114,144 @@ static int lib_test_gpt_blksz(struct unit_test_state *uts)
+     ut_assertok(blkmap_create(GPT_TEST_LABEL, &dev));
+     ut_assertok(blkmap_map_mem(dev, 0, lba, buf));
+
+     *bufp = buf;
+     *devp = dev;

If blkmap_map_mem() fails here, the blkmap is left bound and buf is leaked, since the caller never sees either of them. The same applies to every ut_assert in lib_test_gpt_blkmap() after the device is created.

This matters more than the usual leak-on-failure because this test does not use UTF_DM, so the device stays under the real dm_root. After one failure, every later run of 'ut lib' fails in blkmap_create() with -EBUSY, which hides the original problem.

Please can you move the body of the loop into a helper, so that the caller can do the blkmap_destroy() and free() regardless of the result? What do you think?

test/lib/part_efi.c static int lib_test_gpt_blksz(struct unit_test_state *uts) · line 119

Quoted 8 lines
test/lib/part_efi.c +6 -0
@@ -111,3 +114,144 @@ static int lib_test_gpt_blksz(struct unit_test_state *uts)
+             /* two partitions, the second one running to the end */
+             memset(parts, '\0', sizeof(parts));
+             strcpy((char *)parts[0].name, "first");
+             strcpy((char *)parts[1].name, "second");
+             parts[0].size = 0x100;
+             parts[1].size = 0x100;

The comment does not match the code. Both partitions are 0x100 blocks, so on a 0x400-block disk the second one ends at 0x221, well short of last_usable_lba. Running to the end needs a size of 0, which gpt_verify_partitions() then skips in its size check.

I suspect the fixed size is what you want, so please can you just fix the comment?

test/lib/part_efi.c static int lib_test_gpt_blksz(struct unit_test_state *uts) · line 117

Quoted 6 lines
test/lib/part_efi.c +4 -0
@@ -111,3 +114,144 @@ static int lib_test_gpt_blksz(struct unit_test_state *uts)
+             ut_assertok(part_get_info(desc, 1, &info));
+             ut_asserteq_64(parts[0].size, info.size);
+             ut_assertok(part_get_info(desc, 2, &info));
+             ut_asserteq_64(parts[1].size, info.size);

Patch 2 fixes print_efiname(), but nothing here checks it. gpt_verify_partitions() goes through gpt_convert_efi_name_to_char() instead, so the name returned by part_get_info() is unchecked on big-endian.

Please can you add a ut_asserteq_str() on info.name for each partition? Checking info.start against the expected first_usable_lba would be worthwhile too, since the start is not passed in and so gpt_verify_partitions() skips that check.

Regards,
Simon

#9 lore raw

PATCH v2 5/7 configs: malta64: Enable EFI_PARTITION and BLKMAP for big-endian tests

In reply to Alexey Charkov

disk/part_efi.c has no big-endian coverage in CI, which is how its little-endian assumptions went unnoticed. The GPT tests in test/py/tests/test_gpt.py are restricted to sandbox because they rely on 'host bind', and test/dm/part.c is sandbox-only because UT_DM depends on SANDBOX.

The two tests in test/lib/part_efi.c need neither. One works on a synthetic descriptor and the other on a memory-backed blkmap device, and test/lib/ is built for every board that enables CONFIG_UNIT_TEST. malta64 already sets that and already runs the full pytest suite in CI as the qemu_malta64 job, so enabling EFI_PARTITION and BLKMAP is enough to have both tests built and executed on a big-endian target. The subtests are collected from u-boot.sym automatically, so CI needs no change.

Pick malta64 rather than malta because the width matters. hdr_start and pte_start in gpt_fill_pte() are size_t, so on a 32-bit big-endian target an unconverted __le64 truncates to zero and the partition overlap check still happens to reject an overlap. On MIPS64 the same value stays large, the check accepts a partition that overlaps the entry array, and the test notices.

---
 configs/malta64_defconfig | 2 ++
 1 file changed, 2 insertions(+)
configs/malta64_defconfig +2 -0
index e927be3b38ec..9a5bbe15da92 100644
@@ -26,7 +26,9 @@ CONFIG_CMD_PCI=y
 CONFIG_CMD_DHCP=y
 CONFIG_CMD_PING=y
 # CONFIG_ISO_PARTITION is not set
+CONFIG_EFI_PARTITION=y
 CONFIG_ENV_IS_IN_FLASH=y
+CONFIG_BLKMAP=y
 CONFIG_SYS_IDE_MAXBUS=1
 CONFIG_SYS_ATA_DATA_OFFSET=0
 CONFIG_SYS_ATA_REG_OFFSET=0
Signature · 1 line
2.55.0
Reviewed-by on v2 5/7
#10 lore raw

Re: [PATCH v2 5/7] configs: malta64: Enable EFI_PARTITION and BLKMAP for big-endian tests

Quoted 23 lines · Alexey Charkov

configs: malta64: Enable EFI_PARTITION and BLKMAP for big-endian tests

disk/part_efi.c has no big-endian coverage in CI, which is how its little-endian assumptions went unnoticed. The GPT tests in test/py/tests/test_gpt.py are restricted to sandbox because they rely on 'host bind', and test/dm/part.c is sandbox-only because UT_DM depends on SANDBOX.

The two tests in test/lib/part_efi.c need neither. One works on a synthetic descriptor and the other on a memory-backed blkmap device, and test/lib/ is built for every board that enables CONFIG_UNIT_TEST. malta64 already sets that and already runs the full pytest suite in CI as the qemu_malta64 job, so enabling EFI_PARTITION and BLKMAP is enough to have both tests built and executed on a big-endian target. The subtests are collected from u-boot.sym automatically, so CI needs no change.

Pick malta64 rather than malta because the width matters. hdr_start and pte_start in gpt_fill_pte() are size_t, so on a 32-bit big-endian target an unconverted __le64 truncates to zero and the partition overlap check still happens to reject an overlap. On MIPS64 the same value stays large, the check accepts a partition that overlaps the entry array, and the test notices.

Quoted 4 lines

configs/malta64_defconfig | 2 ++

 1 file changed, 2 insertions(+)
#11 lore raw

PATCH v2 6/7 test: py: gpt: Bind the disk image in test_gpt_write_part_type()

In reply to Alexey Charkov

Unlike every other test in this file, test_gpt_write_part_type() never binds the disk image it operates on. It has worked since it was added only because some test that ran before it left host 0 bound to the image this fixture provides.

That breaks as soon as a test which binds something else is added above it, and it means the test silently depends on collection order rather than on its own fixture. Bind the image like the other tests do.

Fixes 7a598e633a53 ("test/py: tests: gpt: add test_gpt_write_part_type")
---
 test/py/tests/test_gpt.py | 1 +
 1 file changed, 1 insertion(+)
test/py/tests/test_gpt.py +1 -0
index e6d8792ac1fc..fb4c8ba67d48 100644
@@ -338,6 +338,7 @@ def test_gpt_write(state_disk_image, ubman):
 def test_gpt_write_part_type(state_disk_image, ubman):
     """Test the gpt command with part type uuid."""
 
+    ubman.run_command('host bind 0 ' + state_disk_image.path)
     output = ubman.run_command('gpt write host 0 "name=part1,type=data,size=1M;name=part2,size=512K,type=system;name=part3,size=65536,type=u-boot-env;name=part4,size=65536,type=375a56f7-d6c9-4e81-b5f0-09d41ca89efe;name=part5,size=-,type=linux"')
     assert 'Writing GPT: success!' in output
     output = ubman.run_command('part list host 0')
Signature · 1 line
2.55.0
#12 lore raw

PATCH v2 7/7 test: py: gpt: Test the GPT layout on a device with 4096-byte blocks

In reply to Alexey Charkov

Bind a blank image with a 4096-byte logical block size, let U-Boot write a GPT to it, and then check the result both through 'part list' and by unpacking the primary and backup headers straight out of the image. The interesting assertion is that the backup partition entry array ends immediately before the backup header in the last block, which is what regresses when the array size is computed with a hardcoded block count.

No sgdisk is needed since U-Boot creates the table itself, so unlike the other tests here this one has no requiredtool marker. The number of entries comes from the build config rather than being hardcoded to 128, so the expected LBAs are recomputed for builds that set CONFIG_EFI_PARTITION_ENTRIES_NUMBERS differently.

Unbind the device at the end. Every test in this file binds the label '0' and none of them unbinds it, which works only because they all bind the same kind of device; this one does not, so leaving a 4096-byte device behind would change what the next test sees.

---
 test/py/tests/test_gpt.py | 119 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 119 insertions(+)
test/py/tests/test_gpt.py +119 -0
index fb4c8ba67d48..ef592f4d22a9 100644
@@ -6,6 +6,7 @@
 
 import os
 import pytest
+import struct
 import utils
 
 """
@@ -45,6 +46,28 @@ def parse_gpt_parts(disk_str):
 
     return parts
 
+# Layout of gpt_header from include/part_efi.h. It is __packed and
+# little-endian, and struct.calcsize() of this is 92, its header_size.
+GPT_HEADER_FMT = '<8sIIIIQQQQ16sQIII'
+GPT_HEADER_FIELDS = (
+    'signature', 'revision', 'header_size', 'header_crc32', 'reserved1',
+    'my_lba', 'alternate_lba', 'first_usable_lba', 'last_usable_lba',
+    'disk_guid', 'partition_entry_lba', 'num_partition_entries',
+    'sizeof_partition_entry', 'partition_entry_array_crc32')
+
+def parse_gpt_header(blob):
+    """Unpack a raw GPT header.
+
+    Args:
+        blob: Bytes starting at the first byte of the header
+
+    Returns:
+        A dict mapping each gpt_header field name to its value
+    """
+    size = struct.calcsize(GPT_HEADER_FMT)
+    return dict(zip(GPT_HEADER_FIELDS,
+                    struct.unpack(GPT_HEADER_FMT, blob[:size])))
+
 class GptTestDiskImage(object):
     """Disk Image used by the GPT tests."""
 
@@ -93,6 +116,36 @@ class GptTestDiskImage(object):
         cmd = ('cp', persistent, self.path)
         utils.run_and_log(ubman, cmd)
 
+class BlankDiskImage(object):
+    """Zero-filled disk image with no partition table on it."""
+
+    def __init__(self, ubman, size=4 * 1024 * 1024):
+        """Initialize a new BlankDiskImage object.
+
+        Args:
+            ubman: A U-Boot console.
+            size: Image size in bytes. Must be a multiple of the block size
+                the image is later bound with.
+
+        Returns:
+            Nothing.
+        """
+
+        self.size = size
+        self.path = os.path.join(ubman.config.result_dir,
+                                 'test_gpt_blank_disk_image.bin')
+        ubman.log.action('Generating ' + self.path)
+        with open(self.path, 'wb') as fd:
+            fd.truncate(size)
+
[email protected](scope='function')
+def blank_disk_image(ubman):
+    """pytest fixture to provide an empty BlankDiskImage object to tests.
+    This is function-scoped because it uses ubman, which is also
+    function-scoped."""
+
+    return BlankDiskImage(ubman)
+
 @pytest.fixture(scope='function')
 def state_disk_image(ubman):
     """pytest fixture to provide a GptTestDiskImage object to tests.
@@ -330,6 +383,72 @@ def test_gpt_write(state_disk_image, ubman):
     output = ubman.run_command('gpt guid host 0')
     assert '375a56f7-d6c9-4e81-b5f0-09d41ca89efe' in output
 
[email protected]('sandbox')
[email protected]('cmd_gpt')
[email protected]('cmd_part')
+def test_gpt_write_4k_sectors(blank_disk_image, ubman):
+    """Test the GPT layout written to a device with 4096-byte sectors.
+
+    The partition entry array takes up fewer blocks on a device with large
+    sectors, and the backup array has to end immediately before the backup
+    header in the last block whatever the block size is.
+    """
+
+    blksz = 4096
+    entry_sz = 128
+    nblocks = blank_disk_image.size // blksz
+    entries = int(ubman.config.buildconfig.get(
+        'config_efi_partition_entries_numbers', 128))
+    pte_blocks = -(-entries * entry_sz // blksz)
+
+    first_usable = 2 + pte_blocks
+    last_usable = nblocks - pte_blocks - 2
+
+    ubman.run_command(f'host bind 0 {blank_disk_image.path} {blksz}')
+
+    output = ubman.run_command('gpt write host 0 "name=all,size=0"')
+    assert 'Writing GPT: success!' in output
+    output = ubman.run_command('gpt verify host 0')
+    assert 'Verify GPT: success!' in output
+
+    output = ubman.run_command('part list host 0')
+    assert f'0x{first_usable:08x}\t0x{last_usable:08x}\t"all"' in output
+
+    with open(blank_disk_image.path, 'rb') as fd:
+        data = fd.read()
+
+    # The primary header sits in block 1 and describes the whole layout
+    prim = parse_gpt_header(data[blksz:])
+    assert prim['signature'] == b'EFI PART'
+    assert prim['my_lba'] == 1
+    assert prim['alternate_lba'] == nblocks - 1
+    assert prim['partition_entry_lba'] == 2
+    assert prim['first_usable_lba'] == first_usable
+    assert prim['last_usable_lba'] == last_usable
+    assert prim['num_partition_entries'] == entries
+    assert prim['sizeof_partition_entry'] == entry_sz
+
+    # The backup header sits in the very last block...
+    bkp = parse_gpt_header(data[(nblocks - 1) * blksz:])
+    assert bkp['signature'] == b'EFI PART'
+    assert bkp['my_lba'] == nblocks - 1
+    assert bkp['alternate_lba'] == 1
+    assert bkp['first_usable_lba'] == first_usable
+    assert bkp['last_usable_lba'] == last_usable
+
+    # ...and its entry array must end immediately before it
+    assert bkp['partition_entry_lba'] == last_usable + 1
+    assert bkp['partition_entry_lba'] + pte_blocks == nblocks - 1
+
+    # The backup array holds the same entries as the primary one
+    pte_len = entries * entry_sz
+    bkp_off = bkp['partition_entry_lba'] * blksz
+    assert data[bkp_off:bkp_off + pte_len] == data[2 * blksz:2 * blksz + pte_len]
+
+    # Unlike the other tests here this one binds a device with a non-default
+    # block size, so drop it again rather than leave it for whatever runs next
+    ubman.run_command('host unbind 0')
+
 @pytest.mark.boardspec('sandbox')
 @pytest.mark.buildconfigspec('cmd_gpt')
 @pytest.mark.buildconfigspec('cmd_part')
Signature · 1 line
2.55.0
#13 lore raw
In reply to Alexey Charkov

Hi Alexey,

Quoted 6 lines · Alexey Charkov

Patches 3 and 4 add the C tests, which are complementary rather than alternatives. Patch 3 drives gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, which is the only practical way to sweep block sizes from 512 to 32768, but it can never reach anything that touches the medium. Patch 5 backs a blkmap device with plain memory and does a full write/verify/parse round trip

The blkmap round trip is patch 4; patch 5 is the malta64 defconfig change. In the change log, the 'unbind the 4096-byte device' item is listed under patch 6 but is in patch 7, and there are two 'Patch 3' entries, so it is hard to tell which numbering (v1 or v2) each line uses. Please can you fix the numbering if there is a v3?

Quoted 4 lines

Partitions given without an explicit start= will be placed lower, though, and on sunxi first_usable_lba lands exactly on the 8 KiB SPL offset, so sunxi and Rockchip folks may want to look at patch 1 specifically (none of the devices I have override the default).

It would be worth copying those maintainers.

Just to check, has this been tried on a sunxi or Rockchip board where the first partition has no explicit start= ? If that case can overwrite the SPL, I wonder whether the series should deal with it, e.g. by having those boards set CONFIG_EFI_PARTITION_ENTRIES_OFF, or at least mention the change in the documentation, rather than leaving it as a note in the commit message. What do you think?

Quoted 2 lines

Patch 5 enables EFI_PARTITION and BLKMAP on malta64 so both tests are actually built and run on a big-endian target.

The blkmap can only be created with 512-byte blocks, so the round-trip test in patch 4 has a single case and the 4096-byte write/read path is only covered on sandbox, by the python test in patch 7. So the full write/verify/parse path at that block size has no big-endian coverage. That is fine for this series, but please can you list it in the 'Still not covered' section?

BTW the discussion with Heinrich on patch 2 about converting names with the charset functions is still open. If the outcome is to leave the lossy conversion as is due to SPL size (I tend to agree), please can you mention that in the cover letter as a known limitation?

Regards,
Simon

#14 lore raw

Hi Simon,

Thank you for your review!

Quoted 12 lines · Simon Glass

Hi Alexey,

Quoted 6 lines · Alexey Charkov

Patches 3 and 4 add the C tests, which are complementary rather than alternatives. Patch 3 drives gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, which is the only practical way to sweep block sizes from 512 to 32768, but it can never reach anything that touches the medium. Patch 5 backs a blkmap device with plain memory and does a full write/verify/parse round trip

Quoted 5 lines

The blkmap round trip is patch 4; patch 5 is the malta64 defconfig change. In the change log, the 'unbind the 4096-byte device' item is listed under patch 6 but is in patch 7, and there are two 'Patch 3' entries, so it is hard to tell which numbering (v1 or v2) each line uses. Please can you fix the numbering if there is a v3?

Yes, will fix. Deleting a patch between versions is messy in this regard :)

Quoted 6 lines
Quoted 4 lines

Partitions given without an explicit start= will be placed lower, though, and on sunxi first_usable_lba lands exactly on the 8 KiB SPL offset, so sunxi and Rockchip folks may want to look at patch 1 specifically (none of the devices I have override the default).

It would be worth copying those maintainers.

Ack.

Quoted 6 lines

Just to check, has this been tried on a sunxi or Rockchip board where the first partition has no explicit start= ? If that case can overwrite the SPL, I wonder whether the series should deal with it, e.g. by having those boards set CONFIG_EFI_PARTITION_ENTRIES_OFF, or at least mention the change in the documentation, rather than leaving it as a note in the commit message. What do you think?

I've rechecked, and all of those boards that set $partitions also have a fixed start=, so no existing users should really be affected after all. Without $partitions any gpt write would fail anyway, as seems to be the case on Khadas Edge2 (hinting that it was likely never tested in the first place).

Quoted 9 lines
Quoted 2 lines

Patch 5 enables EFI_PARTITION and BLKMAP on malta64 so both tests are actually built and run on a big-endian target.

The blkmap can only be created with 512-byte blocks, so the round-trip test in patch 4 has a single case and the 4096-byte write/read path is only covered on sandbox, by the python test in patch 7. So the full write/verify/parse path at that block size has no big-endian coverage. That is fine for this series, but please can you list it in the 'Still not covered' section?

Yes, full big-endian coverage is quite involved - will mention this in the cover letter on v3.

Quoted 4 lines

BTW the discussion with Heinrich on patch 2 about converting names with the charset functions is still open. If the outcome is to leave the lossy conversion as is due to SPL size (I tend to agree), please can you mention that in the cover letter as a known limitation?

Will do, thanks.

Best regards,
Alexey