Skip to contentSkip to conversation

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

PATCH Superseded Alexey Charkov 6 participants 41 messages Jul 31 – Aug 27

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

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 is an unrelated big-endian correctness fix in the same file, noticed while auditing it: a few header fields are read without converting from little-endian, and one already-converted value is swapped a second time.

Patch 3 is another unrelated bug that has to be fixed before any of this can be tested: part_test_mac() reads one block into a 512-byte on-stack buffer, so it corrupts the stack on any device with larger blocks. Since it runs during partition probing on every device, sandbox crashes on any access at all to a device bound with a 4096-byte block size.

Patches 4 and 6 add the tests. The C test sweeps block sizes from 512 to 32768 against gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, and the Python test writes a real GPT to a host device with 4096-byte blocks and checks the resulting on-disk headers. Both fail without patch 1.

Patch 5 is a prerequisite for patch 6: 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.

Tested by building sandbox (default, flattree, sandbox64, gcc and clang), generic-rk3576 (gcc and clang), sonoff-ihost-rv1126 and A20-OLinuXino_MICRO-eMMC on armv7, and boston32r2 and boston64r2 for MIPS32/MIPS64 big-endian, which is what patch 2 is there for.

---
Alexey Charkov (6):
disk: part_efi: Size the partition entry array from the block size
disk: part_efi: Add missing endianness conversions
disk: part_mac: Fix stack corruption on devices with large blocks
test: dm: part: Check the GPT layout for large sector sizes
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

 disk/part_efi.c           |  55 +++++++++++++++-------
 disk/part_mac.c           |  12 ++---
 test/dm/part.c            | 100 +++++++++++++++++++++++++++++++++++++++
 test/py/tests/test_gpt.py | 116 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 261 insertions(+), 22 deletions(-)

---
base-commit: 100e12ea78c73071b9710f08b32fd4590019266f
change-id: 20260731-gpt-4k-f8b9e3fad474

Best regards,

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

PATCH 1/6 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 assumes 512-byte sectors and the default number of partition entries.

The partition entry array holds GPT_ENTRY_NUMBERS entries of 128 bytes each, so the number of blocks it needs depends on both the entry count and the block size. write_gpt_table() derives that count correctly and writes the backup array at last_usable_lba + 1, so whenever the two disagree 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 128 entries, 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 d8b17ec2e91a..af311867a285 100644
@@ -388,10 +388,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);
@@ -453,9 +466,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 */
@@ -482,7 +493,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 */
@@ -604,18 +617,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;
 
@@ -747,8 +771,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.54.0
Acked-by on v1 1/6
#2 lore raw

Re: [PATCH 1/6] disk: part_efi: Size the partition entry array from the block size

Quoted 44 lines · Alexey Charkov

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

The partition entry array holds GPT_ENTRY_NUMBERS entries of 128 bytes each, so the number of blocks it needs depends on both the entry count and the block size. write_gpt_table() derives that count correctly and writes the backup array at last_usable_lba + 1, so whenever the two disagree 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 128 entries, 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.

Quoted 7 lines
---
 disk/part_efi.c | 47 +++++++++++++++++++++++++++++++++++------------
 1 file changed, 35 insertions(+), 12 deletions(-)

LGTM, but I'd like people that have been involved to take a closer look

Quoted 100 lines
disk/part_efi.c +35 -13
index d8b17ec2e91a..af311867a285 100644
@@ -388,10 +388,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);
@@ -453,9 +466,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 */
@@ -482,7 +493,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 */
@@ -604,18 +617,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;
 
@@ -747,8 +771,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;
 
 
--

2.54.0

Reviewed-by on v1 1/6
#3 lore raw

Re: [PATCH 1/6] disk: part_efi: Size the partition entry array from the block size

In reply to Alexey Charkov
Quoted 45 lines · Alexey Charkov

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 assumes 512-byte sectors and the default number of partition entries.

The partition entry array holds GPT_ENTRY_NUMBERS entries of 128 bytes each, so the number of blocks it needs depends on both the entry count and the block size. write_gpt_table() derives that count correctly and writes the backup array at last_usable_lba + 1, so whenever the two disagree 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 128 entries, 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.

Quoted 6 lines

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

 1 file changed, 35 insertions(+), 12 deletions(-)
#4 lore raw

Re: [PATCH 1/6] disk: part_efi: Size the partition entry array from the block size

In reply to Alexey Charkov
Quoted 2 lines · Alexey Charkov

gpt_fill_header() computes last_usable_lba and first_usable_lba from hardcoded block counts that silently assumes 512-byte sectors and the

Hello Alexey,

Thank you for fixing this issue.

Nits:

%s/assumes/assume/

Quoted 3 lines

default number of partition entries.

Quoted 1 line

The partition entry array holds GPT_ENTRY_NUMBERS entries of 128 bytes

each, so the number of blocks it needs depends on both the entry count

The size of the partition table entries is not fixed to 128 bytes. Instead it is 128 * 2 ** n with n >= 0. The size is stored in field SizeOfPartitionEntry of the partition table header.

You already consider this value in gpt_pte_blocks(). It is just the commit message that is misleading.

Quoted 3 lines

and the block size. write_gpt_table() derives that count correctly and writes the backup array at last_usable_lba + 1, so whenever the two disagree the backup array no longer immediately precedes the backup GPT

It remains unclear which two values might "disagree".

Otherwise the patch looks good to me.

Best regards

Heinrich

Quoted 137 lines

header. Furthermore, on a device with 4096-byte native sectors, such as UFS flash, and the default 128 entries, 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.

Quoted 1 line

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 d8b17ec2e91a..af311867a285 100644
@@ -388,10 +388,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);
@@ -453,9 +466,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 */
@@ -482,7 +493,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 */
@@ -604,18 +617,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;
 
@@ -747,8 +771,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;
 
#5 lore raw

Re: [PATCH 1/6] disk: part_efi: Size the partition entry array from the block size

Hello Heinrich,

Quoted 5 lines · Heinrich Schuchardt
Quoted 2 lines · Alexey Charkov

gpt_fill_header() computes last_usable_lba and first_usable_lba from hardcoded block counts that silently assumes 512-byte sectors and the

Quoted 7 lines

Hello Alexey,

Thank you for fixing this issue.

Nits:

%s/assumes/assume/

Ack

Quoted 10 lines
Quoted 3 lines

default number of partition entries.

Quoted 1 line

The partition entry array holds GPT_ENTRY_NUMBERS entries of 128 bytes

each, so the number of blocks it needs depends on both the entry count

The size of the partition table entries is not fixed to 128 bytes. Instead it is 128 * 2 ** n with n >= 0. The size is stored in field SizeOfPartitionEntry of the partition table header.

You already consider this value in gpt_pte_blocks(). It is just the commit message that is misleading.

Ack

Quoted 5 lines
Quoted 3 lines

and the block size. write_gpt_table() derives that count correctly and writes the backup array at last_usable_lba + 1, so whenever the two disagree the backup array no longer immediately precedes the backup GPT

It remains unclear which two values might "disagree".

Will reword in v2, thank you for looking into this!

Best regards,
Alexey

#6 lore raw

PATCH 2/6 disk: part_efi: Add missing endianness conversions

In reply to Alexey Charkov

Several GPT header fields are read without converting 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 the conversion rather than adding one.

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

---
 disk/part_efi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
disk/part_efi.c +4 -4
index af311867a285..062389c3af0c 100644
@@ -462,10 +462,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++) {
@@ -851,7 +851,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;
 		}
@@ -877,7 +877,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.54.0
Reviewed-by on v1 2/6
#7 lore raw

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

Quoted 3 lines · Alexey Charkov

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

Probably because we got no BE architecture running EFI.

Quoted 10 lines

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.

Quoted 7 lines

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 the conversion rather than adding one.

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

In any case it;'s good to have

Quoted 43 lines
---
 disk/part_efi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
disk/part_efi.c +4 -5
index af311867a285..062389c3af0c 100644
@@ -462,10 +462,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++) {
@@ -851,7 +851,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;
                }
@@ -877,7 +877,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;
 
--

2.54.0

#8 lore raw

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

Quoted 7 lines · Ilias Apalodimas
Quoted 3 lines · Alexey Charkov

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

Probably because we got no BE architecture running EFI.

Isn't the EFI spec explicitly LE?

Quoted 63 lines
Quoted 9 lines

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.

Quoted 7 lines

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 the conversion rather than adding one.

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

In any case it;'s good to have

Quoted 43 lines
---
 disk/part_efi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
disk/part_efi.c +4 -5
index af311867a285..062389c3af0c 100644
@@ -462,10 +462,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++) {
@@ -851,7 +851,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;
                }
@@ -877,7 +877,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;
 
--

2.54.0

#9 lore raw

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

Quoted 4 lines · Peter Robinson
Quoted 1 line · Ilias Apalodimas
Quoted 8 lines
Quoted 6 lines · Alexey Charkov
Quoted 3 lines

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

Probably because we got no BE architecture running EFI.

Isn't the EFI spec explicitly LE?

Ah yes, I forgot that part.
Alexey, you can drop that patch in v2

Cheers
/Ilias

Quoted 64 lines
Quoted 64 lines
Quoted 10 lines

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.

Quoted 7 lines

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 the conversion rather than adding one.

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

In any case it;'s good to have

Quoted 43 lines
---
 disk/part_efi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
disk/part_efi.c +4 -5
index af311867a285..062389c3af0c 100644
@@ -462,10 +462,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++) {
@@ -851,7 +851,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;
                }
@@ -877,7 +877,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;
 
--

2.54.0

#10 lore raw

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

Quoted 11 lines · Ilias Apalodimas
Quoted 9 lines · Peter Robinson
Quoted 6 lines · Ilias Apalodimas
Quoted 3 lines · Alexey Charkov

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

Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Probably because we got no BE architecture running EFI.

Isn't the EFI spec explicitly LE?

Ah yes, I forgot that part.
Alexey, you can drop that patch in v2

Does that mean no BE system can ever have a GUID partition table on any disks relevant to U-Boot, including removable storage? It doesn't have to boot via EFI to benefit from GPT-formatted storage, does it?

Best regards,
Alexey

#11 lore raw

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

Quoted 18 lines · Alexey Charkov
Quoted 15 lines · Ilias Apalodimas
Quoted 12 lines · Peter Robinson
Quoted 7 lines · Ilias Apalodimas
Quoted 3 lines · Alexey Charkov

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

Probably because we got no BE architecture running EFI.

Isn't the EFI spec explicitly LE?

Quoted 8 lines
Quoted 2 lines

Ah yes, I forgot that part.
Alexey, you can drop that patch in v2

Does that mean no BE system can ever have a GUID partition table on any disks relevant to U-Boot, including removable storage? It doesn't
have to boot via EFI to benefit from GPT-formatted storage, does it?

It doesn't but that's the EFI part of U-Boot we are changing here. Cheers
/Ilias

Quoted 2 lines

Best regards,
Alexey

#12 lore raw

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

Hrmm,

Quoted 23 lines · Ilias Apalodimas
Quoted 21 lines · Alexey Charkov
Quoted 17 lines · Ilias Apalodimas
Quoted 4 lines · Peter Robinson
Quoted 1 line · Ilias Apalodimas
Quoted 8 lines
Quoted 6 lines · Alexey Charkov
Quoted 3 lines

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

Probably because we got no BE architecture running EFI.

Isn't the EFI spec explicitly LE?

Ah yes, I forgot that part.
Alexey, you can drop that patch in v2

Quoted 7 lines
Quoted 5 lines

Does that mean no BE system can ever have a GUID partition table on any disks relevant to U-Boot, including removable storage? It doesn't
have to boot via EFI to benefit from GPT-formatted storage, does it?

It doesn't but that's the EFI part of U-Boot we are changing here.

Ok I was too fast on replying. You can keep this patch. It's not for the EFI loader.

Thanks
/Ilias

Quoted 4 lines

Cheers
/Ilias

Quoted 2 lines

Best regards,
Alexey

#13 lore raw

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

Quoted 34 lines · Ilias Apalodimas

Hrmm,

Quoted 29 lines · Ilias Apalodimas
Quoted 26 lines · Alexey Charkov
Quoted 11 lines · Ilias Apalodimas
Quoted 9 lines · Peter Robinson
Quoted 6 lines · Ilias Apalodimas
Quoted 3 lines · Alexey Charkov

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

Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Probably because we got no BE architecture running EFI.

Isn't the EFI spec explicitly LE?

Ah yes, I forgot that part.
Alexey, you can drop that patch in v2

Does that mean no BE system can ever have a GUID partition table on any disks relevant to U-Boot, including removable storage? It doesn't
have to boot via EFI to benefit from GPT-formatted storage, does it?

Quoted 4 lines
Quoted 1 line

It doesn't but that's the EFI part of U-Boot we are changing here.

Ok I was too fast on replying. You can keep this patch. It's not for the EFI loader.

Got it, thank you!

Best regards,
Alexey

Reviewed-by on v1 2/6
#14 lore raw

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

In reply to Alexey Charkov
Quoted 18 lines · Alexey Charkov

disk: part_efi: Add missing endianness conversions

Several GPT header fields are read without converting 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 the conversion rather than adding one.

Quoted 7 lines

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

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

 1 file changed, 4 insertions(+), 4 deletions(-)
Reviewed-by on v1 2/6
#15 lore raw

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

In reply to Alexey Charkov
Quoted 12 lines · Alexey Charkov

Several GPT header fields are read without converting 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.

Quoted 7 lines

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 the conversion rather than adding one.

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

This change is not covered by the test in patch 6/6 as it runs only on the sandbox.

Please, ensure that the GPT tests are also executed on a big-endian systems, e.g malta64_defconfig which run in the CI via QEMU.

Quoted 40 lines
---
  disk/part_efi.c | 8 ++++----
  1 file changed, 4 insertions(+), 4 deletions(-)
disk/part_efi.c +4 -4
index af311867a285..062389c3af0c 100644
@@ -462,10 +462,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++) {
@@ -851,7 +851,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;
  		}
@@ -877,7 +877,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;
#16 lore raw

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

Hello Heinrich,

Quoted 22 lines · Heinrich Schuchardt
Quoted 12 lines · Alexey Charkov

Several GPT header fields are read without converting 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.

Quoted 7 lines

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 the conversion rather than adding one.

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

Quoted 7 lines

This change is not covered by the test in patch 6/6 as it runs only on the sandbox.

Please, ensure that the GPT tests are also executed on a big-endian systems, e.g malta64_defconfig which run in the CI via QEMU.

I've added malta64 based tests in my WIP v2 version and caught more of the same :) Thanks for the suggestion!

Best regards,
Alexey

#17 lore raw

PATCH 3/6 disk: part_mac: Fix stack corruption on devices with large blocks

In reply to Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

---
 disk/part_mac.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
disk/part_mac.c +6 -6
index dd3ce0be832b..f0afab65d755 100644
@@ -37,8 +37,8 @@ static int part_mac_read_pdb(struct blk_desc *desc, int part,
  */
 static int part_test_mac(struct blk_desc *desc)
 {
-	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
 	ulong i, n;
 
 	if (part_mac_read_ddb(desc, ddesc)) {
@@ -64,8 +64,8 @@ static int part_test_mac(struct blk_desc *desc)
 static void part_print_mac(struct blk_desc *desc)
 {
 	ulong i, n;
-	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
 	ldiv_t mb, gb;
 
 	if (part_mac_read_ddb(desc, ddesc)) {
@@ -208,8 +208,8 @@ static int part_mac_read_pdb(struct blk_desc *desc, int part,
 static int part_get_info_mac(struct blk_desc *desc, int part,
 			     struct disk_partition *info)
 {
-	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
 
 	if (part_mac_read_ddb(desc, ddesc))
 		return -1;
Signature · 1 line
2.54.0
Reviewed-by on v1 3/6
#18 lore raw

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

Hi Alexey,

Quoted 11 lines · Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

        ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
        ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

It's 2560b if ISO_PARTITION is enabled, but it's still the same error

Quoted 5 lines

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

Quoted 7 lines

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

Quoted 45 lines
---
 disk/part_mac.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
disk/part_mac.c +6 -7
index dd3ce0be832b..f0afab65d755 100644
@@ -37,8 +37,8 @@ static int part_mac_read_pdb(struct blk_desc *desc, int part,
  */
 static int part_test_mac(struct blk_desc *desc)
 {
-       ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-       ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+       ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+       ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
        ulong i, n;
 
        if (part_mac_read_ddb(desc, ddesc)) {
@@ -64,8 +64,8 @@ static int part_test_mac(struct blk_desc *desc)
 static void part_print_mac(struct blk_desc *desc)
 {
        ulong i, n;
-       ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-       ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+       ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+       ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
        ldiv_t mb, gb;
 
        if (part_mac_read_ddb(desc, ddesc)) {
@@ -208,8 +208,8 @@ static int part_mac_read_pdb(struct blk_desc *desc, int part,
 static int part_get_info_mac(struct blk_desc *desc, int part,
                             struct disk_partition *info)
 {
-       ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-       ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+       ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+       ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
 
        if (part_mac_read_ddb(desc, ddesc))
                return -1;
 
--

2.54.0

Reviewed-by on v1 3/6
#19 lore raw

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

In reply to Alexey Charkov
Quoted 20 lines · Alexey Charkov

disk: part_mac: Fix stack corruption on devices with large blocks

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

        ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
        ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

host bind 0 disk.img 4096
part list host 0

Quoted 8 lines

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

disk/part_mac.c | 12 ++++++------

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

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

In reply to Alexey Charkov
Quoted 15 lines · Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

Quoted 7 lines

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

Modern Apple Computers use GPT partition tables.

Gemini claims:

Because APM was functionally obsolete by the time Advanced Format (4Kn) drives emerged in the 2010s, Apple never updated the specification to establish official compatibility guidelines for native 4 KiB sectors.

If Apple has not defined how to treat 4 KiB sectors, we should not try to invent a scheme.

Apple has already deleted the documentation of this outdated partition table format (http://developer.apple.com/techpubs/mac/Devices/Devices-126.html)

My preference would be to remove this driver completely.

Best regards

Heinrich

Quoted 42 lines
---
  disk/part_mac.c | 12 ++++++------
  1 file changed, 6 insertions(+), 6 deletions(-)
disk/part_mac.c +6 -6
index dd3ce0be832b..f0afab65d755 100644
@@ -37,8 +37,8 @@ static int part_mac_read_pdb(struct blk_desc *desc, int part,
   */
  static int part_test_mac(struct blk_desc *desc)
  {
-	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
  	ulong i, n;
 
  	if (part_mac_read_ddb(desc, ddesc)) {
@@ -64,8 +64,8 @@ static int part_test_mac(struct blk_desc *desc)
  static void part_print_mac(struct blk_desc *desc)
  {
  	ulong i, n;
-	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
  	ldiv_t mb, gb;
 
  	if (part_mac_read_ddb(desc, ddesc)) {
@@ -208,8 +208,8 @@ static int part_mac_read_pdb(struct blk_desc *desc, int part,
  static int part_get_info_mac(struct blk_desc *desc, int part,
  			     struct disk_partition *info)
  {
-	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
-	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_driver_desc_t, ddesc, 1, desc->blksz);
+	ALLOC_CACHE_ALIGN_BUFFER_PAD(mac_partition_t, mpart, 1, desc->blksz);
 
  	if (part_mac_read_ddb(desc, ddesc))
  		return -1;
#21 lore raw

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

Quoted 32 lines · Heinrich Schuchardt
Quoted 15 lines · Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

	ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
	ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

Quoted 7 lines

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

Modern Apple Computers use GPT partition tables.

Gemini claims:

Because APM was functionally obsolete by the time Advanced Format (4Kn) drives emerged in the 2010s, Apple never updated the specification to establish official compatibility guidelines for native 4 KiB sectors.

Quoted 7 lines

If Apple has not defined how to treat 4 KiB sectors, we should not try to invent a scheme.

Apple has already deleted the documentation of this outdated partition table format (http://developer.apple.com/techpubs/mac/Devices/Devices-126.html)

My preference would be to remove this driver completely.

Yes, this is another case where we can just drop the driver and if someone *needs* this for something, likely emulated, they can bring it back.

Signature · 1 line
Tom
#22 lore raw

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

Hello Heinrich, Tom,

Quoted 37 lines · Tom Rini
Quoted 35 lines · Heinrich Schuchardt
Quoted 15 lines · Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

    ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
    ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

Quoted 7 lines

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

Modern Apple Computers use GPT partition tables.

Gemini claims:

Because APM was functionally obsolete by the time Advanced Format (4Kn) drives emerged in the 2010s, Apple never updated the specification to establish official compatibility guidelines for native 4 KiB sectors.

If Apple has not defined how to treat 4 KiB sectors, we should not try to invent a scheme.

Quoted 8 lines
Quoted 4 lines

Apple has already deleted the documentation of this outdated partition table format (http://developer.apple.com/techpubs/mac/Devices/Devices-126.html)

My preference would be to remove this driver completely.

Yes, this is another case where we can just drop the driver and if someone *needs* this for something, likely emulated, they can bring it back.

I've sent a separate patch [1] removing the driver altogether, which Heinrich has reviewed already. That one is against next though, and I believe these fixes would be great to have in main, so I'd rather keep this patch in the series for 2026.10. There will be a "change vs. remove" merge conflict when main is merged into next which will need to be resolved in favor of the removal. The upside is that tests don't keep crashing wherever a Mac partition table is probed for with a 4Kn storage device.

Does that sound fine?

[1] https://lore.kernel.org/u-boot/[email protected]/

Best regards,
Alexey

#23 lore raw

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

Quoted 58 lines · Alexey Charkov

Hello Heinrich, Tom,

Quoted 37 lines · Tom Rini
Quoted 35 lines · Heinrich Schuchardt
Quoted 15 lines · Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

     ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
     ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

Quoted 7 lines

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

Modern Apple Computers use GPT partition tables.

Gemini claims:

Because APM was functionally obsolete by the time Advanced Format (4Kn) drives emerged in the 2010s, Apple never updated the specification to establish official compatibility guidelines for native 4 KiB sectors.

If Apple has not defined how to treat 4 KiB sectors, we should not try to invent a scheme.

Quoted 8 lines
Quoted 4 lines

Apple has already deleted the documentation of this outdated partition table format (http://developer.apple.com/techpubs/mac/Devices/Devices-126.html)

My preference would be to remove this driver completely.

Yes, this is another case where we can just drop the driver and if someone *needs* this for something, likely emulated, they can bring it back.

I've sent a separate patch [1] removing the driver altogether, which Heinrich has reviewed already. That one is against next though, and I believe these fixes would be great to have in main, so I'd rather keep this patch in the series for 2026.10. There will be a "change vs. remove" merge conflict when main is merged into next which will need to be resolved in favor of the removal. The upside is that tests don't keep crashing wherever a Mac partition table is probed for with a 4Kn storage device.

Quoted 1 line

Does that sound fine?

Nobody seems to be using the MAC partition driver with 4 KiB devices.

I would rather drop this patch to make merging next after v2026.10 easier.

Maybe Tom already wants to drop the MAC partition driver in 2026.10.

Best regards

Heinrich

Quoted 5 lines

[1] https://lore.kernel.org/u-boot/[email protected]/

Best regards,
Alexey

#24 lore raw

Re: [PATCH 3/6] disk: part_mac: Fix stack corruption on devices with large blocks

Quoted 60 lines · Heinrich Schuchardt
Quoted 58 lines · Alexey Charkov

Hello Heinrich, Tom,

Quoted 37 lines · Tom Rini
Quoted 35 lines · Heinrich Schuchardt
Quoted 15 lines · Alexey Charkov

part_test_mac(), part_print_mac() and part_get_info_mac() each declare a single-block buffer sized after the descriptor struct:

     ALLOC_CACHE_ALIGN_BUFFER(mac_driver_desc_t, ddesc, 1);
     ALLOC_CACHE_ALIGN_BUFFER(mac_partition_t, mpart, 1);

Both structs are 512 bytes, but every blk_dread() below them asks for one block, which transfers desc->blksz bytes. On a device with 4096-byte logical blocks that writes 4096 bytes into a 512-byte on-stack buffer and corrupts the stack.

part_test_mac() runs on every block device during partition probing, so on sandbox with CONFIG_MAC_PARTITION=y this crashes on any access at all to a device with large blocks, for instance:

Quoted 7 lines

host bind 0 disk.img 4096
part list host 0

Pad the buffers out to the block size with ALLOC_CACHE_ALIGN_BUFFER_PAD(), which is what part_efi.c already does for its own block buffers.

Modern Apple Computers use GPT partition tables.

Gemini claims:

Because APM was functionally obsolete by the time Advanced Format (4Kn) drives emerged in the 2010s, Apple never updated the specification to establish official compatibility guidelines for native 4 KiB sectors.

If Apple has not defined how to treat 4 KiB sectors, we should not try to invent a scheme.

Quoted 8 lines
Quoted 4 lines

Apple has already deleted the documentation of this outdated partition table format (http://developer.apple.com/techpubs/mac/Devices/Devices-126.html)

My preference would be to remove this driver completely.

Yes, this is another case where we can just drop the driver and if someone *needs* this for something, likely emulated, they can bring it back.

I've sent a separate patch [1] removing the driver altogether, which Heinrich has reviewed already. That one is against next though, and I believe these fixes would be great to have in main, so I'd rather keep this patch in the series for 2026.10. There will be a "change vs. remove" merge conflict when main is merged into next which will need to be resolved in favor of the removal. The upside is that tests don't keep crashing wherever a Mac partition table is probed for with a 4Kn storage device.

Quoted 3 lines
Quoted 1 line

Does that sound fine?

Nobody seems to be using the MAC partition driver with 4 KiB devices.

Sure, but the probe runs unconditionally whenever the driver is enabled, and it crashes then even if no MAC partition label is found.

Quoted 3 lines

I would rather drop this patch to make merging next after v2026.10 easier.

Maybe Tom already wants to drop the MAC partition driver in 2026.10.

That would work too - I just thought a deletion is not appropriate for the feature-freeze period.

Best regards,
Alexey

#25 lore raw

PATCH 4/6 test: dm: part: 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.

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

test/dm/part.c:313, dm_test_part_gpt_blksz():

      entry_lba + pte_blks == first_lba: Expected 0x12 (18), got 0x22 (34)
---
 test/dm/part.c | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 100 insertions(+)
test/dm/part.c +100 -0
index ad37d7f406f4..4b48322fb807 100644
@@ -5,6 +5,8 @@
 
 #include <dm.h>
 #include <env.h>
+#include <malloc.h>
+#include <memalign.h>
 #include <mmc.h>
 #include <part.h>
 #include <part_efi.h>
@@ -248,3 +250,101 @@ static int dm_test_part_get_info_by_uuid(struct unit_test_state *uts)
 	return 0;
 }
 DM_TEST(dm_test_part_get_info_by_uuid, UTF_SCAN_PDATA | UTF_SCAN_FDT);
+
+/*
+ * Check that the GPT layout adapts to the block size of the device. Neither
+ * gpt_fill_header() nor gpt_fill_pte() does any block I/O, so a synthetic
+ * descriptor is enough here; partition_entries_offset() reads the device tree
+ * '/config' node, which is available without scanning for devices.
+ */
+static int dm_test_part_gpt_blksz(struct unit_test_state *uts)
+{
+	static const struct {
+		unsigned long blksz;
+		lbaint_t lba;
+	} cases[] = {
+		{   512, 0x2000 },	/* 4MB, the traditional 34-block layout */
+		{  1024, 0x1000 },
+		{  2048,  0x800 },
+		{  4096,  0x400 },	/* 4K native media, e.g. UFS */
+		{  8192,  0x200 },
+		{ 16384,  0x100 },	/* the array fits in a single block... */
+		{ 32768,   0x40 },	/* ...on a device smaller than 34 blocks */
+	};
+
+	char str_disk_guid[UUID_STR_LEN + 1] =
+		"8d60b397-1bb6-4d33-80ee-b1587d24c2f8";
+	struct disk_partition part;
+	struct blk_desc desc;
+	gpt_header gpt_h;
+	gpt_entry *gpt_e;
+	int i;
+
+	gpt_e = calloc(GPT_ENTRY_NUMBERS, sizeof(gpt_entry));
+	ut_assertnonnull(gpt_e);
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++) {
+		u64 entry_lba, first_lba, last_lba;
+		u32 pte_blks;
+
+		memset(&desc, '\0', sizeof(desc));
+		memset(&gpt_h, '\0', sizeof(gpt_h));
+		desc.blksz = cases[i].blksz;
+		desc.log2blksz = LOG2(desc.blksz);
+		desc.lba = cases[i].lba;
+
+		ut_assertok(gpt_fill_header(&desc, &gpt_h, str_disk_guid, 1));
+
+		/*
+		 * Size the array with BLOCK_CNT() rather than the
+		 * DIV_ROUND_UP() that gpt_pte_blocks() uses, so that this
+		 * checks the layout instead of restating the implementation.
+		 */
+		pte_blks = BLOCK_CNT(le32_to_cpu(gpt_h.num_partition_entries) *
+				     le32_to_cpu(gpt_h.sizeof_partition_entry),
+				     (&desc));
+		entry_lba = le64_to_cpu(gpt_h.partition_entry_lba);
+		first_lba = le64_to_cpu(gpt_h.first_usable_lba);
+		last_lba = le64_to_cpu(gpt_h.last_usable_lba);
+
+		ut_asserteq_64(1, le64_to_cpu(gpt_h.my_lba));
+		ut_asserteq_64(desc.lba - 1, le64_to_cpu(gpt_h.alternate_lba));
+
+		/* the primary array ends where the usable area begins */
+		ut_assert(entry_lba >= 2);
+		ut_asserteq_64(entry_lba + pte_blks, first_lba);
+		ut_assert(first_lba < last_lba);
+
+		/*
+		 * write_gpt_table() puts the backup array at
+		 * last_usable_lba + 1, so it has to end exactly where the
+		 * backup header begins
+		 */
+		ut_asserteq_64(le64_to_cpu(gpt_h.alternate_lba),
+			       last_lba + 1 + pte_blks);
+
+		/* a partition with no start and no size fills the disk */
+		memset(&part, '\0', sizeof(part));
+		disk_partition_set_uuid(&part, str_disk_guid);
+		ut_assertok(gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+		ut_asserteq_64(first_lba, le64_to_cpu(gpt_e[0].starting_lba));
+		ut_asserteq_64(last_lba, le64_to_cpu(gpt_e[0].ending_lba));
+
+		/* a partition overlapping the entry array is rejected */
+		part.start = entry_lba;
+		part.size = 1;
+		ut_asserteq(-ENOSPC,
+			    gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+
+		/* so is one running past the end of the usable area */
+		part.start = first_lba;
+		part.size = last_lba - first_lba + 2;
+		ut_asserteq(-E2BIG,
+			    gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+	}
+
+	free(gpt_e);
+
+	return 0;
+}
+DM_TEST(dm_test_part_gpt_blksz, 0);
Signature · 1 line
2.54.0
Acked-by on v1 4/6
#26 lore raw

Re: [PATCH 4/6] test: dm: part: Check the GPT layout for large sector sizes

Quoted 13 lines · 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.

Quoted 8 lines

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

test/dm/part.c:313, dm_test_part_gpt_blksz():

      entry_lba + pte_blks == first_lba: Expected 0x12 (18), got 0x22 (34)

---

Quoted 122 lines
 test/dm/part.c | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 100 insertions(+)
test/dm/part.c +100 -1
index ad37d7f406f4..4b48322fb807 100644
@@ -5,6 +5,8 @@
 
 #include <dm.h>
 #include <env.h>
+#include <malloc.h>
+#include <memalign.h>
 #include <mmc.h>
 #include <part.h>
 #include <part_efi.h>
@@ -248,3 +250,101 @@ static int dm_test_part_get_info_by_uuid(struct unit_test_state *uts)
        return 0;
 }
 DM_TEST(dm_test_part_get_info_by_uuid, UTF_SCAN_PDATA | UTF_SCAN_FDT);
+
+/*
+ * Check that the GPT layout adapts to the block size of the device. Neither
+ * gpt_fill_header() nor gpt_fill_pte() does any block I/O, so a synthetic
+ * descriptor is enough here; partition_entries_offset() reads the device tree
+ * '/config' node, which is available without scanning for devices.
+ */
+static int dm_test_part_gpt_blksz(struct unit_test_state *uts)
+{
+       static const struct {
+               unsigned long blksz;
+               lbaint_t lba;
+       } cases[] = {
+               {   512, 0x2000 },      /* 4MB, the traditional 34-block layout */
+               {  1024, 0x1000 },
+               {  2048,  0x800 },
+               {  4096,  0x400 },      /* 4K native media, e.g. UFS */
+               {  8192,  0x200 },
+               { 16384,  0x100 },      /* the array fits in a single block... */
+               { 32768,   0x40 },      /* ...on a device smaller than 34 blocks */
+       };
+
+       char str_disk_guid[UUID_STR_LEN + 1] =
+               "8d60b397-1bb6-4d33-80ee-b1587d24c2f8";
+       struct disk_partition part;
+       struct blk_desc desc;
+       gpt_header gpt_h;
+       gpt_entry *gpt_e;
+       int i;
+
+       gpt_e = calloc(GPT_ENTRY_NUMBERS, sizeof(gpt_entry));
+       ut_assertnonnull(gpt_e);
+
+       for (i = 0; i < ARRAY_SIZE(cases); i++) {
+               u64 entry_lba, first_lba, last_lba;
+               u32 pte_blks;
+
+               memset(&desc, '\0', sizeof(desc));
+               memset(&gpt_h, '\0', sizeof(gpt_h));
+               desc.blksz = cases[i].blksz;
+               desc.log2blksz = LOG2(desc.blksz);
+               desc.lba = cases[i].lba;
+
+               ut_assertok(gpt_fill_header(&desc, &gpt_h, str_disk_guid, 1));
+
+               /*
+                * Size the array with BLOCK_CNT() rather than the
+                * DIV_ROUND_UP() that gpt_pte_blocks() uses, so that this
+                * checks the layout instead of restating the implementation.
+                */
+               pte_blks = BLOCK_CNT(le32_to_cpu(gpt_h.num_partition_entries) *
+                                    le32_to_cpu(gpt_h.sizeof_partition_entry),
+                                    (&desc));
+               entry_lba = le64_to_cpu(gpt_h.partition_entry_lba);
+               first_lba = le64_to_cpu(gpt_h.first_usable_lba);
+               last_lba = le64_to_cpu(gpt_h.last_usable_lba);
+
+               ut_asserteq_64(1, le64_to_cpu(gpt_h.my_lba));
+               ut_asserteq_64(desc.lba - 1, le64_to_cpu(gpt_h.alternate_lba));
+
+               /* the primary array ends where the usable area begins */
+               ut_assert(entry_lba >= 2);
+               ut_asserteq_64(entry_lba + pte_blks, first_lba);
+               ut_assert(first_lba < last_lba);
+
+               /*
+                * write_gpt_table() puts the backup array at
+                * last_usable_lba + 1, so it has to end exactly where the
+                * backup header begins
+                */
+               ut_asserteq_64(le64_to_cpu(gpt_h.alternate_lba),
+                              last_lba + 1 + pte_blks);
+
+               /* a partition with no start and no size fills the disk */
+               memset(&part, '\0', sizeof(part));
+               disk_partition_set_uuid(&part, str_disk_guid);
+               ut_assertok(gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+               ut_asserteq_64(first_lba, le64_to_cpu(gpt_e[0].starting_lba));
+               ut_asserteq_64(last_lba, le64_to_cpu(gpt_e[0].ending_lba));
+
+               /* a partition overlapping the entry array is rejected */
+               part.start = entry_lba;
+               part.size = 1;
+               ut_asserteq(-ENOSPC,
+                           gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+
+               /* so is one running past the end of the usable area */
+               part.start = first_lba;
+               part.size = last_lba - first_lba + 2;
+               ut_asserteq(-E2BIG,
+                           gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+       }
+
+       free(gpt_e);
+
+       return 0;
+}
+DM_TEST(dm_test_part_gpt_blksz, 0);
 
--

2.54.0

Reviewed-by on v1 4/6
#27 lore raw

Re: [PATCH 4/6] test: dm: part: Check the GPT layout for large sector sizes

In reply to Alexey Charkov
Quoted 17 lines · Alexey Charkov

test: dm: part: Check the GPT layout for large sector sizes

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.

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

Quoted 8 lines

test/dm/part.c:313, dm_test_part_gpt_blksz():

      entry_lba + pte_blks == first_lba: Expected 0x12 (18), got 0x22 (34)

test/dm/part.c | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 1 file changed, 100 insertions(+)
#28 lore raw

Re: [PATCH 4/6] test: dm: part: Check the GPT layout for large sector sizes

In reply to Alexey Charkov
Quoted 12 lines · 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.

Quoted 7 lines

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

   test/dm/part.c:313, dm_test_part_gpt_blksz():
       entry_lba + pte_blks == first_lba: Expected 0x12 (18), got 0x22 (34)

Thank you for providing the new test.

test/dm/part.c is never tested in the CI on big-endian systems as it is restricted to the sandbox.

The sandbox restriction arises because test/dm/part.c relies on MMC drives emulated on the sandbox. We should instead create memory backed BLKMAP devices. Then we can run the partition table tests on QEMU and on real hardware.

For your new test I would suggest to simply move it to a new file in test/lib/ as it does not rely on the presence of block devices.

Heinrich

Quoted 120 lines
---
  test/dm/part.c | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 100 insertions(+)
test/dm/part.c +100 -0
index ad37d7f406f4..4b48322fb807 100644
@@ -5,6 +5,8 @@
 
  #include <dm.h>
  #include <env.h>
+#include <malloc.h>
+#include <memalign.h>
  #include <mmc.h>
  #include <part.h>
  #include <part_efi.h>
@@ -248,3 +250,101 @@ static int dm_test_part_get_info_by_uuid(struct unit_test_state *uts)
  	return 0;
  }
  DM_TEST(dm_test_part_get_info_by_uuid, UTF_SCAN_PDATA | UTF_SCAN_FDT);
+
+/*
+ * Check that the GPT layout adapts to the block size of the device. Neither
+ * gpt_fill_header() nor gpt_fill_pte() does any block I/O, so a synthetic
+ * descriptor is enough here; partition_entries_offset() reads the device tree
+ * '/config' node, which is available without scanning for devices.
+ */
+static int dm_test_part_gpt_blksz(struct unit_test_state *uts)
+{
+	static const struct {
+		unsigned long blksz;
+		lbaint_t lba;
+	} cases[] = {
+		{   512, 0x2000 },	/* 4MB, the traditional 34-block layout */
+		{  1024, 0x1000 },
+		{  2048,  0x800 },
+		{  4096,  0x400 },	/* 4K native media, e.g. UFS */
+		{  8192,  0x200 },
+		{ 16384,  0x100 },	/* the array fits in a single block... */
+		{ 32768,   0x40 },	/* ...on a device smaller than 34 blocks */
+	};
+
+	char str_disk_guid[UUID_STR_LEN + 1] =
+		"8d60b397-1bb6-4d33-80ee-b1587d24c2f8";
+	struct disk_partition part;
+	struct blk_desc desc;
+	gpt_header gpt_h;
+	gpt_entry *gpt_e;
+	int i;
+
+	gpt_e = calloc(GPT_ENTRY_NUMBERS, sizeof(gpt_entry));
+	ut_assertnonnull(gpt_e);
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++) {
+		u64 entry_lba, first_lba, last_lba;
+		u32 pte_blks;
+
+		memset(&desc, '\0', sizeof(desc));
+		memset(&gpt_h, '\0', sizeof(gpt_h));
+		desc.blksz = cases[i].blksz;
+		desc.log2blksz = LOG2(desc.blksz);
+		desc.lba = cases[i].lba;
+
+		ut_assertok(gpt_fill_header(&desc, &gpt_h, str_disk_guid, 1));
+
+		/*
+		 * Size the array with BLOCK_CNT() rather than the
+		 * DIV_ROUND_UP() that gpt_pte_blocks() uses, so that this
+		 * checks the layout instead of restating the implementation.
+		 */
+		pte_blks = BLOCK_CNT(le32_to_cpu(gpt_h.num_partition_entries) *
+				     le32_to_cpu(gpt_h.sizeof_partition_entry),
+				     (&desc));
+		entry_lba = le64_to_cpu(gpt_h.partition_entry_lba);
+		first_lba = le64_to_cpu(gpt_h.first_usable_lba);
+		last_lba = le64_to_cpu(gpt_h.last_usable_lba);
+
+		ut_asserteq_64(1, le64_to_cpu(gpt_h.my_lba));
+		ut_asserteq_64(desc.lba - 1, le64_to_cpu(gpt_h.alternate_lba));
+
+		/* the primary array ends where the usable area begins */
+		ut_assert(entry_lba >= 2);
+		ut_asserteq_64(entry_lba + pte_blks, first_lba);
+		ut_assert(first_lba < last_lba);
+
+		/*
+		 * write_gpt_table() puts the backup array at
+		 * last_usable_lba + 1, so it has to end exactly where the
+		 * backup header begins
+		 */
+		ut_asserteq_64(le64_to_cpu(gpt_h.alternate_lba),
+			       last_lba + 1 + pte_blks);
+
+		/* a partition with no start and no size fills the disk */
+		memset(&part, '\0', sizeof(part));
+		disk_partition_set_uuid(&part, str_disk_guid);
+		ut_assertok(gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+		ut_asserteq_64(first_lba, le64_to_cpu(gpt_e[0].starting_lba));
+		ut_asserteq_64(last_lba, le64_to_cpu(gpt_e[0].ending_lba));
+
+		/* a partition overlapping the entry array is rejected */
+		part.start = entry_lba;
+		part.size = 1;
+		ut_asserteq(-ENOSPC,
+			    gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+
+		/* so is one running past the end of the usable area */
+		part.start = first_lba;
+		part.size = last_lba - first_lba + 2;
+		ut_asserteq(-E2BIG,
+			    gpt_fill_pte(&desc, &gpt_h, gpt_e, &part, 1));
+	}
+
+	free(gpt_e);
+
+	return 0;
+}
+DM_TEST(dm_test_part_gpt_blksz, 0);
#29 lore raw

Re: [PATCH 4/6] test: dm: part: Check the GPT layout for large sector sizes

Hello Heinrich,

Quoted 27 lines · Heinrich Schuchardt
Quoted 12 lines · 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.

Quoted 7 lines

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

   test/dm/part.c:313, dm_test_part_gpt_blksz():
       entry_lba + pte_blks == first_lba: Expected 0x12 (18), got 0x22 (34)

Thank you for providing the new test.

test/dm/part.c is never tested in the CI on big-endian systems as it is restricted to the sandbox.

Quoted 7 lines

The sandbox restriction arises because test/dm/part.c relies on MMC drives emulated on the sandbox. We should instead create memory backed BLKMAP devices. Then we can run the partition table tests on QEMU and on real hardware.

For your new test I would suggest to simply move it to a new file in test/lib/ as it does not rely on the presence of block devices.

Thanks for the suggestion - I moved it in v2 and it works fine.

Regarding the other point: memory backed blkmap currently supports only 512-byte sectors. Therefore, in v2 I added a blkmap-based test in addition to the sandbox-based one (rather than replacing it), and they exercise different edge cases. The blkmap-based test runs on malta64 catching endianness bugs and validating host block reads, while the sandbox-based test exercises an externally generated spec-compliant GPT image to ensure we aren't just being tautological.

Hope this sounds good.

Best regards,
Alexey

#30 lore raw

PATCH 5/6 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.54.0
Reviewed-by on v1 5/6
#31 lore raw

Re: [PATCH 5/6] test: py: gpt: Bind the disk image in test_gpt_write_part_type()

Quoted 6 lines · 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.

Quoted 7 lines

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")

---

Quoted 19 lines
 test/py/tests/test_gpt.py | 1 +
 1 file changed, 1 insertion(+)
test/py/tests/test_gpt.py +1 -1
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')
 
--

2.54.0

Reviewed-by on v1 5/6
#32 lore raw

Re: [PATCH 5/6] test: py: gpt: Bind the disk image in test_gpt_write_part_type()

In reply to Alexey Charkov
Quoted 11 lines · Alexey Charkov

test: py: gpt: Bind the disk image in test_gpt_write_part_type()

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.

Quoted 6 lines
Fixes 7a598e633a53 ("test/py: tests: gpt: add test_gpt_write_part_type")

test/py/tests/test_gpt.py | 1 +

 1 file changed, 1 insertion(+)
#33 lore raw

Re: [PATCH 5/6] test: py: gpt: Bind the disk image in test_gpt_write_part_type()

In reply to Alexey Charkov
Quoted 20 lines · 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 +0 -0
index e6d8792ac1fc..fb4c8ba67d48 100644

test/py/tests/test_gpt.py def test_gpt_write(state_disk_image, ubman): · line 341

Quoted 4 lines
test/py/tests/test_gpt.py +1 -0
@@ -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)

The "0" in the host bind 0 command is not the device number but a label. If a prior host bind command used a different label your device "0" may not have device number 0 as assumed below.

Here is an example:

=> host bind 1 ../sandbox.img
=> host bind 0 ../sandbox.img
=> host info

dev       blocks  blksz label           path
  0       131072    512 1               ../sandbox.img
  1       131072    512 0               ../sandbox.img

Each test that uses host bind should unbind the device at the end of the test. This also applies to test_gpt_write_part_type().

For reliable testing we need a host sub-command that writes the device-number (dev_seq(dev)) for a label to a variable. We should extend the host info command for this purpose:

[PATCH 1/1] cmd/host: allow to retrieve sequence number for label
https://lists.u-boot-project.org/pipermail/u-boot/2026-August/629880.html

Best regards

Heinrich

Quoted 4 lines
test/py/tests/test_gpt.py +0 -0
      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')
#34 lore raw

Re: [PATCH 5/6] test: py: gpt: Bind the disk image in test_gpt_write_part_type()

Quoted 31 lines · Heinrich Schuchardt
Quoted 20 lines · 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 +0 -0
index e6d8792ac1fc..fb4c8ba67d48 100644

test/py/tests/test_gpt.py def test_gpt_write(state_disk_image, ubman): · line 341

Quoted 4 lines
test/py/tests/test_gpt.py +1 -0
@@ -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)

The "0" in the host bind 0 command is not the device number but a label. If a prior host bind command used a different label your device "0" may not have device number 0 as assumed below.

Quoted 8 lines

Here is an example:

=> host bind 1 ../sandbox.img
=> host bind 0 ../sandbox.img
=> host info
dev blocks blksz label path

   0       131072    512 1               ../sandbox.img
   1       131072    512 0               ../sandbox.img

Wow, that's very intuitive indeed :-D

Quoted 2 lines

Each test that uses host bind should unbind the device at the end of the test. This also applies to test_gpt_write_part_type().

Added an unbind in my newly introduced test in v2. Shall I produce a separate patch to add unbind in the other tests here? Or wait for your patch to get merged, so that the tests can be converted to take the device number from a variable instead of hardcoding 0?

Quoted 6 lines

For reliable testing we need a host sub-command that writes the device-number (dev_seq(dev)) for a label to a variable. We should extend the host info command for this purpose:

[PATCH 1/1] cmd/host: allow to retrieve sequence number for label
https://lists.u-boot-project.org/pipermail/u-boot/2026-August/629880.html

Best regards,
Alexey

#35 lore raw

PATCH 6/6 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.

---
 test/py/tests/test_gpt.py | 115 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 115 insertions(+)
test/py/tests/test_gpt.py +115 -0
index fb4c8ba67d48..823fa40a9295 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,68 @@ 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]
+
 @pytest.mark.boardspec('sandbox')
 @pytest.mark.buildconfigspec('cmd_gpt')
 @pytest.mark.buildconfigspec('cmd_part')
Signature · 1 line
2.54.0
Reviewed-by on v1 6/6
#36 lore raw

Re: [PATCH 6/6] test: py: gpt: Test the GPT layout on a device with 4096-byte blocks

Quoted 15 lines · Alexey Charkov

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

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.

Quoted 4 lines

test/py/tests/test_gpt.py | 115 ++++++++++++++++++++++++++++++++++++++++++++++

 1 file changed, 115 insertions(+)
#37 lore raw

Re: [PATCH 6/6] test: py: gpt: Test the GPT layout on a device with 4096-byte blocks

In reply to Alexey Charkov
Quoted 7 lines · 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.

Quoted 7 lines

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.

Currently this test only runs on the sandbox.

Please, ensure that the test is also run on a big-endian systems in our CI as you are adding patches for big-endian support.

Best regards

Heinrich

Quoted 152 lines
---
  test/py/tests/test_gpt.py | 115 ++++++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 115 insertions(+)
test/py/tests/test_gpt.py +115 -0
index fb4c8ba67d48..823fa40a9295 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,68 @@ 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]
+
  @pytest.mark.boardspec('sandbox')
  @pytest.mark.buildconfigspec('cmd_gpt')
  @pytest.mark.buildconfigspec('cmd_part')
#38 lore raw
In reply to Alexey Charkov
Quoted 67 lines · Alexey Charkov

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 is an unrelated big-endian correctness fix in the same file, noticed while auditing it: a few header fields are read without converting from little-endian, and one already-converted value is swapped a second time.

Patch 3 is another unrelated bug that has to be fixed before any of this can be tested: part_test_mac() reads one block into a 512-byte on-stack buffer, so it corrupts the stack on any device with larger blocks. Since it runs during partition probing on every device, sandbox crashes on any access at all to a device bound with a 4096-byte block size.

Patches 4 and 6 add the tests. The C test sweeps block sizes from 512 to 32768 against gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, and the Python test writes a real GPT to a host device with 4096-byte blocks and checks the resulting on-disk headers. Both fail without patch 1.

Patch 5 is a prerequisite for patch 6: 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.

Tested by building sandbox (default, flattree, sandbox64, gcc and clang), generic-rk3576 (gcc and clang), sonoff-ihost-rv1126 and A20-OLinuXino_MICRO-eMMC on armv7, and boston32r2 and boston64r2 for MIPS32/MIPS64 big-endian, which is what patch 2 is there for.

---
Alexey Charkov (6):
disk: part_efi: Size the partition entry array from the block size
disk: part_efi: Add missing endianness conversions
disk: part_mac: Fix stack corruption on devices with large blocks
test: dm: part: Check the GPT layout for large sector sizes
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

Quoted 5 lines
 disk/part_efi.c           |  55 +++++++++++++++-------
 disk/part_mac.c           |  12 ++---
 test/dm/part.c            | 100 +++++++++++++++++++++++++++++++++++++++
 test/py/tests/test_gpt.py | 116 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 261 insertions(+), 22 deletions(-)

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

Best regards,
Alexey

#39 lore raw
Quoted 69 lines · Alexey Charkov
Quoted 67 lines · Alexey Charkov

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 is an unrelated big-endian correctness fix in the same file, noticed while auditing it: a few header fields are read without converting from little-endian, and one already-converted value is swapped a second time.

Patch 3 is another unrelated bug that has to be fixed before any of this can be tested: part_test_mac() reads one block into a 512-byte on-stack buffer, so it corrupts the stack on any device with larger blocks. Since it runs during partition probing on every device, sandbox crashes on any access at all to a device bound with a 4096-byte block size.

Patches 4 and 6 add the tests. The C test sweeps block sizes from 512 to 32768 against gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, and the Python test writes a real GPT to a host device with 4096-byte blocks and checks the resulting on-disk headers. Both fail without patch 1.

Patch 5 is a prerequisite for patch 6: 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.

Tested by building sandbox (default, flattree, sandbox64, gcc and clang), generic-rk3576 (gcc and clang), sonoff-ihost-rv1126 and A20-OLinuXino_MICRO-eMMC on armv7, and boston32r2 and boston64r2 for MIPS32/MIPS64 big-endian, which is what patch 2 is there for.

---
Alexey Charkov (6):
disk: part_efi: Size the partition entry array from the block size
disk: part_efi: Add missing endianness conversions
disk: part_mac: Fix stack corruption on devices with large blocks
test: dm: part: Check the GPT layout for large sector sizes
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

Quoted 8 lines
Quoted 5 lines
 disk/part_efi.c           |  55 +++++++++++++++-------
 disk/part_mac.c           |  12 ++---
 test/dm/part.c            | 100 +++++++++++++++++++++++++++++++++++++++
 test/py/tests/test_gpt.py | 116 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 261 insertions(+), 22 deletions(-)

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

Gentle ping regarding this series. All patches got R-b, can this please be applied?

get_maintainer.pl says these fall under "THE REST" - Tom, can you please pick it up?

Thanks a lot!

Best regards,
Alexey

#40 lore raw
Quoted 76 lines · Alexey Charkov
Quoted 75 lines · Alexey Charkov
Quoted 72 lines · Alexey Charkov

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 is an unrelated big-endian correctness fix in the same file, noticed while auditing it: a few header fields are read without converting from little-endian, and one already-converted value is swapped a second time.

Patch 3 is another unrelated bug that has to be fixed before any of this can be tested: part_test_mac() reads one block into a 512-byte on-stack buffer, so it corrupts the stack on any device with larger blocks. Since it runs during partition probing on every device, sandbox crashes on any access at all to a device bound with a 4096-byte block size.

Patches 4 and 6 add the tests. The C test sweeps block sizes from 512 to 32768 against gpt_fill_header()/gpt_fill_pte() with a synthetic descriptor, and the Python test writes a real GPT to a host device with 4096-byte blocks and checks the resulting on-disk headers. Both fail without patch 1.

Patch 5 is a prerequisite for patch 6: 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.

Tested by building sandbox (default, flattree, sandbox64, gcc and clang), generic-rk3576 (gcc and clang), sonoff-ihost-rv1126 and A20-OLinuXino_MICRO-eMMC on armv7, and boston32r2 and boston64r2 for MIPS32/MIPS64 big-endian, which is what patch 2 is there for.

---
Alexey Charkov (6):
disk: part_efi: Size the partition entry array from the block size
disk: part_efi: Add missing endianness conversions
disk: part_mac: Fix stack corruption on devices with large blocks
test: dm: part: Check the GPT layout for large sector sizes
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

 disk/part_efi.c           |  55 +++++++++++++++-------
 disk/part_mac.c           |  12 ++---
 test/dm/part.c            | 100 +++++++++++++++++++++++++++++++++++++++
 test/py/tests/test_gpt.py | 116 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 261 insertions(+), 22 deletions(-)
Quoted 8 lines
Quoted 2 lines

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

Gentle ping regarding this series. All patches got R-b, can this please be applied?

get_maintainer.pl says these fall under "THE REST" - Tom, can you please pick it up?

I assigned this to Heinrich in patchwork as it's adjacent to other areas he owns and was hoping he'd be able to provide some review.

Signature · 1 line
Tom