git: 9b42d3e12ffc - main - mkimg: Ensure GPT Entry Array is at least 16k

From: Warner Losh <imp_at_FreeBSD.org>
Date: Tue, 17 Oct 2023 17:17:18 UTC
The branch main has been updated by imp:

URL: https://cgit.FreeBSD.org/src/commit/?id=9b42d3e12ffc6896fcb4e60c1b239ddf60705831

commit 9b42d3e12ffc6896fcb4e60c1b239ddf60705831
Author:     Warner Losh <imp@FreeBSD.org>
AuthorDate: 2023-10-17 17:14:14 +0000
Commit:     Warner Losh <imp@FreeBSD.org>
CommitDate: 2023-10-17 17:14:23 +0000

    mkimg: Ensure GPT Entry Array is at least 16k
    
    UEFI v2.10 Section 5.3 documentes that the minimum reserved space after
    the GPT header be at least 16kB. Enforce this minimum. Before, we'd only
    set the number of entries to be the unpadded size. gpart's selective
    enforcement of aspects of the GPT standard meant that these images would
    work, but couldn't be changed (to add a partition or grow the size of a
    partition). This ensures that gpart's overly picky standards don't cause
    problems for people wishing to, for example, resize release images.
    
    MFC after:              1 day (we want this in 14.0)
    PR:                     274312
    Sponsored by:           Netflix
    Reviewed by:            emaste
    Differential Revision:  https://reviews.freebsd.org/D42245
---
 sys/sys/disk/gpt.h  |  7 +++++++
 usr.bin/mkimg/gpt.c | 16 ++++++++++++----
 2 files changed, 19 insertions(+), 4 deletions(-)

diff --git a/sys/sys/disk/gpt.h b/sys/sys/disk/gpt.h
index e48b13684814..596a5cba1681 100644
--- a/sys/sys/disk/gpt.h
+++ b/sys/sys/disk/gpt.h
@@ -82,6 +82,13 @@ struct gpt_hdr {
 CTASSERT(offsetof(struct gpt_hdr, padding) == 92);
 #endif
 
+/*
+ * The GPT standard (section 5.3 of UEFI standard version 2.10) requires
+ * we reserve at least 16k after the PMBR and the GPT header for the GPT
+ * Array Entries.
+ */
+#define GPT_MIN_RESERVED	16384
+
 struct gpt_ent {
 	gpt_uuid_t	ent_type;
 	gpt_uuid_t	ent_uuid;
diff --git a/usr.bin/mkimg/gpt.c b/usr.bin/mkimg/gpt.c
index 59c51a6a177b..ed3f008c394f 100644
--- a/usr.bin/mkimg/gpt.c
+++ b/usr.bin/mkimg/gpt.c
@@ -24,7 +24,7 @@
  * SUCH DAMAGE.
  */
 
-#include <sys/cdefs.h>
+#include <sys/param.h>
 #include <sys/errno.h>
 #include <stddef.h>
 #include <stdint.h>
@@ -124,13 +124,21 @@ crc32(const void *buf, size_t sz)
 	return (crc ^ ~0U);
 }
 
+/*
+ * Return the number of sectors needed to store the partition table.
+ */
 static u_int
 gpt_tblsz(void)
 {
-	u_int ents;
+	u_int eps;		/* Entries per Sector */
 
-	ents = secsz / sizeof(struct gpt_ent);
-	return ((nparts + ents - 1) / ents);
+	/*
+	 * Count the number of sectors needed for the GPT Entry Array to store
+	 * the number of partitions defined for this image.  Enforce the 16kB
+	 * minimum space for the GPT Entry Array per UEFI v2.10 Section 5.3.
+	 */
+	eps = secsz / sizeof(struct gpt_ent);
+	return (MAX(howmany(GPT_MIN_RESERVED, secsz), howmany(nparts, eps)));
 }
 
 static lba_t