]> git.ipfire.org Git - thirdparty/util-linux.git/blob - libfdisk/src/gpt.c
4646043560c82a377b55950da674090fa714fafc
[thirdparty/util-linux.git] / libfdisk / src / gpt.c
1 /*
2 * Copyright (C) 2007 Karel Zak <kzak@redhat.com>
3 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
4 *
5 * GUID Partition Table (GPT) support. Based on UEFI Specs 2.3.1
6 * Chapter 5: GUID Partition Table (GPT) Disk Layout (Jun 27th, 2012).
7 * Some ideas and inspiration from GNU parted and gptfdisk.
8 */
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <inttypes.h>
13 #include <sys/stat.h>
14 #include <sys/utsname.h>
15 #include <sys/types.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <errno.h>
19 #include <ctype.h>
20 #include <uuid.h>
21
22 #include "fdiskP.h"
23
24 #include "nls.h"
25 #include "crc32.h"
26 #include "blkdev.h"
27 #include "bitops.h"
28 #include "strutils.h"
29 #include "all-io.h"
30 #include "pt-mbr.h"
31
32 /**
33 * SECTION: gpt
34 * @title: UEFI GPT
35 * @short_description: specific functionality
36 */
37
38 #define GPT_HEADER_SIGNATURE 0x5452415020494645LL /* EFI PART */
39 #define GPT_HEADER_REVISION_V1_02 0x00010200
40 #define GPT_HEADER_REVISION_V1_00 0x00010000
41 #define GPT_HEADER_REVISION_V0_99 0x00009900
42 #define GPT_HEADER_MINSZ 92 /* bytes */
43
44 #define GPT_PMBR_LBA 0
45 #define GPT_MBR_PROTECTIVE 1
46 #define GPT_MBR_HYBRID 2
47
48 #define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001ULL
49
50 #define EFI_PMBR_OSTYPE 0xEE
51 #define MSDOS_MBR_SIGNATURE 0xAA55
52 #define GPT_PART_NAME_LEN (72 / sizeof(uint16_t))
53 #define GPT_NPARTITIONS FDISK_GPT_NPARTITIONS_DEFAULT
54
55 /* Globally unique identifier */
56 struct gpt_guid {
57 uint32_t time_low;
58 uint16_t time_mid;
59 uint16_t time_hi_and_version;
60 uint8_t clock_seq_hi;
61 uint8_t clock_seq_low;
62 uint8_t node[6];
63 };
64
65
66 /* only checking that the GUID is 0 is enough to verify an empty partition. */
67 #define GPT_UNUSED_ENTRY_GUID \
68 ((struct gpt_guid) { 0x00000000, 0x0000, 0x0000, 0x00, 0x00, \
69 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }})
70
71 /* Linux native partition type */
72 #define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
73
74 /*
75 * Attribute bits
76 */
77 enum {
78 /* UEFI specific */
79 GPT_ATTRBIT_REQ = 0,
80 GPT_ATTRBIT_NOBLOCK = 1,
81 GPT_ATTRBIT_LEGACY = 2,
82
83 /* GUID specific (range 48..64)*/
84 GPT_ATTRBIT_GUID_FIRST = 48,
85 GPT_ATTRBIT_GUID_COUNT = 16
86 };
87
88 #define GPT_ATTRSTR_REQ "RequiredPartition"
89 #define GPT_ATTRSTR_REQ_TYPO "RequiredPartiton"
90 #define GPT_ATTRSTR_NOBLOCK "NoBlockIOProtocol"
91 #define GPT_ATTRSTR_LEGACY "LegacyBIOSBootable"
92
93 /* The GPT Partition entry array contains an array of GPT entries. */
94 struct gpt_entry {
95 struct gpt_guid type; /* purpose and type of the partition */
96 struct gpt_guid partition_guid;
97 uint64_t lba_start;
98 uint64_t lba_end;
99 uint64_t attrs;
100 uint16_t name[GPT_PART_NAME_LEN];
101 } __attribute__ ((packed));
102
103 /* GPT header */
104 struct gpt_header {
105 uint64_t signature; /* header identification */
106 uint32_t revision; /* header version */
107 uint32_t size; /* in bytes */
108 uint32_t crc32; /* header CRC checksum */
109 uint32_t reserved1; /* must be 0 */
110 uint64_t my_lba; /* LBA of block that contains this struct (LBA 1) */
111 uint64_t alternative_lba; /* backup GPT header */
112 uint64_t first_usable_lba; /* first usable logical block for partitions */
113 uint64_t last_usable_lba; /* last usable logical block for partitions */
114 struct gpt_guid disk_guid; /* unique disk identifier */
115 uint64_t partition_entry_lba; /* LBA of start of partition entries array */
116 uint32_t npartition_entries; /* total partition entries - normally 128 */
117 uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
118 uint32_t partition_entry_array_crc32; /* partition CRC checksum */
119 uint8_t reserved2[512 - 92]; /* must all be 0 */
120 } __attribute__ ((packed));
121
122 struct gpt_record {
123 uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
124 uint8_t start_head; /* unused by EFI, pt start in CHS */
125 uint8_t start_sector; /* unused by EFI, pt start in CHS */
126 uint8_t start_track;
127 uint8_t os_type; /* EFI and legacy non-EFI OS types */
128 uint8_t end_head; /* unused by EFI, pt end in CHS */
129 uint8_t end_sector; /* unused by EFI, pt end in CHS */
130 uint8_t end_track; /* unused by EFI, pt end in CHS */
131 uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
132 uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
133 } __attribute__ ((packed));
134
135 /* Protected MBR and legacy MBR share same structure */
136 struct gpt_legacy_mbr {
137 uint8_t boot_code[440];
138 uint32_t unique_mbr_signature;
139 uint16_t unknown;
140 struct gpt_record partition_record[4];
141 uint16_t signature;
142 } __attribute__ ((packed));
143
144 /*
145 * Here be dragons!
146 * See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
147 */
148 #define DEF_GUID(_u, _n) \
149 { \
150 .typestr = (_u), \
151 .name = (_n), \
152 }
153
154 /* Probably the most complete list of the GUIDs are at:
155 * https://wikipedia.org/wiki/GUID_Partition_Table
156 */
157 static struct fdisk_parttype gpt_parttypes[] =
158 {
159 /* Generic OS */
160 DEF_GUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", N_("EFI System")),
161
162 DEF_GUID("024DEE41-33E7-11D3-9D69-0008C781F39F", N_("MBR partition scheme")),
163 DEF_GUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593", N_("Intel Fast Flash")),
164
165 /* Hah!IdontneedEFI */
166 DEF_GUID("21686148-6449-6E6F-744E-656564454649", N_("BIOS boot")),
167
168 /* NIH syndrome */
169 DEF_GUID("F4019732-066E-4E12-8273-346C5641494F", N_("Sony boot partition")),
170 DEF_GUID("BFBFAFE7-A34F-448A-9A5B-6213EB736C22", N_("Lenovo boot partition")),
171
172 /* PowerPC reference platform boot partition */
173 DEF_GUID("9E1A2D38-C612-4316-AA26-8B49521E5A8B", N_("PowerPC PReP boot")),
174
175 /* Open Network Install Environment */
176 DEF_GUID("7412F7D5-A156-4B13-81DC-867174929325", N_("ONIE boot")),
177 DEF_GUID("D4E6E2CD-4469-46F3-B5CB-1BFF57AFC149", N_("ONIE config")),
178
179 /* Windows */
180 DEF_GUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE", N_("Microsoft reserved")),
181 DEF_GUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", N_("Microsoft basic data")),
182 DEF_GUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3", N_("Microsoft LDM metadata")),
183 DEF_GUID("AF9B60A0-1431-4F62-BC68-3311714A69AD", N_("Microsoft LDM data")),
184 DEF_GUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC", N_("Windows recovery environment")),
185 DEF_GUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174", N_("IBM General Parallel Fs")),
186 DEF_GUID("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D", N_("Microsoft Storage Spaces")),
187
188 /* HP-UX */
189 DEF_GUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000", N_("HP-UX data")),
190 DEF_GUID("E2A1E728-32E3-11D6-A682-7B03A0000000", N_("HP-UX service")),
191
192 /* Linux (http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec) */
193 DEF_GUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", N_("Linux swap")),
194 DEF_GUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4", N_("Linux filesystem")),
195 DEF_GUID("3B8F8425-20E0-4F3B-907F-1A25A76F98E8", N_("Linux server data")),
196 DEF_GUID("44479540-F297-41B2-9AF7-D131D5F0458A", N_("Linux root (x86)")),
197 DEF_GUID("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3", N_("Linux root (ARM)")),
198 DEF_GUID("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709", N_("Linux root (x86-64)")),
199 DEF_GUID("B921B045-1DF0-41C3-AF44-4C6F280D3FAE", N_("Linux root (ARM-64)")),
200 DEF_GUID("993D8D3D-F80E-4225-855A-9DAF8ED7EA97", N_("Linux root (IA-64)")),
201 DEF_GUID("8DA63339-0007-60C0-C436-083AC8230908", N_("Linux reserved")),
202 DEF_GUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915", N_("Linux home")),
203 DEF_GUID("A19D880F-05FC-4D3B-A006-743F0F84911E", N_("Linux RAID")),
204 DEF_GUID("BC13C2FF-59E6-4262-A352-B275FD6F7172", N_("Linux extended boot")),
205 DEF_GUID("E6D6D379-F507-44C2-A23C-238F2A3DF928", N_("Linux LVM")),
206 /* ... too crazy, ignore for now:
207 DEF_GUID("7FFEC5C9-2D00-49B7-8941-3EA10A5586B7", N_("Linux plain dm-crypt")),
208 DEF_GUID("CA7D7CCB-63ED-4C53-861C-1742536059CC", N_("Linux LUKS")),
209 */
210
211 /* FreeBSD */
212 DEF_GUID("516E7CB4-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD data")),
213 DEF_GUID("83BD6B9D-7F41-11DC-BE0B-001560B84F0F", N_("FreeBSD boot")),
214 DEF_GUID("516E7CB5-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD swap")),
215 DEF_GUID("516E7CB6-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD UFS")),
216 DEF_GUID("516E7CBA-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD ZFS")),
217 DEF_GUID("516E7CB8-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD Vinum")),
218
219 /* Apple OSX */
220 DEF_GUID("48465300-0000-11AA-AA11-00306543ECAC", N_("Apple HFS/HFS+")),
221 DEF_GUID("55465300-0000-11AA-AA11-00306543ECAC", N_("Apple UFS")),
222 DEF_GUID("52414944-0000-11AA-AA11-00306543ECAC", N_("Apple RAID")),
223 DEF_GUID("52414944-5F4F-11AA-AA11-00306543ECAC", N_("Apple RAID offline")),
224 DEF_GUID("426F6F74-0000-11AA-AA11-00306543ECAC", N_("Apple boot")),
225 DEF_GUID("4C616265-6C00-11AA-AA11-00306543ECAC", N_("Apple label")),
226 DEF_GUID("5265636F-7665-11AA-AA11-00306543ECAC", N_("Apple TV recovery")),
227 DEF_GUID("53746F72-6167-11AA-AA11-00306543ECAC", N_("Apple Core storage")),
228
229 /* Solaris */
230 DEF_GUID("6A82CB45-1DD2-11B2-99A6-080020736631", N_("Solaris boot")),
231 DEF_GUID("6A85CF4D-1DD2-11B2-99A6-080020736631", N_("Solaris root")),
232 /* same as Apple ZFS */
233 DEF_GUID("6A898CC3-1DD2-11B2-99A6-080020736631", N_("Solaris /usr & Apple ZFS")),
234 DEF_GUID("6A87C46F-1DD2-11B2-99A6-080020736631", N_("Solaris swap")),
235 DEF_GUID("6A8B642B-1DD2-11B2-99A6-080020736631", N_("Solaris backup")),
236 DEF_GUID("6A8EF2E9-1DD2-11B2-99A6-080020736631", N_("Solaris /var")),
237 DEF_GUID("6A90BA39-1DD2-11B2-99A6-080020736631", N_("Solaris /home")),
238 DEF_GUID("6A9283A5-1DD2-11B2-99A6-080020736631", N_("Solaris alternate sector")),
239 DEF_GUID("6A945A3B-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 1")),
240 DEF_GUID("6A9630D1-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 2")),
241 DEF_GUID("6A980767-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 3")),
242 DEF_GUID("6A96237F-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 4")),
243 DEF_GUID("6A8D2AC7-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 5")),
244
245 /* NetBSD */
246 DEF_GUID("49F48D32-B10E-11DC-B99B-0019D1879648", N_("NetBSD swap")),
247 DEF_GUID("49F48D5A-B10E-11DC-B99B-0019D1879648", N_("NetBSD FFS")),
248 DEF_GUID("49F48D82-B10E-11DC-B99B-0019D1879648", N_("NetBSD LFS")),
249 DEF_GUID("2DB519C4-B10E-11DC-B99B-0019D1879648", N_("NetBSD concatenated")),
250 DEF_GUID("2DB519EC-B10E-11DC-B99B-0019D1879648", N_("NetBSD encrypted")),
251 DEF_GUID("49F48DAA-B10E-11DC-B99B-0019D1879648", N_("NetBSD RAID")),
252
253 /* ChromeOS */
254 DEF_GUID("FE3A2A5D-4F32-41A7-B725-ACCC3285A309", N_("ChromeOS kernel")),
255 DEF_GUID("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC", N_("ChromeOS root fs")),
256 DEF_GUID("2E0A753D-9E48-43B0-8337-B15192CB1B5E", N_("ChromeOS reserved")),
257
258 /* MidnightBSD */
259 DEF_GUID("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD data")),
260 DEF_GUID("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD boot")),
261 DEF_GUID("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD swap")),
262 DEF_GUID("0394EF8B-237E-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD UFS")),
263 DEF_GUID("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD ZFS")),
264 DEF_GUID("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD Vinum")),
265
266 /* Ceph */
267 DEF_GUID("45B0969E-9B03-4F30-B4C6-B4B80CEFF106", N_("Ceph Journal")),
268 DEF_GUID("45B0969E-9B03-4F30-B4C6-5EC00CEFF106", N_("Ceph Encrypted Journal")),
269 DEF_GUID("4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D", N_("Ceph OSD")),
270 DEF_GUID("4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D", N_("Ceph crypt OSD")),
271 DEF_GUID("89C57F98-2FE5-4DC0-89C1-F3AD0CEFF2BE", N_("Ceph disk in creation")),
272 DEF_GUID("89C57F98-2FE5-4DC0-89C1-5EC00CEFF2BE", N_("Ceph crypt disk in creation")),
273
274 /* OpenBSD */
275 DEF_GUID("824CC7A0-36A8-11E3-890A-952519AD3F61", N_("OpenBSD data")),
276
277 /* QNX */
278 DEF_GUID("CEF5A9AD-73BC-4601-89F3-CDEEEEE321A1", N_("QNX6 file system")),
279
280 /* Plan 9 */
281 DEF_GUID("C91818F9-8025-47AF-89D2-F030D7000C2C", N_("Plan 9 partition"))
282 };
283
284 /* gpt_entry macros */
285 #define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
286 #define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
287
288 /*
289 * in-memory fdisk GPT stuff
290 */
291 struct fdisk_gpt_label {
292 struct fdisk_label head; /* generic part */
293
294 /* gpt specific part */
295 struct gpt_header *pheader; /* primary header */
296 struct gpt_header *bheader; /* backup header */
297 struct gpt_entry *ents; /* entries (partitions) */
298 };
299
300 static void gpt_deinit(struct fdisk_label *lb);
301
302 static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
303 {
304 return (struct fdisk_gpt_label *) cxt->label;
305 }
306
307 /*
308 * Returns the partition length, or 0 if end is before beginning.
309 */
310 static uint64_t gpt_partition_size(const struct gpt_entry *e)
311 {
312 uint64_t start = gpt_partition_start(e);
313 uint64_t end = gpt_partition_end(e);
314
315 return start > end ? 0 : end - start + 1ULL;
316 }
317
318 /* prints UUID in the real byte order! */
319 static void gpt_debug_uuid(const char *mesg, struct gpt_guid *guid)
320 {
321 const unsigned char *uuid = (unsigned char *) guid;
322
323 fprintf(stderr, "%s: "
324 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
325 mesg,
326 uuid[0], uuid[1], uuid[2], uuid[3],
327 uuid[4], uuid[5],
328 uuid[6], uuid[7],
329 uuid[8], uuid[9],
330 uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
331 }
332
333 /*
334 * UUID is traditionally 16 byte big-endian array, except Intel EFI
335 * specification where the UUID is a structure of little-endian fields.
336 */
337 static void swap_efi_guid(struct gpt_guid *uid)
338 {
339 uid->time_low = swab32(uid->time_low);
340 uid->time_mid = swab16(uid->time_mid);
341 uid->time_hi_and_version = swab16(uid->time_hi_and_version);
342 }
343
344 static int string_to_guid(const char *in, struct gpt_guid *guid)
345 {
346 if (uuid_parse(in, (unsigned char *) guid)) { /* BE */
347 DBG(LABEL, ul_debug("GPT: failed to parse GUID: %s", in));
348 return -EINVAL;
349 }
350 swap_efi_guid(guid); /* LE */
351 return 0;
352 }
353
354 static char *guid_to_string(const struct gpt_guid *guid, char *out)
355 {
356 struct gpt_guid u = *guid; /* LE */
357
358 swap_efi_guid(&u); /* BE */
359 uuid_unparse_upper((unsigned char *) &u, out);
360
361 return out;
362 }
363
364 static struct fdisk_parttype *gpt_partition_parttype(
365 struct fdisk_context *cxt,
366 const struct gpt_entry *e)
367 {
368 struct fdisk_parttype *t;
369 char str[37];
370
371 guid_to_string(&e->type, str);
372 t = fdisk_label_get_parttype_from_string(cxt->label, str);
373 return t ? : fdisk_new_unknown_parttype(0, str);
374 }
375
376 static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
377 {
378 e->type = *uuid;
379 DBG(LABEL, gpt_debug_uuid("new type", &(e->type)));
380 }
381
382 static void gpt_entry_set_name(struct gpt_entry *e, char *str)
383 {
384 char name[GPT_PART_NAME_LEN] = { 0 };
385 size_t i, sz = strlen(str);
386
387 if (sz) {
388 if (sz > GPT_PART_NAME_LEN)
389 sz = GPT_PART_NAME_LEN;
390 memcpy(name, str, sz);
391 }
392
393 for (i = 0; i < GPT_PART_NAME_LEN; i++)
394 e->name[i] = cpu_to_le16((uint16_t) name[i]);
395 }
396
397 static int gpt_entry_set_uuid(struct gpt_entry *e, char *str)
398 {
399 struct gpt_guid uuid;
400 int rc;
401
402 rc = string_to_guid(str, &uuid);
403 if (rc)
404 return rc;
405
406 e->partition_guid = uuid;
407 return 0;
408 }
409
410
411 static const char *gpt_get_header_revstr(struct gpt_header *header)
412 {
413 if (!header)
414 goto unknown;
415
416 switch (le32_to_cpu(header->revision)) {
417 case GPT_HEADER_REVISION_V1_02:
418 return "1.2";
419 case GPT_HEADER_REVISION_V1_00:
420 return "1.0";
421 case GPT_HEADER_REVISION_V0_99:
422 return "0.99";
423 default:
424 goto unknown;
425 }
426
427 unknown:
428 return "unknown";
429 }
430
431 static inline int partition_unused(const struct gpt_entry *e)
432 {
433 return !memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
434 sizeof(struct gpt_guid));
435 }
436
437 static char *gpt_get_header_id(struct gpt_header *header)
438 {
439 char str[37];
440
441 guid_to_string(&header->disk_guid, str);
442
443 return strdup(str);
444 }
445
446
447 /*
448 * Builds a clean new valid protective MBR - will wipe out any existing data.
449 * Returns 0 on success, otherwise < 0 on error.
450 */
451 static int gpt_mknew_pmbr(struct fdisk_context *cxt)
452 {
453 struct gpt_legacy_mbr *pmbr = NULL;
454 int rc;
455
456 if (!cxt || !cxt->firstsector)
457 return -ENOSYS;
458
459 if (fdisk_has_protected_bootbits(cxt))
460 rc = fdisk_init_firstsector_buffer(cxt, 0, MBR_PT_BOOTBITS_SIZE);
461 else
462 rc = fdisk_init_firstsector_buffer(cxt, 0, 0);
463 if (rc)
464 return rc;
465
466 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
467
468 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
469 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
470 pmbr->partition_record[0].start_sector = 1;
471 pmbr->partition_record[0].end_head = 0xFE;
472 pmbr->partition_record[0].end_sector = 0xFF;
473 pmbr->partition_record[0].end_track = 0xFF;
474 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
475 pmbr->partition_record[0].size_in_lba =
476 cpu_to_le32((uint32_t) min( cxt->total_sectors - 1ULL, 0xFFFFFFFFULL) );
477
478 return 0;
479 }
480
481 /* some universal differences between the headers */
482 static void gpt_mknew_header_common(struct fdisk_context *cxt,
483 struct gpt_header *header, uint64_t lba)
484 {
485 if (!cxt || !header)
486 return;
487
488 header->my_lba = cpu_to_le64(lba);
489
490 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) { /* primary */
491 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1ULL);
492 header->partition_entry_lba = cpu_to_le64(2ULL);
493 } else { /* backup */
494 uint64_t esz = (uint64_t) le32_to_cpu(header->npartition_entries)
495 * sizeof(struct gpt_entry);
496 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
497
498 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
499 header->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1ULL - esects);
500 }
501 }
502
503 /*
504 * Builds a new GPT header (at sector lba) from a backup header2.
505 * If building a primary header, then backup is the secondary, and vice versa.
506 *
507 * Always pass a new (zeroized) header to build upon as we don't
508 * explicitly zero-set some values such as CRCs and reserved.
509 *
510 * Returns 0 on success, otherwise < 0 on error.
511 */
512 static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
513 struct gpt_header *header,
514 uint64_t lba,
515 struct gpt_header *header2)
516 {
517 if (!cxt || !header || !header2)
518 return -ENOSYS;
519
520 header->signature = header2->signature;
521 header->revision = header2->revision;
522 header->size = header2->size;
523 header->npartition_entries = header2->npartition_entries;
524 header->sizeof_partition_entry = header2->sizeof_partition_entry;
525 header->first_usable_lba = header2->first_usable_lba;
526 header->last_usable_lba = header2->last_usable_lba;
527
528 memcpy(&header->disk_guid,
529 &header2->disk_guid, sizeof(header2->disk_guid));
530 gpt_mknew_header_common(cxt, header, lba);
531
532 return 0;
533 }
534
535 static struct gpt_header *gpt_copy_header(struct fdisk_context *cxt,
536 struct gpt_header *src)
537 {
538 struct gpt_header *res;
539
540 if (!cxt || !src)
541 return NULL;
542
543 assert(cxt->sector_size >= sizeof(struct gpt_header));
544
545 res = calloc(1, cxt->sector_size);
546 if (!res) {
547 fdisk_warn(cxt, _("failed to allocate GPT header"));
548 return NULL;
549 }
550
551 res->my_lba = src->alternative_lba;
552 res->alternative_lba = src->my_lba;
553
554 res->signature = src->signature;
555 res->revision = src->revision;
556 res->size = src->size;
557 res->npartition_entries = src->npartition_entries;
558 res->sizeof_partition_entry = src->sizeof_partition_entry;
559 res->first_usable_lba = src->first_usable_lba;
560 res->last_usable_lba = src->last_usable_lba;
561
562 memcpy(&res->disk_guid, &src->disk_guid, sizeof(src->disk_guid));
563
564
565 if (res->my_lba == GPT_PRIMARY_PARTITION_TABLE_LBA)
566 res->partition_entry_lba = cpu_to_le64(2ULL);
567 else {
568 uint64_t esz = (uint64_t) le32_to_cpu(src->npartition_entries) * sizeof(struct gpt_entry);
569 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
570
571 res->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1ULL - esects);
572 }
573
574 return res;
575 }
576
577 static int get_script_u64(struct fdisk_context *cxt, uint64_t *num, const char *name)
578 {
579 const char *str;
580 int pwr = 0, rc = 0;
581
582 assert(cxt);
583
584 *num = 0;
585
586 if (!cxt->script)
587 return 1;
588
589 str = fdisk_script_get_header(cxt->script, name);
590 if (!str)
591 return 1;
592
593 rc = parse_size(str, (uintmax_t *) num, &pwr);
594 if (rc < 0)
595 return rc;
596 if (pwr)
597 *num /= cxt->sector_size;
598 return 0;
599 }
600
601 static int count_first_last_lba(struct fdisk_context *cxt,
602 uint64_t *first, uint64_t *last)
603 {
604 int rc = 0;
605 uint64_t flba, llba;
606
607 uint64_t esz = 0;
608
609 assert(cxt);
610 assert(first);
611 assert(last);
612
613 *first = *last = 0;
614
615 /* UEFI default */
616 esz = sizeof(struct gpt_entry) * GPT_NPARTITIONS / cxt->sector_size;
617 llba = cxt->total_sectors - 2ULL - esz;
618 flba = esz + 2ULL;
619
620 /* script default */
621 if (cxt->script) {
622 rc = get_script_u64(cxt, first, "first-lba");
623 if (rc < 0)
624 return rc;
625
626 DBG(LABEL, ul_debug("FirstLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
627 *first, flba, (uintmax_t)cxt->first_lba));
628
629 if (rc == 0 && (*first < flba || *first > llba)) {
630 fdisk_warnx(cxt, _("First LBA specified by script is out of range."));
631 return -ERANGE;
632 }
633
634 rc = get_script_u64(cxt, last, "last-lba");
635 if (rc < 0)
636 return rc;
637
638 DBG(LABEL, ul_debug("LastLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
639 *last, llba, (uintmax_t)cxt->last_lba));
640
641 if (rc == 0 && (*last > llba || *last < flba)) {
642 fdisk_warnx(cxt, _("Last LBA specified by script is out of range."));
643 return -ERANGE;
644 }
645 }
646
647 if (!*last)
648 *last = llba;
649
650 /* default by topology */
651 if (!*first)
652 *first = flba < cxt->first_lba &&
653 cxt->first_lba < *last ? cxt->first_lba : flba;
654 return 0;
655 }
656
657 /*
658 * Builds a clean new GPT header (currently under revision 1.0).
659 *
660 * Always pass a new (zeroized) header to build upon as we don't
661 * explicitly zero-set some values such as CRCs and reserved.
662 *
663 * Returns 0 on success, otherwise < 0 on error.
664 */
665 static int gpt_mknew_header(struct fdisk_context *cxt,
666 struct gpt_header *header, uint64_t lba)
667 {
668 uint64_t first, last;
669 int has_id = 0, rc;
670
671 if (!cxt || !header)
672 return -ENOSYS;
673
674 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
675 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
676
677 /* According to EFI standard it's valid to count all the first
678 * sector into header size, but some tools may have a problem
679 * to accept it, so use the header without the zeroed area.
680 * This does not have any impact to CRC, etc. --kzak Jan-2015
681 */
682 header->size = cpu_to_le32(sizeof(struct gpt_header)
683 - sizeof(header->reserved2));
684
685 /*
686 * 128 partitions are the default. It can go beyond that, but
687 * we're creating a de facto header here, so no funny business.
688 */
689 header->npartition_entries = cpu_to_le32(GPT_NPARTITIONS);
690 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
691
692 rc = count_first_last_lba(cxt, &first, &last);
693 if (rc)
694 return rc;
695
696 header->first_usable_lba = cpu_to_le64(first);
697 header->last_usable_lba = cpu_to_le64(last);
698
699 gpt_mknew_header_common(cxt, header, lba);
700
701 if (cxt->script) {
702 const char *id = fdisk_script_get_header(cxt->script, "label-id");
703 if (id && string_to_guid(id, &header->disk_guid) == 0)
704 has_id = 1;
705 }
706
707 if (!has_id) {
708 uuid_generate_random((unsigned char *) &header->disk_guid);
709 swap_efi_guid(&header->disk_guid);
710 }
711 return 0;
712 }
713
714 /*
715 * Checks if there is a valid protective MBR partition table.
716 * Returns 0 if it is invalid or failure. Otherwise, return
717 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depending on the detection.
718 */
719 static int valid_pmbr(struct fdisk_context *cxt)
720 {
721 int i, part = 0, ret = 0; /* invalid by default */
722 struct gpt_legacy_mbr *pmbr = NULL;
723
724 if (!cxt->firstsector)
725 goto done;
726
727 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
728
729 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
730 goto done;
731
732 /* seems like a valid MBR was found, check DOS primary partitions */
733 for (i = 0; i < 4; i++) {
734 if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
735 /*
736 * Ok, we at least know that there's a protective MBR,
737 * now check if there are other partition types for
738 * hybrid MBR.
739 */
740 part = i;
741 ret = GPT_MBR_PROTECTIVE;
742 break;
743 }
744 }
745
746 if (ret != GPT_MBR_PROTECTIVE)
747 goto done;
748
749 /* LBA of the GPT partition header */
750 if (pmbr->partition_record[part].starting_lba !=
751 cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
752 goto done;
753
754 for (i = 0 ; i < 4; i++) {
755 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
756 (pmbr->partition_record[i].os_type != 0x00))
757 ret = GPT_MBR_HYBRID;
758 }
759
760 /*
761 * Protective MBRs take up the lesser of the whole disk
762 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
763 * Some partitioning programs, nonetheless, choose to set
764 * the size to the maximum 32-bit limitation, disregarding
765 * the disk size.
766 *
767 * Hybrid MBRs do not necessarily comply with this.
768 *
769 * Consider a bad value here to be a warning to support dd-ing
770 * an image from a smaller disk to a bigger disk.
771 */
772 if (ret == GPT_MBR_PROTECTIVE) {
773 uint64_t sz_lba = (uint64_t) le32_to_cpu(pmbr->partition_record[part].size_in_lba);
774 if (sz_lba != cxt->total_sectors - 1ULL && sz_lba != 0xFFFFFFFFULL) {
775 fdisk_warnx(cxt, _("GPT PMBR size mismatch (%"PRIu64" != %"PRIu64") "
776 "will be corrected by w(rite)."),
777 sz_lba, cxt->total_sectors - 1ULL);
778 fdisk_label_set_changed(cxt->label, 1);
779 }
780 }
781 done:
782 return ret;
783 }
784
785 static uint64_t last_lba(struct fdisk_context *cxt)
786 {
787 struct stat s;
788 uint64_t sectors = 0;
789
790 memset(&s, 0, sizeof(s));
791 if (fstat(cxt->dev_fd, &s) == -1) {
792 fdisk_warn(cxt, _("gpt: stat() failed"));
793 return 0;
794 }
795
796 if (S_ISBLK(s.st_mode))
797 sectors = cxt->total_sectors - 1ULL;
798 else if (S_ISREG(s.st_mode))
799 sectors = ((uint64_t) s.st_size /
800 (uint64_t) cxt->sector_size) - 1ULL;
801 else
802 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
803
804 DBG(LABEL, ul_debug("GPT last LBA: %"PRIu64"", sectors));
805 return sectors;
806 }
807
808 static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
809 void *buffer, const size_t bytes)
810 {
811 off_t offset = lba * cxt->sector_size;
812
813 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
814 return -1;
815 return (size_t)read(cxt->dev_fd, buffer, bytes) != bytes;
816 }
817
818
819 /* Returns the GPT entry array */
820 static struct gpt_entry *gpt_read_entries(struct fdisk_context *cxt,
821 struct gpt_header *header)
822 {
823 ssize_t sz;
824 struct gpt_entry *ret = NULL;
825 off_t offset;
826
827 assert(cxt);
828 assert(header);
829
830 sz = (ssize_t) le32_to_cpu(header->npartition_entries) *
831 le32_to_cpu(header->sizeof_partition_entry);
832
833 ret = calloc(1, sz);
834 if (!ret)
835 return NULL;
836 offset = (off_t) le64_to_cpu(header->partition_entry_lba) *
837 cxt->sector_size;
838
839 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
840 goto fail;
841 if (sz != read(cxt->dev_fd, ret, sz))
842 goto fail;
843
844 return ret;
845
846 fail:
847 free(ret);
848 return NULL;
849 }
850
851 static inline uint32_t count_crc32(const unsigned char *buf, size_t len,
852 size_t ex_off, size_t ex_len)
853 {
854 return (ul_crc32_exclude_offset(~0L, buf, len, ex_off, ex_len) ^ ~0L);
855 }
856
857 static inline uint32_t gpt_header_count_crc32(struct gpt_header *header)
858 {
859 return count_crc32((unsigned char *) header, /* buffer */
860 le32_to_cpu(header->size), /* size of buffer */
861 offsetof(struct gpt_header, crc32), /* exclude */
862 sizeof(header->crc32)); /* size of excluded area */
863 }
864
865 static inline uint32_t gpt_entryarr_count_crc32(struct gpt_header *header, struct gpt_entry *ents)
866 {
867 size_t arysz = 0;
868
869 arysz = (size_t) le32_to_cpu(header->npartition_entries) *
870 le32_to_cpu(header->sizeof_partition_entry);
871
872 return count_crc32((unsigned char *) ents, arysz, 0, 0);
873 }
874
875
876 /*
877 * Recompute header and partition array 32bit CRC checksums.
878 * This function does not fail - if there's corruption, then it
879 * will be reported when checksumming it again (ie: probing or verify).
880 */
881 static void gpt_recompute_crc(struct gpt_header *header, struct gpt_entry *ents)
882 {
883 if (!header)
884 return;
885
886 header->partition_entry_array_crc32 =
887 cpu_to_le32( gpt_entryarr_count_crc32(header, ents) );
888
889 header->crc32 = cpu_to_le32( gpt_header_count_crc32(header) );
890 }
891
892 /*
893 * Compute the 32bit CRC checksum of the partition table header.
894 * Returns 1 if it is valid, otherwise 0.
895 */
896 static int gpt_check_header_crc(struct gpt_header *header, struct gpt_entry *ents)
897 {
898 uint32_t orgcrc = le32_to_cpu(header->crc32),
899 crc = gpt_header_count_crc32(header);
900
901 if (crc == orgcrc)
902 return 1;
903
904 /*
905 * If we have checksum mismatch it may be due to stale data, like a
906 * partition being added or deleted. Recompute the CRC again and make
907 * sure this is not the case.
908 */
909 if (ents) {
910 gpt_recompute_crc(header, ents);
911 return gpt_header_count_crc32(header) == orgcrc;
912 }
913
914 return 0;
915 }
916
917 /*
918 * It initializes the partition entry array.
919 * Returns 1 if the checksum is valid, otherwise 0.
920 */
921 static int gpt_check_entryarr_crc(struct gpt_header *header,
922 struct gpt_entry *ents)
923 {
924 if (!header || !ents)
925 return 0;
926
927 return gpt_entryarr_count_crc32(header, ents) ==
928 le32_to_cpu(header->partition_entry_array_crc32);
929 }
930
931 static int gpt_check_lba_sanity(struct fdisk_context *cxt, struct gpt_header *header)
932 {
933 int ret = 0;
934 uint64_t lu, fu, lastlba = last_lba(cxt);
935
936 fu = le64_to_cpu(header->first_usable_lba);
937 lu = le64_to_cpu(header->last_usable_lba);
938
939 /* check if first and last usable LBA make sense */
940 if (lu < fu) {
941 DBG(LABEL, ul_debug("error: header last LBA is before first LBA"));
942 goto done;
943 }
944
945 /* check if first and last usable LBAs with the disk's last LBA */
946 if (fu > lastlba || lu > lastlba) {
947 DBG(LABEL, ul_debug("error: header LBAs are after the disk's last LBA"));
948 goto done;
949 }
950
951 /* the header has to be outside usable range */
952 if (fu < GPT_PRIMARY_PARTITION_TABLE_LBA &&
953 GPT_PRIMARY_PARTITION_TABLE_LBA < lu) {
954 DBG(LABEL, ul_debug("error: header outside of usable range"));
955 goto done;
956 }
957
958 ret = 1; /* sane */
959 done:
960 return ret;
961 }
962
963 /* Check if there is a valid header signature */
964 static int gpt_check_signature(struct gpt_header *header)
965 {
966 return header->signature == cpu_to_le64(GPT_HEADER_SIGNATURE);
967 }
968
969 /*
970 * Return the specified GPT Header, or NULL upon failure/invalid.
971 * Note that all tests must pass to ensure a valid header,
972 * we do not rely on only testing the signature for a valid probe.
973 */
974 static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
975 uint64_t lba,
976 struct gpt_entry **_ents)
977 {
978 struct gpt_header *header = NULL;
979 struct gpt_entry *ents = NULL;
980 uint32_t hsz;
981
982 if (!cxt)
983 return NULL;
984
985 /* always allocate all sector, the area after GPT header
986 * has to be fill by zeros */
987 assert(cxt->sector_size >= sizeof(struct gpt_header));
988
989 header = calloc(1, cxt->sector_size);
990 if (!header)
991 return NULL;
992
993 /* read and verify header */
994 if (read_lba(cxt, lba, header, cxt->sector_size) != 0)
995 goto invalid;
996
997 if (!gpt_check_signature(header))
998 goto invalid;
999
1000 /* make sure header size is between 92 and sector size bytes */
1001 hsz = le32_to_cpu(header->size);
1002 if (hsz < GPT_HEADER_MINSZ || hsz > cxt->sector_size)
1003 goto invalid;
1004
1005 if (!gpt_check_header_crc(header, NULL))
1006 goto invalid;
1007
1008 /* read and verify entries */
1009 ents = gpt_read_entries(cxt, header);
1010 if (!ents)
1011 goto invalid;
1012
1013 if (!gpt_check_entryarr_crc(header, ents))
1014 goto invalid;
1015
1016 if (!gpt_check_lba_sanity(cxt, header))
1017 goto invalid;
1018
1019 /* valid header must be at MyLBA */
1020 if (le64_to_cpu(header->my_lba) != lba)
1021 goto invalid;
1022
1023
1024 if (_ents)
1025 *_ents = ents;
1026 else
1027 free(ents);
1028
1029 DBG(LABEL, ul_debug("found valid GPT Header on LBA %"PRIu64"", lba));
1030 return header;
1031 invalid:
1032 free(header);
1033 free(ents);
1034
1035 DBG(LABEL, ul_debug("read GPT Header on LBA %"PRIu64" failed", lba));
1036 return NULL;
1037 }
1038
1039
1040 static int gpt_locate_disklabel(struct fdisk_context *cxt, int n,
1041 const char **name, uint64_t *offset, size_t *size)
1042 {
1043 struct fdisk_gpt_label *gpt;
1044
1045 assert(cxt);
1046
1047 *name = NULL;
1048 *offset = 0;
1049 *size = 0;
1050
1051 switch (n) {
1052 case 0:
1053 *name = "PMBR";
1054 *offset = 0;
1055 *size = 512;
1056 break;
1057 case 1:
1058 *name = _("GPT Header");
1059 *offset = (uint64_t) GPT_PRIMARY_PARTITION_TABLE_LBA * cxt->sector_size;
1060 *size = sizeof(struct gpt_header);
1061 break;
1062 case 2:
1063 *name = _("GPT Entries");
1064 gpt = self_label(cxt);
1065 *offset = (uint64_t) le64_to_cpu(gpt->pheader->partition_entry_lba) *
1066 cxt->sector_size;
1067 *size = (size_t) le32_to_cpu(gpt->pheader->npartition_entries) *
1068 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
1069 break;
1070 default:
1071 return 1; /* no more chunks */
1072 }
1073
1074 return 0;
1075 }
1076
1077 static int gpt_get_disklabel_item(struct fdisk_context *cxt, struct fdisk_labelitem *item)
1078 {
1079 struct gpt_header *h;
1080 int rc = 0;
1081
1082 assert(cxt);
1083 assert(cxt->label);
1084 assert(fdisk_is_label(cxt, GPT));
1085
1086 h = self_label(cxt)->pheader;
1087
1088 switch (item->id) {
1089 case GPT_LABELITEM_ID:
1090 item->name = _("Disk identifier");
1091 item->type = 's';
1092 item->data.str = gpt_get_header_id(h);
1093 if (!item->data.str)
1094 rc = -ENOMEM;
1095 break;
1096 case GPT_LABELITEM_FIRSTLBA:
1097 item->name = _("First LBA");
1098 item->type = 'j';
1099 item->data.num64 = le64_to_cpu(h->first_usable_lba);
1100 break;
1101 case GPT_LABELITEM_LASTLBA:
1102 item->name = _("Last LBA");
1103 item->type = 'j';
1104 item->data.num64 = le64_to_cpu(h->last_usable_lba);
1105 break;
1106 case GPT_LABELITEM_ALTLBA:
1107 /* TRANSLATORS: The LBA (Logical Block Address) of the backup GPT header. */
1108 item->name = _("Alternative LBA");
1109 item->type = 'j';
1110 item->data.num64 = le64_to_cpu(h->alternative_lba);
1111 break;
1112 case GPT_LABELITEM_ENTRIESLBA:
1113 /* TRANSLATORS: The start of the array of partition entries. */
1114 item->name = _("Partition entries LBA");
1115 item->type = 'j';
1116 item->data.num64 = le64_to_cpu(h->partition_entry_lba);
1117 break;
1118 case GPT_LABELITEM_ENTRIESALLOC:
1119 item->name = _("Allocated partition entries");
1120 item->type = 'j';
1121 item->data.num64 = le32_to_cpu(h->npartition_entries);
1122 break;
1123 default:
1124 if (item->id < __FDISK_NLABELITEMS)
1125 rc = 1; /* unsupported generic item */
1126 else
1127 rc = 2; /* out of range */
1128 break;
1129 }
1130
1131 return rc;
1132 }
1133
1134 /*
1135 * Returns the number of partitions that are in use.
1136 */
1137 static unsigned partitions_in_use(struct gpt_header *header,
1138 struct gpt_entry *ents)
1139 {
1140 uint32_t i, used = 0;
1141
1142 if (!header || ! ents)
1143 return 0;
1144
1145 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
1146 if (!partition_unused(&ents[i]))
1147 used++;
1148 return used;
1149 }
1150
1151
1152 /*
1153 * Check if a partition is too big for the disk (sectors).
1154 * Returns the faulting partition number, otherwise 0.
1155 */
1156 static uint32_t check_too_big_partitions(struct gpt_header *header,
1157 struct gpt_entry *ents, uint64_t sectors)
1158 {
1159 uint32_t i;
1160
1161 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1162 if (partition_unused(&ents[i]))
1163 continue;
1164 if (gpt_partition_end(&ents[i]) >= sectors)
1165 return i + 1;
1166 }
1167
1168 return 0;
1169 }
1170
1171 /*
1172 * Check if a partition ends before it begins
1173 * Returns the faulting partition number, otherwise 0.
1174 */
1175 static uint32_t check_start_after_end_partitions(struct gpt_header *header,
1176 struct gpt_entry *ents)
1177 {
1178 uint32_t i;
1179
1180 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1181 if (partition_unused(&ents[i]))
1182 continue;
1183 if (gpt_partition_start(&ents[i]) > gpt_partition_end(&ents[i]))
1184 return i + 1;
1185 }
1186
1187 return 0;
1188 }
1189
1190 /*
1191 * Check if partition e1 overlaps with partition e2.
1192 */
1193 static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
1194 {
1195 uint64_t start1 = gpt_partition_start(e1);
1196 uint64_t end1 = gpt_partition_end(e1);
1197 uint64_t start2 = gpt_partition_start(e2);
1198 uint64_t end2 = gpt_partition_end(e2);
1199
1200 return (start1 && start2 && (start1 <= end2) != (end1 < start2));
1201 }
1202
1203 /*
1204 * Find any partitions that overlap.
1205 */
1206 static uint32_t check_overlap_partitions(struct gpt_header *header,
1207 struct gpt_entry *ents)
1208 {
1209 uint32_t i, j;
1210
1211 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
1212 for (j = 0; j < i; j++) {
1213 if (partition_unused(&ents[i]) ||
1214 partition_unused(&ents[j]))
1215 continue;
1216 if (partition_overlap(&ents[i], &ents[j])) {
1217 DBG(LABEL, ul_debug("GPT partitions overlap detected [%u vs. %u]", i, j));
1218 return i + 1;
1219 }
1220 }
1221
1222 return 0;
1223 }
1224
1225 /*
1226 * Find the first available block after the starting point; returns 0 if
1227 * there are no available blocks left, or error. From gdisk.
1228 */
1229 static uint64_t find_first_available(struct gpt_header *header,
1230 struct gpt_entry *ents, uint64_t start)
1231 {
1232 uint64_t first;
1233 uint32_t i, first_moved = 0;
1234
1235 uint64_t fu, lu;
1236
1237 if (!header || !ents)
1238 return 0;
1239
1240 fu = le64_to_cpu(header->first_usable_lba);
1241 lu = le64_to_cpu(header->last_usable_lba);
1242
1243 /*
1244 * Begin from the specified starting point or from the first usable
1245 * LBA, whichever is greater...
1246 */
1247 first = start < fu ? fu : start;
1248
1249 /*
1250 * Now search through all partitions; if first is within an
1251 * existing partition, move it to the next sector after that
1252 * partition and repeat. If first was moved, set firstMoved
1253 * flag; repeat until firstMoved is not set, so as to catch
1254 * cases where partitions are out of sequential order....
1255 */
1256 do {
1257 first_moved = 0;
1258 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1259 if (partition_unused(&ents[i]))
1260 continue;
1261 if (first < gpt_partition_start(&ents[i]))
1262 continue;
1263 if (first <= gpt_partition_end(&ents[i])) {
1264 first = gpt_partition_end(&ents[i]) + 1;
1265 first_moved = 1;
1266 }
1267 }
1268 } while (first_moved == 1);
1269
1270 if (first > lu)
1271 first = 0;
1272
1273 return first;
1274 }
1275
1276
1277 /* Returns last available sector in the free space pointed to by start. From gdisk. */
1278 static uint64_t find_last_free(struct gpt_header *header,
1279 struct gpt_entry *ents, uint64_t start)
1280 {
1281 uint32_t i;
1282 uint64_t nearest_start;
1283
1284 if (!header || !ents)
1285 return 0;
1286
1287 nearest_start = le64_to_cpu(header->last_usable_lba);
1288
1289 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1290 uint64_t ps = gpt_partition_start(&ents[i]);
1291
1292 if (nearest_start > ps && ps > start)
1293 nearest_start = ps - 1ULL;
1294 }
1295
1296 return nearest_start;
1297 }
1298
1299 /* Returns the last free sector on the disk. From gdisk. */
1300 static uint64_t find_last_free_sector(struct gpt_header *header,
1301 struct gpt_entry *ents)
1302 {
1303 uint32_t i, last_moved;
1304 uint64_t last = 0;
1305
1306 if (!header || !ents)
1307 goto done;
1308
1309 /* start by assuming the last usable LBA is available */
1310 last = le64_to_cpu(header->last_usable_lba);
1311 do {
1312 last_moved = 0;
1313 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1314 if ((last >= gpt_partition_start(&ents[i])) &&
1315 (last <= gpt_partition_end(&ents[i]))) {
1316 last = gpt_partition_start(&ents[i]) - 1ULL;
1317 last_moved = 1;
1318 }
1319 }
1320 } while (last_moved == 1);
1321 done:
1322 return last;
1323 }
1324
1325 /*
1326 * Finds the first available sector in the largest block of unallocated
1327 * space on the disk. Returns 0 if there are no available blocks left.
1328 * From gdisk.
1329 */
1330 static uint64_t find_first_in_largest(struct gpt_header *header,
1331 struct gpt_entry *ents)
1332 {
1333 uint64_t start = 0, first_sect, last_sect;
1334 uint64_t segment_size, selected_size = 0, selected_segment = 0;
1335
1336 if (!header || !ents)
1337 goto done;
1338
1339 do {
1340 first_sect = find_first_available(header, ents, start);
1341 if (first_sect != 0) {
1342 last_sect = find_last_free(header, ents, first_sect);
1343 segment_size = last_sect - first_sect + 1ULL;
1344
1345 if (segment_size > selected_size) {
1346 selected_size = segment_size;
1347 selected_segment = first_sect;
1348 }
1349 start = last_sect + 1ULL;
1350 }
1351 } while (first_sect != 0);
1352
1353 done:
1354 return selected_segment;
1355 }
1356
1357 /*
1358 * Find the total number of free sectors, the number of segments in which
1359 * they reside, and the size of the largest of those segments. From gdisk.
1360 */
1361 static uint64_t get_free_sectors(struct fdisk_context *cxt, struct gpt_header *header,
1362 struct gpt_entry *ents, uint32_t *nsegments,
1363 uint64_t *largest_segment)
1364 {
1365 uint32_t num = 0;
1366 uint64_t first_sect, last_sect;
1367 uint64_t largest_seg = 0, segment_sz;
1368 uint64_t totfound = 0, start = 0; /* starting point for each search */
1369
1370 if (!cxt->total_sectors)
1371 goto done;
1372
1373 do {
1374 first_sect = find_first_available(header, ents, start);
1375 if (first_sect) {
1376 last_sect = find_last_free(header, ents, first_sect);
1377 segment_sz = last_sect - first_sect + 1;
1378
1379 if (segment_sz > largest_seg)
1380 largest_seg = segment_sz;
1381 totfound += segment_sz;
1382 num++;
1383 start = last_sect + 1ULL;
1384 }
1385 } while (first_sect);
1386
1387 done:
1388 if (nsegments)
1389 *nsegments = num;
1390 if (largest_segment)
1391 *largest_segment = largest_seg;
1392
1393 return totfound;
1394 }
1395
1396 static int gpt_probe_label(struct fdisk_context *cxt)
1397 {
1398 int mbr_type;
1399 struct fdisk_gpt_label *gpt;
1400
1401 assert(cxt);
1402 assert(cxt->label);
1403 assert(fdisk_is_label(cxt, GPT));
1404
1405 gpt = self_label(cxt);
1406
1407 /* TODO: it would be nice to support scenario when GPT headers are OK,
1408 * but PMBR is corrupt */
1409 mbr_type = valid_pmbr(cxt);
1410 if (!mbr_type)
1411 goto failed;
1412
1413 DBG(LABEL, ul_debug("found a %s MBR", mbr_type == GPT_MBR_PROTECTIVE ?
1414 "protective" : "hybrid"));
1415
1416 /* primary header */
1417 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1418 &gpt->ents);
1419
1420 if (gpt->pheader)
1421 /* primary OK, try backup from alternative LBA */
1422 gpt->bheader = gpt_read_header(cxt,
1423 le64_to_cpu(gpt->pheader->alternative_lba),
1424 NULL);
1425 else
1426 /* primary corrupted -- try last LBA */
1427 gpt->bheader = gpt_read_header(cxt, last_lba(cxt), &gpt->ents);
1428
1429 if (!gpt->pheader && !gpt->bheader)
1430 goto failed;
1431
1432 /* primary OK, backup corrupted -- recovery */
1433 if (gpt->pheader && !gpt->bheader) {
1434 fdisk_warnx(cxt, _("The backup GPT table is corrupt, but the "
1435 "primary appears OK, so that will be used."));
1436 gpt->bheader = gpt_copy_header(cxt, gpt->pheader);
1437 if (!gpt->bheader)
1438 goto failed;
1439 gpt_recompute_crc(gpt->bheader, gpt->ents);
1440
1441 /* primary corrupted, backup OK -- recovery */
1442 } else if (!gpt->pheader && gpt->bheader) {
1443 fdisk_warnx(cxt, _("The primary GPT table is corrupt, but the "
1444 "backup appears OK, so that will be used."));
1445 gpt->pheader = gpt_copy_header(cxt, gpt->bheader);
1446 if (!gpt->pheader)
1447 goto failed;
1448 gpt_recompute_crc(gpt->pheader, gpt->ents);
1449 }
1450
1451 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1452 cxt->label->nparts_cur = partitions_in_use(gpt->pheader, gpt->ents);
1453 return 1;
1454 failed:
1455 DBG(LABEL, ul_debug("GPT probe failed"));
1456 gpt_deinit(cxt->label);
1457 return 0;
1458 }
1459
1460 /*
1461 * Stolen from libblkid - can be removed once partition semantics
1462 * are added to the fdisk API.
1463 */
1464 static char *encode_to_utf8(unsigned char *src, size_t count)
1465 {
1466 uint16_t c;
1467 char *dest;
1468 size_t i, j, len = count;
1469
1470 dest = calloc(1, count);
1471 if (!dest)
1472 return NULL;
1473
1474 for (j = i = 0; i + 2 <= count; i += 2) {
1475 /* always little endian */
1476 c = (src[i+1] << 8) | src[i];
1477 if (c == 0) {
1478 dest[j] = '\0';
1479 break;
1480 } else if (c < 0x80) {
1481 if (j+1 >= len)
1482 break;
1483 dest[j++] = (uint8_t) c;
1484 } else if (c < 0x800) {
1485 if (j+2 >= len)
1486 break;
1487 dest[j++] = (uint8_t) (0xc0 | (c >> 6));
1488 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1489 } else {
1490 if (j+3 >= len)
1491 break;
1492 dest[j++] = (uint8_t) (0xe0 | (c >> 12));
1493 dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
1494 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1495 }
1496 }
1497 dest[j] = '\0';
1498
1499 return dest;
1500 }
1501
1502 static int gpt_entry_attrs_to_string(struct gpt_entry *e, char **res)
1503 {
1504 unsigned int n, count = 0;
1505 size_t l;
1506 char *bits, *p;
1507 uint64_t attrs;
1508
1509 assert(e);
1510 assert(res);
1511
1512 *res = NULL;
1513 attrs = e->attrs;
1514 if (!attrs)
1515 return 0; /* no attributes at all */
1516
1517 bits = (char *) &attrs;
1518
1519 /* Note that sizeof() is correct here, we need separators between
1520 * the strings so also count \0 is correct */
1521 *res = calloc(1, sizeof(GPT_ATTRSTR_NOBLOCK) +
1522 sizeof(GPT_ATTRSTR_REQ) +
1523 sizeof(GPT_ATTRSTR_LEGACY) +
1524 sizeof("GUID:") + (GPT_ATTRBIT_GUID_COUNT * 3));
1525 if (!*res)
1526 return -errno;
1527
1528 p = *res;
1529 if (isset(bits, GPT_ATTRBIT_REQ)) {
1530 memcpy(p, GPT_ATTRSTR_REQ, (l = sizeof(GPT_ATTRSTR_REQ)));
1531 p += l - 1;
1532 }
1533 if (isset(bits, GPT_ATTRBIT_NOBLOCK)) {
1534 if (p > *res)
1535 *p++ = ' ';
1536 memcpy(p, GPT_ATTRSTR_NOBLOCK, (l = sizeof(GPT_ATTRSTR_NOBLOCK)));
1537 p += l - 1;
1538 }
1539 if (isset(bits, GPT_ATTRBIT_LEGACY)) {
1540 if (p > *res)
1541 *p++ = ' ';
1542 memcpy(p, GPT_ATTRSTR_LEGACY, (l = sizeof(GPT_ATTRSTR_LEGACY)));
1543 p += l - 1;
1544 }
1545
1546 for (n = GPT_ATTRBIT_GUID_FIRST;
1547 n < GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT; n++) {
1548
1549 if (!isset(bits, n))
1550 continue;
1551 if (!count) {
1552 if (p > *res)
1553 *p++ = ' ';
1554 p += sprintf(p, "GUID:%u", n);
1555 } else
1556 p += sprintf(p, ",%u", n);
1557 count++;
1558 }
1559
1560 return 0;
1561 }
1562
1563 static int gpt_entry_attrs_from_string(
1564 struct fdisk_context *cxt,
1565 struct gpt_entry *e,
1566 const char *str)
1567 {
1568 const char *p = str;
1569 uint64_t attrs = 0;
1570 char *bits;
1571
1572 assert(e);
1573 assert(p);
1574
1575 DBG(LABEL, ul_debug("GPT: parsing string attributes '%s'", p));
1576
1577 bits = (char *) &attrs;
1578
1579 while (p && *p) {
1580 int bit = -1;
1581
1582 while (isblank(*p)) p++;
1583 if (!*p)
1584 break;
1585
1586 DBG(LABEL, ul_debug(" parsing item '%s'", p));
1587
1588 if (strncmp(p, GPT_ATTRSTR_REQ,
1589 sizeof(GPT_ATTRSTR_REQ) - 1) == 0) {
1590 bit = GPT_ATTRBIT_REQ;
1591 p += sizeof(GPT_ATTRSTR_REQ) - 1;
1592 } else if (strncmp(p, GPT_ATTRSTR_REQ_TYPO,
1593 sizeof(GPT_ATTRSTR_REQ_TYPO) - 1) == 0) {
1594 bit = GPT_ATTRBIT_REQ;
1595 p += sizeof(GPT_ATTRSTR_REQ_TYPO) - 1;
1596 } else if (strncmp(p, GPT_ATTRSTR_LEGACY,
1597 sizeof(GPT_ATTRSTR_LEGACY) - 1) == 0) {
1598 bit = GPT_ATTRBIT_LEGACY;
1599 p += sizeof(GPT_ATTRSTR_LEGACY) - 1;
1600 } else if (strncmp(p, GPT_ATTRSTR_NOBLOCK,
1601 sizeof(GPT_ATTRSTR_NOBLOCK) - 1) == 0) {
1602 bit = GPT_ATTRBIT_NOBLOCK;
1603 p += sizeof(GPT_ATTRSTR_NOBLOCK) - 1;
1604
1605 /* GUID:<bit> as well as <bit> */
1606 } else if (isdigit((unsigned char) *p)
1607 || (strncmp(p, "GUID:", 5) == 0
1608 && isdigit((unsigned char) *(p + 5)))) {
1609 char *end = NULL;
1610
1611 if (*p == 'G')
1612 p += 5;
1613
1614 errno = 0;
1615 bit = strtol(p, &end, 0);
1616 if (errno || !end || end == str
1617 || bit < GPT_ATTRBIT_GUID_FIRST
1618 || bit >= GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT)
1619 bit = -1;
1620 else
1621 p = end;
1622 }
1623
1624 if (bit < 0) {
1625 fdisk_warnx(cxt, _("unsupported GPT attribute bit '%s'"), p);
1626 return -EINVAL;
1627 }
1628
1629 if (*p && *p != ',' && !isblank(*p)) {
1630 fdisk_warnx(cxt, _("failed to parse GPT attribute string '%s'"), str);
1631 return -EINVAL;
1632 }
1633
1634 setbit(bits, bit);
1635
1636 while (isblank(*p)) p++;
1637 if (*p == ',')
1638 p++;
1639 }
1640
1641 e->attrs = attrs;
1642 return 0;
1643 }
1644
1645 static int gpt_get_partition(struct fdisk_context *cxt, size_t n,
1646 struct fdisk_partition *pa)
1647 {
1648 struct fdisk_gpt_label *gpt;
1649 struct gpt_entry *e;
1650 char u_str[37];
1651 int rc = 0;
1652
1653 assert(cxt);
1654 assert(cxt->label);
1655 assert(fdisk_is_label(cxt, GPT));
1656
1657 gpt = self_label(cxt);
1658
1659 if ((uint32_t) n >= le32_to_cpu(gpt->pheader->npartition_entries))
1660 return -EINVAL;
1661
1662 gpt = self_label(cxt);
1663 e = &gpt->ents[n];
1664
1665 pa->used = !partition_unused(e) || gpt_partition_start(e);
1666 if (!pa->used)
1667 return 0;
1668
1669 pa->start = gpt_partition_start(e);
1670 pa->size = gpt_partition_size(e);
1671 pa->type = gpt_partition_parttype(cxt, e);
1672
1673 if (guid_to_string(&e->partition_guid, u_str)) {
1674 pa->uuid = strdup(u_str);
1675 if (!pa->uuid) {
1676 rc = -errno;
1677 goto done;
1678 }
1679 } else
1680 pa->uuid = NULL;
1681
1682 rc = gpt_entry_attrs_to_string(e, &pa->attrs);
1683 if (rc)
1684 goto done;
1685
1686 pa->name = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1687 return 0;
1688 done:
1689 fdisk_reset_partition(pa);
1690 return rc;
1691 }
1692
1693
1694 static int gpt_set_partition(struct fdisk_context *cxt, size_t n,
1695 struct fdisk_partition *pa)
1696 {
1697 struct fdisk_gpt_label *gpt;
1698 struct gpt_entry *e;
1699 int rc = 0;
1700 uint64_t start, end;
1701
1702 assert(cxt);
1703 assert(cxt->label);
1704 assert(fdisk_is_label(cxt, GPT));
1705
1706 gpt = self_label(cxt);
1707
1708 if ((uint32_t) n >= le32_to_cpu(gpt->pheader->npartition_entries))
1709 return -EINVAL;
1710
1711 FDISK_INIT_UNDEF(start);
1712 FDISK_INIT_UNDEF(end);
1713
1714 gpt = self_label(cxt);
1715 e = &gpt->ents[n];
1716
1717 if (pa->uuid) {
1718 char new_u[37], old_u[37];
1719
1720 guid_to_string(&e->partition_guid, old_u);
1721 rc = gpt_entry_set_uuid(e, pa->uuid);
1722 if (rc)
1723 return rc;
1724 guid_to_string(&e->partition_guid, new_u);
1725 fdisk_info(cxt, _("Partition UUID changed from %s to %s."),
1726 old_u, new_u);
1727 }
1728
1729 if (pa->name) {
1730 char *old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1731 gpt_entry_set_name(e, pa->name);
1732
1733 fdisk_info(cxt, _("Partition name changed from '%s' to '%.*s'."),
1734 old, (int) GPT_PART_NAME_LEN, pa->name);
1735 free(old);
1736 }
1737
1738 if (pa->type && pa->type->typestr) {
1739 struct gpt_guid typeid;
1740
1741 rc = string_to_guid(pa->type->typestr, &typeid);
1742 if (rc)
1743 return rc;
1744 gpt_entry_set_type(e, &typeid);
1745 }
1746 if (pa->attrs) {
1747 rc = gpt_entry_attrs_from_string(cxt, e, pa->attrs);
1748 if (rc)
1749 return rc;
1750 }
1751
1752 if (fdisk_partition_has_start(pa))
1753 start = pa->start;
1754 if (fdisk_partition_has_size(pa) || fdisk_partition_has_start(pa)) {
1755 uint64_t xstart = fdisk_partition_has_start(pa) ? pa->start : gpt_partition_start(e);
1756 uint64_t xsize = fdisk_partition_has_size(pa) ? pa->size : gpt_partition_size(e);
1757 end = xstart + xsize - 1ULL;
1758 }
1759
1760 if (!FDISK_IS_UNDEF(start)) {
1761 if (start < le64_to_cpu(gpt->pheader->first_usable_lba)) {
1762 fdisk_warnx(cxt, _("The start of the partition understeps FirstUsableLBA."));
1763 return -EINVAL;
1764 }
1765 e->lba_start = cpu_to_le64(start);
1766 }
1767 if (!FDISK_IS_UNDEF(end)) {
1768 if (end > le64_to_cpu(gpt->pheader->last_usable_lba)) {
1769 fdisk_warnx(cxt, _("The end of the partition oversteps LastUsableLBA."));
1770 return -EINVAL;
1771 }
1772 e->lba_end = cpu_to_le64(end);
1773 }
1774 gpt_recompute_crc(gpt->pheader, gpt->ents);
1775 gpt_recompute_crc(gpt->bheader, gpt->ents);
1776
1777 fdisk_label_set_changed(cxt->label, 1);
1778 return rc;
1779 }
1780
1781
1782
1783 /*
1784 * Write partitions.
1785 * Returns 0 on success, or corresponding error otherwise.
1786 */
1787 static int gpt_write_partitions(struct fdisk_context *cxt,
1788 struct gpt_header *header, struct gpt_entry *ents)
1789 {
1790 off_t offset = (off_t) le64_to_cpu(header->partition_entry_lba) * cxt->sector_size;
1791 uint32_t nparts = le32_to_cpu(header->npartition_entries);
1792 uint32_t totwrite = nparts * le32_to_cpu(header->sizeof_partition_entry);
1793 ssize_t rc;
1794
1795 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1796 goto fail;
1797
1798 rc = write(cxt->dev_fd, ents, totwrite);
1799 if (rc > 0 && totwrite == (uint32_t) rc)
1800 return 0;
1801 fail:
1802 return -errno;
1803 }
1804
1805 /*
1806 * Write a GPT header to a specified LBA.
1807 *
1808 * We read all sector, so we have to write all sector back
1809 * to the device -- never ever rely on sizeof(struct gpt_header)!
1810 *
1811 * Returns 0 on success, or corresponding error otherwise.
1812 */
1813 static int gpt_write_header(struct fdisk_context *cxt,
1814 struct gpt_header *header, uint64_t lba)
1815 {
1816 off_t offset = lba * cxt->sector_size;
1817
1818 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1819 goto fail;
1820 if (cxt->sector_size ==
1821 (size_t) write(cxt->dev_fd, header, cxt->sector_size))
1822 return 0;
1823 fail:
1824 return -errno;
1825 }
1826
1827 /*
1828 * Write the protective MBR.
1829 * Returns 0 on success, or corresponding error otherwise.
1830 */
1831 static int gpt_write_pmbr(struct fdisk_context *cxt)
1832 {
1833 off_t offset;
1834 struct gpt_legacy_mbr *pmbr = NULL;
1835
1836 assert(cxt);
1837 assert(cxt->firstsector);
1838
1839 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
1840
1841 /* zero out the legacy partitions */
1842 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
1843
1844 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
1845 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
1846 pmbr->partition_record[0].start_sector = 1;
1847 pmbr->partition_record[0].end_head = 0xFE;
1848 pmbr->partition_record[0].end_sector = 0xFF;
1849 pmbr->partition_record[0].end_track = 0xFF;
1850 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
1851
1852 /*
1853 * Set size_in_lba to the size of the disk minus one. If the size of the disk
1854 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
1855 */
1856 if (cxt->total_sectors - 1ULL > 0xFFFFFFFFULL)
1857 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
1858 else
1859 pmbr->partition_record[0].size_in_lba =
1860 cpu_to_le32((uint32_t) (cxt->total_sectors - 1ULL));
1861
1862 offset = GPT_PMBR_LBA * cxt->sector_size;
1863 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1864 goto fail;
1865
1866 /* pMBR covers the first sector (LBA) of the disk */
1867 if (write_all(cxt->dev_fd, pmbr, cxt->sector_size))
1868 goto fail;
1869 return 0;
1870 fail:
1871 return -errno;
1872 }
1873
1874 /*
1875 * Writes in-memory GPT and pMBR data to disk.
1876 * Returns 0 if successful write, otherwise, a corresponding error.
1877 * Any indication of error will abort the operation.
1878 */
1879 static int gpt_write_disklabel(struct fdisk_context *cxt)
1880 {
1881 struct fdisk_gpt_label *gpt;
1882 int mbr_type;
1883
1884 assert(cxt);
1885 assert(cxt->label);
1886 assert(fdisk_is_label(cxt, GPT));
1887
1888 gpt = self_label(cxt);
1889 mbr_type = valid_pmbr(cxt);
1890
1891 /* check that disk is big enough to handle the backup header */
1892 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
1893 goto err0;
1894
1895 /* check that the backup header is properly placed */
1896 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1ULL)
1897 /* TODO: correct this (with user authorization) and write */
1898 goto err0;
1899
1900 if (check_overlap_partitions(gpt->pheader, gpt->ents))
1901 goto err0;
1902
1903 /* recompute CRCs for both headers */
1904 gpt_recompute_crc(gpt->pheader, gpt->ents);
1905 gpt_recompute_crc(gpt->bheader, gpt->ents);
1906
1907 /*
1908 * UEFI requires writing in this specific order:
1909 * 1) backup partition tables
1910 * 2) backup GPT header
1911 * 3) primary partition tables
1912 * 4) primary GPT header
1913 * 5) protective MBR
1914 *
1915 * If any write fails, we abort the rest.
1916 */
1917 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
1918 goto err1;
1919 if (gpt_write_header(cxt, gpt->bheader,
1920 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
1921 goto err1;
1922 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
1923 goto err1;
1924 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
1925 goto err1;
1926
1927 if (mbr_type == GPT_MBR_HYBRID)
1928 fdisk_warnx(cxt, _("The device contains hybrid MBR -- writing GPT only. "
1929 "You have to sync the MBR manually."));
1930 else if (gpt_write_pmbr(cxt) != 0)
1931 goto err1;
1932
1933 DBG(LABEL, ul_debug("GPT write success"));
1934 return 0;
1935 err0:
1936 DBG(LABEL, ul_debug("GPT write failed: incorrect input"));
1937 errno = EINVAL;
1938 return -EINVAL;
1939 err1:
1940 DBG(LABEL, ul_debug("GPT write failed: %m"));
1941 return -errno;
1942 }
1943
1944 /*
1945 * Verify data integrity and report any found problems for:
1946 * - primary and backup header validations
1947 * - partition validations
1948 */
1949 static int gpt_verify_disklabel(struct fdisk_context *cxt)
1950 {
1951 int nerror = 0;
1952 unsigned int ptnum;
1953 struct fdisk_gpt_label *gpt;
1954
1955 assert(cxt);
1956 assert(cxt->label);
1957 assert(fdisk_is_label(cxt, GPT));
1958
1959 gpt = self_label(cxt);
1960 if (!gpt)
1961 return -EINVAL;
1962
1963 if (!gpt->bheader) {
1964 nerror++;
1965 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
1966 }
1967
1968 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
1969 nerror++;
1970 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
1971 }
1972 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
1973 nerror++;
1974 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
1975 }
1976
1977 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
1978 nerror++;
1979 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
1980 }
1981
1982 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
1983 nerror++;
1984 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
1985 }
1986 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
1987 nerror++;
1988 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
1989 }
1990
1991 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
1992 nerror++;
1993 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
1994 }
1995 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
1996 nerror++;
1997 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
1998
1999 }
2000 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
2001 nerror++;
2002 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
2003 }
2004
2005 /*
2006 * if the GPT is the primary table, check the alternateLBA
2007 * to see if it is a valid GPT
2008 */
2009 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
2010 le64_to_cpu(gpt->bheader->alternative_lba))) {
2011 nerror++;
2012 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
2013 }
2014
2015 ptnum = check_overlap_partitions(gpt->pheader, gpt->ents);
2016 if (ptnum) {
2017 nerror++;
2018 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
2019 ptnum, ptnum+1);
2020 }
2021
2022 ptnum = check_too_big_partitions(gpt->pheader, gpt->ents, cxt->total_sectors);
2023 if (ptnum) {
2024 nerror++;
2025 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
2026 ptnum);
2027 }
2028
2029 ptnum = check_start_after_end_partitions(gpt->pheader, gpt->ents);
2030 if (ptnum) {
2031 nerror++;
2032 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
2033 ptnum);
2034 }
2035
2036 if (!nerror) { /* yay :-) */
2037 uint32_t nsegments = 0;
2038 uint64_t free_sectors = 0, largest_segment = 0;
2039 char *strsz = NULL;
2040
2041 fdisk_info(cxt, _("No errors detected."));
2042 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
2043 fdisk_info(cxt, _("Using %u out of %d partitions."),
2044 partitions_in_use(gpt->pheader, gpt->ents),
2045 le32_to_cpu(gpt->pheader->npartition_entries));
2046
2047 free_sectors = get_free_sectors(cxt, gpt->pheader, gpt->ents,
2048 &nsegments, &largest_segment);
2049 if (largest_segment)
2050 strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER,
2051 largest_segment * cxt->sector_size);
2052
2053 fdisk_info(cxt,
2054 P_("A total of %ju free sectors is available in %u segment.",
2055 "A total of %ju free sectors is available in %u segments "
2056 "(the largest is %s).", nsegments),
2057 free_sectors, nsegments, strsz);
2058 free(strsz);
2059
2060 } else
2061 fdisk_warnx(cxt,
2062 P_("%d error detected.", "%d errors detected.", nerror),
2063 nerror);
2064
2065 return 0;
2066 }
2067
2068 /* Delete a single GPT partition, specified by partnum. */
2069 static int gpt_delete_partition(struct fdisk_context *cxt,
2070 size_t partnum)
2071 {
2072 struct fdisk_gpt_label *gpt;
2073
2074 assert(cxt);
2075 assert(cxt->label);
2076 assert(fdisk_is_label(cxt, GPT));
2077
2078 gpt = self_label(cxt);
2079
2080 if (partnum >= cxt->label->nparts_max
2081 || partition_unused(&gpt->ents[partnum]))
2082 return -EINVAL;
2083
2084 /* hasta la vista, baby! */
2085 memset(&gpt->ents[partnum], 0, sizeof(struct gpt_entry));
2086 if (!partition_unused(&gpt->ents[partnum]))
2087 return -EINVAL;
2088 else {
2089 gpt_recompute_crc(gpt->pheader, gpt->ents);
2090 gpt_recompute_crc(gpt->bheader, gpt->ents);
2091 cxt->label->nparts_cur--;
2092 fdisk_label_set_changed(cxt->label, 1);
2093 }
2094
2095 return 0;
2096 }
2097
2098
2099 /* Performs logical checks to add a new partition entry */
2100 static int gpt_add_partition(
2101 struct fdisk_context *cxt,
2102 struct fdisk_partition *pa,
2103 size_t *partno)
2104 {
2105 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
2106 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
2107 uint64_t dflt_f, dflt_l; /* largest segment (default) */
2108 struct gpt_guid typeid;
2109 struct fdisk_gpt_label *gpt;
2110 struct gpt_header *pheader;
2111 struct gpt_entry *e, *ents;
2112 struct fdisk_ask *ask = NULL;
2113 size_t partnum;
2114 int rc;
2115
2116 assert(cxt);
2117 assert(cxt->label);
2118 assert(fdisk_is_label(cxt, GPT));
2119
2120 gpt = self_label(cxt);
2121 pheader = gpt->pheader;
2122 ents = gpt->ents;
2123
2124 rc = fdisk_partition_next_partno(pa, cxt, &partnum);
2125 if (rc) {
2126 DBG(LABEL, ul_debug("GPT failed to get next partno"));
2127 return rc;
2128 }
2129 if (!partition_unused(&ents[partnum])) {
2130 fdisk_warnx(cxt, _("Partition %zu is already defined. "
2131 "Delete it before re-adding it."), partnum +1);
2132 return -ERANGE;
2133 }
2134 if (le32_to_cpu(pheader->npartition_entries) ==
2135 partitions_in_use(pheader, ents)) {
2136 fdisk_warnx(cxt, _("All partitions are already in use."));
2137 return -ENOSPC;
2138 }
2139 if (!get_free_sectors(cxt, pheader, ents, NULL, NULL)) {
2140 fdisk_warnx(cxt, _("No free sectors available."));
2141 return -ENOSPC;
2142 }
2143
2144 rc = string_to_guid(pa && pa->type && pa->type->typestr ?
2145 pa->type->typestr:
2146 GPT_DEFAULT_ENTRY_TYPE, &typeid);
2147 if (rc)
2148 return rc;
2149
2150 disk_f = find_first_available(pheader, ents, le64_to_cpu(pheader->first_usable_lba));
2151
2152 /* if first sector no explicitly defined then ignore small gaps before
2153 * the first partition */
2154 if ((!pa || !fdisk_partition_has_start(pa))
2155 && !partition_unused(&ents[0])
2156 && disk_f < gpt_partition_start(&ents[0])) {
2157
2158 do {
2159 uint64_t x;
2160 DBG(LABEL, ul_debug("testing first sector %"PRIu64"", disk_f));
2161 disk_f = find_first_available(pheader, ents, disk_f);
2162 if (!disk_f)
2163 break;
2164 x = find_last_free(pheader, ents, disk_f);
2165 if (x - disk_f >= cxt->grain / cxt->sector_size)
2166 break;
2167 DBG(LABEL, ul_debug("first sector %"PRIu64" addresses to small space, continue...", disk_f));
2168 disk_f = x + 1ULL;
2169 } while(1);
2170
2171 if (disk_f == 0)
2172 disk_f = find_first_available(pheader, ents, le64_to_cpu(pheader->first_usable_lba));
2173 }
2174
2175 disk_l = find_last_free_sector(pheader, ents);
2176
2177 /* the default is the largest free space */
2178 dflt_f = find_first_in_largest(pheader, ents);
2179 dflt_l = find_last_free(pheader, ents, dflt_f);
2180
2181 /* align the default in range <dflt_f,dflt_l>*/
2182 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
2183
2184 /* first sector */
2185 if (pa && pa->start_follow_default) {
2186 user_f = dflt_f;
2187
2188 } else if (pa && fdisk_partition_has_start(pa)) {
2189 DBG(LABEL, ul_debug("first sector defined: %ju", (uintmax_t)pa->start));
2190 if (pa->start != find_first_available(pheader, ents, pa->start)) {
2191 fdisk_warnx(cxt, _("Sector %ju already used."), (uintmax_t)pa->start);
2192 return -ERANGE;
2193 }
2194 user_f = pa->start;
2195 } else {
2196 /* ask by dialog */
2197 for (;;) {
2198 if (!ask)
2199 ask = fdisk_new_ask();
2200 else
2201 fdisk_reset_ask(ask);
2202
2203 /* First sector */
2204 fdisk_ask_set_query(ask, _("First sector"));
2205 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
2206 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
2207 fdisk_ask_number_set_default(ask, dflt_f); /* default */
2208 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
2209
2210 rc = fdisk_do_ask(cxt, ask);
2211 if (rc)
2212 goto done;
2213
2214 user_f = fdisk_ask_number_get_result(ask);
2215 if (user_f != find_first_available(pheader, ents, user_f)) {
2216 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
2217 continue;
2218 }
2219 break;
2220 }
2221 }
2222
2223
2224 /* Last sector */
2225 dflt_l = find_last_free(pheader, ents, user_f);
2226
2227 if (pa && pa->end_follow_default) {
2228 user_l = dflt_l;
2229
2230 } else if (pa && fdisk_partition_has_size(pa)) {
2231 user_l = user_f + pa->size - 1;
2232 DBG(LABEL, ul_debug("size defined: %ju, end: %"PRIu64" (last possible: %"PRIu64")",
2233 (uintmax_t)pa->size, user_l, dflt_l));
2234 if (user_l != dflt_l && !pa->size_explicit
2235 && user_l - user_f > (cxt->grain / fdisk_get_sector_size(cxt))) {
2236 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2237 if (user_l > user_f)
2238 user_l -= 1ULL;
2239 }
2240 } else {
2241 for (;;) {
2242 if (!ask)
2243 ask = fdisk_new_ask();
2244 else
2245 fdisk_reset_ask(ask);
2246 if (!ask)
2247 return -ENOMEM;
2248
2249 fdisk_ask_set_query(ask, _("Last sector, +sectors or +size{K,M,G,T,P}"));
2250 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
2251 fdisk_ask_number_set_low(ask, user_f); /* minimal */
2252 fdisk_ask_number_set_default(ask, dflt_l); /* default */
2253 fdisk_ask_number_set_high(ask, dflt_l); /* maximal */
2254 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
2255 fdisk_ask_number_set_unit(ask, cxt->sector_size);
2256
2257 rc = fdisk_do_ask(cxt, ask);
2258 if (rc)
2259 goto done;
2260
2261 user_l = fdisk_ask_number_get_result(ask);
2262 if (fdisk_ask_number_is_relative(ask)) {
2263 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2264 if (user_l > user_f)
2265 user_l -= 1ULL;
2266 }
2267
2268 if (user_l >= user_f && user_l <= disk_l)
2269 break;
2270
2271 fdisk_warnx(cxt, _("Value out of range."));
2272 }
2273 }
2274
2275
2276 if (user_f > user_l || partnum >= cxt->label->nparts_max) {
2277 fdisk_warnx(cxt, _("Could not create partition %zu"), partnum + 1);
2278 rc = -EINVAL;
2279 goto done;
2280 }
2281
2282 /* Be paranoid and check against on-disk setting rather than against libfdisk cxt */
2283 if (user_l > le64_to_cpu(pheader->last_usable_lba)) {
2284 fdisk_warnx(cxt, _("The last usable GPT sector is %ju, but %ju is requested."),
2285 le64_to_cpu(pheader->last_usable_lba), user_l);
2286 rc = -EINVAL;
2287 goto done;
2288 }
2289
2290 if (user_f < le64_to_cpu(pheader->first_usable_lba)) {
2291 fdisk_warnx(cxt, _("The first usable GPT sector is %ju, but %ju is requested."),
2292 le64_to_cpu(pheader->first_usable_lba), user_f);
2293 rc = -EINVAL;
2294 goto done;
2295 }
2296
2297 assert(!FDISK_IS_UNDEF(user_l));
2298 assert(!FDISK_IS_UNDEF(user_f));
2299
2300 e = &ents[partnum];
2301 e->lba_end = cpu_to_le64(user_l);
2302 e->lba_start = cpu_to_le64(user_f);
2303
2304 gpt_entry_set_type(e, &typeid);
2305
2306 if (pa && pa->uuid) {
2307 /* Sometimes it's necessary to create a copy of the PT and
2308 * reuse already defined UUID
2309 */
2310 rc = gpt_entry_set_uuid(e, pa->uuid);
2311 if (rc)
2312 goto done;
2313 } else {
2314 /* Any time a new partition entry is created a new GUID must be
2315 * generated for that partition, and every partition is guaranteed
2316 * to have a unique GUID.
2317 */
2318 uuid_generate_random((unsigned char *) &e->partition_guid);
2319 swap_efi_guid(&e->partition_guid);
2320 }
2321
2322 if (pa && pa->name && *pa->name)
2323 gpt_entry_set_name(e, pa->name);
2324 if (pa && pa->attrs)
2325 gpt_entry_attrs_from_string(cxt, e, pa->attrs);
2326
2327 DBG(LABEL, ul_debug("GPT new partition: partno=%zu, start=%"PRIu64", end=%"PRIu64", size=%"PRIu64"",
2328 partnum,
2329 gpt_partition_start(e),
2330 gpt_partition_end(e),
2331 gpt_partition_size(e)));
2332
2333 gpt_recompute_crc(gpt->pheader, ents);
2334 gpt_recompute_crc(gpt->bheader, ents);
2335
2336 /* report result */
2337 {
2338 struct fdisk_parttype *t;
2339
2340 cxt->label->nparts_cur++;
2341 fdisk_label_set_changed(cxt->label, 1);
2342
2343 t = gpt_partition_parttype(cxt, &ents[partnum]);
2344 fdisk_info_new_partition(cxt, partnum + 1, user_f, user_l, t);
2345 fdisk_unref_parttype(t);
2346 }
2347
2348 rc = 0;
2349 if (partno)
2350 *partno = partnum;
2351 done:
2352 fdisk_unref_ask(ask);
2353 return rc;
2354 }
2355
2356 /*
2357 * Create a new GPT disklabel - destroys any previous data.
2358 */
2359 static int gpt_create_disklabel(struct fdisk_context *cxt)
2360 {
2361 int rc = 0;
2362 size_t esz = 0;
2363 char str[37];
2364 struct fdisk_gpt_label *gpt;
2365
2366 assert(cxt);
2367 assert(cxt->label);
2368 assert(fdisk_is_label(cxt, GPT));
2369
2370 gpt = self_label(cxt);
2371
2372 /* label private stuff has to be empty, see gpt_deinit() */
2373 assert(gpt->pheader == NULL);
2374 assert(gpt->bheader == NULL);
2375
2376 /*
2377 * When no header, entries or pmbr is set, we're probably
2378 * dealing with a new, empty disk - so always allocate memory
2379 * to deal with the data structures whatever the case is.
2380 */
2381 rc = gpt_mknew_pmbr(cxt);
2382 if (rc < 0)
2383 goto done;
2384
2385 assert(cxt->sector_size >= sizeof(struct gpt_header));
2386
2387 /* primary */
2388 gpt->pheader = calloc(1, cxt->sector_size);
2389 if (!gpt->pheader) {
2390 rc = -ENOMEM;
2391 goto done;
2392 }
2393 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
2394 if (rc < 0)
2395 goto done;
2396
2397 /* backup ("copy" primary) */
2398 gpt->bheader = calloc(1, cxt->sector_size);
2399 if (!gpt->bheader) {
2400 rc = -ENOMEM;
2401 goto done;
2402 }
2403 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
2404 last_lba(cxt), gpt->pheader);
2405 if (rc < 0)
2406 goto done;
2407
2408 esz = (size_t) le32_to_cpu(gpt->pheader->npartition_entries) *
2409 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
2410 gpt->ents = calloc(1, esz);
2411 if (!gpt->ents) {
2412 rc = -ENOMEM;
2413 goto done;
2414 }
2415 gpt_recompute_crc(gpt->pheader, gpt->ents);
2416 gpt_recompute_crc(gpt->bheader, gpt->ents);
2417
2418 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
2419 cxt->label->nparts_cur = 0;
2420
2421 guid_to_string(&gpt->pheader->disk_guid, str);
2422 fdisk_label_set_changed(cxt->label, 1);
2423 fdisk_info(cxt, _("Created a new GPT disklabel (GUID: %s)."), str);
2424 done:
2425 return rc;
2426 }
2427
2428 static int gpt_set_disklabel_id(struct fdisk_context *cxt)
2429 {
2430 struct fdisk_gpt_label *gpt;
2431 struct gpt_guid uuid;
2432 char *str, *old, *new;
2433 int rc;
2434
2435 assert(cxt);
2436 assert(cxt->label);
2437 assert(fdisk_is_label(cxt, GPT));
2438
2439 gpt = self_label(cxt);
2440 if (fdisk_ask_string(cxt,
2441 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &str))
2442 return -EINVAL;
2443
2444 rc = string_to_guid(str, &uuid);
2445 free(str);
2446
2447 if (rc) {
2448 fdisk_warnx(cxt, _("Failed to parse your UUID."));
2449 return rc;
2450 }
2451
2452 old = gpt_get_header_id(gpt->pheader);
2453
2454 gpt->pheader->disk_guid = uuid;
2455 gpt->bheader->disk_guid = uuid;
2456
2457 gpt_recompute_crc(gpt->pheader, gpt->ents);
2458 gpt_recompute_crc(gpt->bheader, gpt->ents);
2459
2460 new = gpt_get_header_id(gpt->pheader);
2461
2462 fdisk_info(cxt, _("Disk identifier changed from %s to %s."), old, new);
2463
2464 free(old);
2465 free(new);
2466 fdisk_label_set_changed(cxt->label, 1);
2467 return 0;
2468 }
2469
2470 static int gpt_check_table_overlap(struct fdisk_context *cxt,
2471 uint64_t first_usable,
2472 uint64_t last_usable)
2473 {
2474 struct fdisk_gpt_label *gpt = self_label(cxt);
2475 unsigned int i;
2476 int rc = 0;
2477
2478 /* First check if there's enough room for the table. last_lba may have wrapped */
2479 if (first_usable > cxt->total_sectors || /* far too little space */
2480 last_usable > cxt->total_sectors || /* wrapped */
2481 first_usable > last_usable) { /* too little space */
2482 fdisk_warnx(cxt, _("Not enough space for new partition table!"));
2483 return -ENOSPC;
2484 }
2485
2486 /* check that all partitions fit in the remaining space */
2487 for (i = 0; i < le32_to_cpu(gpt->pheader->npartition_entries); i++) {
2488 if (partition_unused(&gpt->ents[i]))
2489 continue;
2490 if (gpt_partition_start(&gpt->ents[i]) < first_usable) {
2491 fdisk_warnx(cxt, _("Partition #%u out of range (minimal start is %"PRIu64" sectors)"),
2492 i + 1, first_usable);
2493 rc = -EINVAL;
2494 }
2495 if (gpt_partition_end(&gpt->ents[i]) > last_usable) {
2496 fdisk_warnx(cxt, _("Partition #%u out of range (maximal end is %"PRIu64" sectors)"),
2497 i + 1, last_usable - 1ULL);
2498 rc = -EINVAL;
2499 }
2500 }
2501 return rc;
2502 }
2503
2504 /**
2505 * fdisk_gpt_set_npartitions:
2506 * @cxt: context
2507 * @entries: new size
2508 *
2509 * Elarge GPT entries array if possible. The function check if an existing
2510 * partition does not overlap the entries array area. If yes, then it report
2511 * warning and returns -EINVAL.
2512 *
2513 * Returns: 0 on success, < 0 on error.
2514 * Since: 2.29
2515 */
2516 int fdisk_gpt_set_npartitions(struct fdisk_context *cxt, uint32_t entries)
2517 {
2518 struct fdisk_gpt_label *gpt;
2519 size_t old_size, new_size;
2520 uint32_t old;
2521 struct gpt_entry *ents;
2522 uint64_t first_usable, last_usable;
2523 int rc;
2524
2525 assert(cxt);
2526 assert(cxt->label);
2527 assert(fdisk_is_label(cxt, GPT));
2528
2529 gpt = self_label(cxt);
2530
2531 old = le32_to_cpu(gpt->pheader->npartition_entries);
2532 if (old == entries)
2533 return 0; /* do nothing, say nothing */
2534
2535 /* calculate the size (bytes) of the entries array */
2536 new_size = entries * le32_to_cpu(gpt->pheader->sizeof_partition_entry);
2537 old_size = old * le32_to_cpu(gpt->pheader->sizeof_partition_entry);
2538
2539 /* calculate new range of usable LBAs */
2540 first_usable = (uint64_t) (new_size / cxt->sector_size) + 2ULL;
2541 last_usable = cxt->total_sectors - 2ULL - (uint64_t) (new_size / cxt->sector_size);
2542
2543 /* if expanding the table, first check that everything fits,
2544 * then allocate more memory and zero. */
2545 if (entries > old) {
2546 rc = gpt_check_table_overlap(cxt, first_usable, last_usable);
2547 if (rc)
2548 return rc;
2549 ents = realloc(gpt->ents, new_size);
2550 if (!ents) {
2551 fdisk_warnx(cxt, _("Cannot allocate memory!"));
2552 return -ENOMEM;
2553 }
2554 memset(ents + old, 0, new_size - old_size);
2555 gpt->ents = ents;
2556 }
2557
2558 /* everything's ok, apply the new size */
2559 gpt->pheader->npartition_entries = cpu_to_le32(entries);
2560 gpt->bheader->npartition_entries = cpu_to_le32(entries);
2561
2562 /* usable LBA addresses will have changed */
2563 fdisk_set_first_lba(cxt, first_usable);
2564 fdisk_set_last_lba(cxt, last_usable);
2565 gpt->pheader->first_usable_lba = cpu_to_le64(first_usable);
2566 gpt->bheader->first_usable_lba = cpu_to_le64(first_usable);
2567 gpt->pheader->last_usable_lba = cpu_to_le64(last_usable);
2568 gpt->bheader->last_usable_lba = cpu_to_le64(last_usable);
2569
2570
2571 /* The backup header must be recalculated */
2572 gpt_mknew_header_common(cxt, gpt->bheader, le64_to_cpu(gpt->pheader->alternative_lba));
2573
2574 /* CRCs will have changed */
2575 gpt_recompute_crc(gpt->pheader, gpt->ents);
2576 gpt_recompute_crc(gpt->bheader, gpt->ents);
2577
2578 fdisk_info(cxt, _("Partition table length changed from %"PRIu32" to %"PRIu64"."), old, entries);
2579
2580 fdisk_label_set_changed(cxt->label, 1);
2581 return 0;
2582 }
2583
2584 static int gpt_part_is_used(struct fdisk_context *cxt, size_t i)
2585 {
2586 struct fdisk_gpt_label *gpt;
2587 struct gpt_entry *e;
2588
2589 assert(cxt);
2590 assert(cxt->label);
2591 assert(fdisk_is_label(cxt, GPT));
2592
2593 gpt = self_label(cxt);
2594
2595 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2596 return 0;
2597 e = &gpt->ents[i];
2598
2599 return !partition_unused(e) || gpt_partition_start(e);
2600 }
2601
2602 /**
2603 * fdisk_gpt_is_hybrid:
2604 * @cxt: context
2605 *
2606 * The regular GPT contains PMBR (dummy protective MBR) where the protective
2607 * MBR does not address any partitions.
2608 *
2609 * Hybrid GPT contains regular MBR where this partition table addresses the
2610 * same partitions as GPT. It's recommended to not use hybrid GPT due to MBR
2611 * limits.
2612 *
2613 * The libfdisk does not provide functionality to sync GPT and MBR, you have to
2614 * directly access and modify (P)MBR (see fdisk_new_nested_context()).
2615 *
2616 * Returns: 1 if partition table detected as hybrid otherwise return 0
2617 */
2618 int fdisk_gpt_is_hybrid(struct fdisk_context *cxt)
2619 {
2620 assert(cxt);
2621 return valid_pmbr(cxt) == GPT_MBR_HYBRID;
2622 }
2623
2624 /**
2625 * fdisk_gpt_get_partition_attrs:
2626 * @cxt: context
2627 * @partnum: partition number
2628 * @attrs: GPT partition attributes
2629 *
2630 * Sets @attrs for the given partition
2631 *
2632 * Returns: 0 on success, <0 on error.
2633 */
2634 int fdisk_gpt_get_partition_attrs(
2635 struct fdisk_context *cxt,
2636 size_t partnum,
2637 uint64_t *attrs)
2638 {
2639 struct fdisk_gpt_label *gpt;
2640
2641 assert(cxt);
2642 assert(cxt->label);
2643 assert(fdisk_is_label(cxt, GPT));
2644
2645 gpt = self_label(cxt);
2646
2647 if ((uint32_t) partnum >= le32_to_cpu(gpt->pheader->npartition_entries))
2648 return -EINVAL;
2649
2650 *attrs = le64_to_cpu(gpt->ents[partnum].attrs);
2651 return 0;
2652 }
2653
2654 /**
2655 * fdisk_gpt_set_partition_attrs:
2656 * @cxt: context
2657 * @partnum: partition number
2658 * @attrs: GPT partition attributes
2659 *
2660 * Sets the GPT partition attributes field to @attrs.
2661 *
2662 * Returns: 0 on success, <0 on error.
2663 */
2664 int fdisk_gpt_set_partition_attrs(
2665 struct fdisk_context *cxt,
2666 size_t partnum,
2667 uint64_t attrs)
2668 {
2669 struct fdisk_gpt_label *gpt;
2670
2671 assert(cxt);
2672 assert(cxt->label);
2673 assert(fdisk_is_label(cxt, GPT));
2674
2675 DBG(LABEL, ul_debug("GPT entry attributes change requested partno=%zu", partnum));
2676 gpt = self_label(cxt);
2677
2678 if ((uint32_t) partnum >= le32_to_cpu(gpt->pheader->npartition_entries))
2679 return -EINVAL;
2680
2681 gpt->ents[partnum].attrs = cpu_to_le64(attrs);
2682 fdisk_info(cxt, _("The attributes on partition %zu changed to 0x%016" PRIx64 "."),
2683 partnum + 1, attrs);
2684
2685 gpt_recompute_crc(gpt->pheader, gpt->ents);
2686 gpt_recompute_crc(gpt->bheader, gpt->ents);
2687 fdisk_label_set_changed(cxt->label, 1);
2688 return 0;
2689 }
2690
2691 static int gpt_toggle_partition_flag(
2692 struct fdisk_context *cxt,
2693 size_t i,
2694 unsigned long flag)
2695 {
2696 struct fdisk_gpt_label *gpt;
2697 uint64_t attrs;
2698 uintmax_t tmp;
2699 char *bits;
2700 const char *name = NULL;
2701 int bit = -1, rc;
2702
2703 assert(cxt);
2704 assert(cxt->label);
2705 assert(fdisk_is_label(cxt, GPT));
2706
2707 DBG(LABEL, ul_debug("GPT entry attribute change requested partno=%zu", i));
2708 gpt = self_label(cxt);
2709
2710 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2711 return -EINVAL;
2712
2713 attrs = gpt->ents[i].attrs;
2714 bits = (char *) &attrs;
2715
2716 switch (flag) {
2717 case GPT_FLAG_REQUIRED:
2718 bit = GPT_ATTRBIT_REQ;
2719 name = GPT_ATTRSTR_REQ;
2720 break;
2721 case GPT_FLAG_NOBLOCK:
2722 bit = GPT_ATTRBIT_NOBLOCK;
2723 name = GPT_ATTRSTR_NOBLOCK;
2724 break;
2725 case GPT_FLAG_LEGACYBOOT:
2726 bit = GPT_ATTRBIT_LEGACY;
2727 name = GPT_ATTRSTR_LEGACY;
2728 break;
2729 case GPT_FLAG_GUIDSPECIFIC:
2730 rc = fdisk_ask_number(cxt, 48, 48, 63, _("Enter GUID specific bit"), &tmp);
2731 if (rc)
2732 return rc;
2733 bit = tmp;
2734 break;
2735 default:
2736 /* already specified PT_FLAG_GUIDSPECIFIC bit */
2737 if (flag >= 48 && flag <= 63) {
2738 bit = flag;
2739 flag = GPT_FLAG_GUIDSPECIFIC;
2740 }
2741 break;
2742 }
2743
2744 if (bit < 0) {
2745 fdisk_warnx(cxt, _("failed to toggle unsupported bit %lu"), flag);
2746 return -EINVAL;
2747 }
2748
2749 if (!isset(bits, bit))
2750 setbit(bits, bit);
2751 else
2752 clrbit(bits, bit);
2753
2754 gpt->ents[i].attrs = attrs;
2755
2756 if (flag == GPT_FLAG_GUIDSPECIFIC)
2757 fdisk_info(cxt, isset(bits, bit) ?
2758 _("The GUID specific bit %d on partition %zu is enabled now.") :
2759 _("The GUID specific bit %d on partition %zu is disabled now."),
2760 bit, i + 1);
2761 else
2762 fdisk_info(cxt, isset(bits, bit) ?
2763 _("The %s flag on partition %zu is enabled now.") :
2764 _("The %s flag on partition %zu is disabled now."),
2765 name, i + 1);
2766
2767 gpt_recompute_crc(gpt->pheader, gpt->ents);
2768 gpt_recompute_crc(gpt->bheader, gpt->ents);
2769 fdisk_label_set_changed(cxt->label, 1);
2770 return 0;
2771 }
2772
2773 static int gpt_entry_cmp_start(const void *a, const void *b)
2774 {
2775 struct gpt_entry *ae = (struct gpt_entry *) a,
2776 *be = (struct gpt_entry *) b;
2777 int au = partition_unused(ae),
2778 bu = partition_unused(be);
2779
2780 if (au && bu)
2781 return 0;
2782 if (au)
2783 return 1;
2784 if (bu)
2785 return -1;
2786
2787 return cmp_numbers(gpt_partition_start(ae), gpt_partition_start(be));
2788 }
2789
2790 /* sort partition by start sector */
2791 static int gpt_reorder(struct fdisk_context *cxt)
2792 {
2793 struct fdisk_gpt_label *gpt;
2794 size_t i, nparts, mess;
2795
2796 assert(cxt);
2797 assert(cxt->label);
2798 assert(fdisk_is_label(cxt, GPT));
2799
2800 gpt = self_label(cxt);
2801 nparts = le32_to_cpu(gpt->pheader->npartition_entries);
2802
2803 for (i = 0, mess = 0; mess == 0 && i + 1 < nparts; i++)
2804 mess = gpt_entry_cmp_start(
2805 (const void *) &gpt->ents[i],
2806 (const void *) &gpt->ents[i + 1]) > 0;
2807
2808 if (!mess) {
2809 fdisk_info(cxt, _("Nothing to do. Ordering is correct already."));
2810 return 1;
2811 }
2812
2813 qsort(gpt->ents, nparts, sizeof(struct gpt_entry),
2814 gpt_entry_cmp_start);
2815
2816 gpt_recompute_crc(gpt->pheader, gpt->ents);
2817 gpt_recompute_crc(gpt->bheader, gpt->ents);
2818 fdisk_label_set_changed(cxt->label, 1);
2819
2820 return 0;
2821 }
2822
2823 static int gpt_reset_alignment(struct fdisk_context *cxt)
2824 {
2825 struct fdisk_gpt_label *gpt;
2826 struct gpt_header *h;
2827
2828 assert(cxt);
2829 assert(cxt->label);
2830 assert(fdisk_is_label(cxt, GPT));
2831
2832 gpt = self_label(cxt);
2833 h = gpt ? gpt->pheader : NULL;
2834
2835 if (h) {
2836 /* always follow existing table */
2837 cxt->first_lba = le64_to_cpu(h->first_usable_lba);
2838 cxt->last_lba = le64_to_cpu(h->last_usable_lba);
2839 } else {
2840 /* estimate ranges for GPT */
2841 uint64_t first, last;
2842
2843 count_first_last_lba(cxt, &first, &last);
2844
2845 if (cxt->first_lba < first)
2846 cxt->first_lba = first;
2847 if (cxt->last_lba > last)
2848 cxt->last_lba = last;
2849 }
2850
2851 return 0;
2852 }
2853 /*
2854 * Deinitialize fdisk-specific variables
2855 */
2856 static void gpt_deinit(struct fdisk_label *lb)
2857 {
2858 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
2859
2860 if (!gpt)
2861 return;
2862
2863 free(gpt->ents);
2864 free(gpt->pheader);
2865 free(gpt->bheader);
2866
2867 gpt->ents = NULL;
2868 gpt->pheader = NULL;
2869 gpt->bheader = NULL;
2870 }
2871
2872 static const struct fdisk_label_operations gpt_operations =
2873 {
2874 .probe = gpt_probe_label,
2875 .write = gpt_write_disklabel,
2876 .verify = gpt_verify_disklabel,
2877 .create = gpt_create_disklabel,
2878 .locate = gpt_locate_disklabel,
2879 .get_item = gpt_get_disklabel_item,
2880 .set_id = gpt_set_disklabel_id,
2881
2882 .get_part = gpt_get_partition,
2883 .set_part = gpt_set_partition,
2884 .add_part = gpt_add_partition,
2885 .del_part = gpt_delete_partition,
2886 .reorder = gpt_reorder,
2887
2888 .part_is_used = gpt_part_is_used,
2889 .part_toggle_flag = gpt_toggle_partition_flag,
2890
2891 .deinit = gpt_deinit,
2892
2893 .reset_alignment = gpt_reset_alignment
2894 };
2895
2896 static const struct fdisk_field gpt_fields[] =
2897 {
2898 /* basic */
2899 { FDISK_FIELD_DEVICE, N_("Device"), 10, 0 },
2900 { FDISK_FIELD_START, N_("Start"), 5, FDISK_FIELDFL_NUMBER },
2901 { FDISK_FIELD_END, N_("End"), 5, FDISK_FIELDFL_NUMBER },
2902 { FDISK_FIELD_SECTORS, N_("Sectors"), 5, FDISK_FIELDFL_NUMBER },
2903 { FDISK_FIELD_SIZE, N_("Size"), 5, FDISK_FIELDFL_NUMBER | FDISK_FIELDFL_EYECANDY },
2904 { FDISK_FIELD_TYPE, N_("Type"), 0.1, FDISK_FIELDFL_EYECANDY },
2905 /* expert */
2906 { FDISK_FIELD_TYPEID, N_("Type-UUID"), 36, FDISK_FIELDFL_DETAIL },
2907 { FDISK_FIELD_UUID, N_("UUID"), 36, FDISK_FIELDFL_DETAIL },
2908 { FDISK_FIELD_NAME, N_("Name"), 0.2, FDISK_FIELDFL_DETAIL },
2909 { FDISK_FIELD_ATTR, N_("Attrs"), 0, FDISK_FIELDFL_DETAIL }
2910 };
2911
2912 /*
2913 * allocates GPT in-memory stuff
2914 */
2915 struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt)
2916 {
2917 struct fdisk_label *lb;
2918 struct fdisk_gpt_label *gpt;
2919
2920 assert(cxt);
2921
2922 gpt = calloc(1, sizeof(*gpt));
2923 if (!gpt)
2924 return NULL;
2925
2926 /* initialize generic part of the driver */
2927 lb = (struct fdisk_label *) gpt;
2928 lb->name = "gpt";
2929 lb->id = FDISK_DISKLABEL_GPT;
2930 lb->op = &gpt_operations;
2931 lb->parttypes = gpt_parttypes;
2932 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
2933
2934 lb->fields = gpt_fields;
2935 lb->nfields = ARRAY_SIZE(gpt_fields);
2936
2937 return lb;
2938 }
2939
2940 #ifdef TEST_PROGRAM
2941 static int test_getattr(struct fdisk_test *ts, int argc, char *argv[])
2942 {
2943 const char *disk = argv[1];
2944 size_t part = strtoul(argv[2], NULL, 0) - 1;
2945 struct fdisk_context *cxt;
2946 uint64_t atters = 0;
2947
2948 cxt = fdisk_new_context();
2949 fdisk_assign_device(cxt, disk, 1);
2950
2951 if (!fdisk_is_label(cxt, GPT))
2952 return EXIT_FAILURE;
2953
2954 if (fdisk_gpt_get_partition_attrs(cxt, part, &atters))
2955 return EXIT_FAILURE;
2956
2957 printf("%s: 0x%016" PRIx64 "\n", argv[2], atters);
2958
2959 fdisk_unref_context(cxt);
2960 return 0;
2961 }
2962
2963 static int test_setattr(struct fdisk_test *ts, int argc, char *argv[])
2964 {
2965 const char *disk = argv[1];
2966 size_t part = strtoul(argv[2], NULL, 0) - 1;
2967 uint64_t atters = strtoull(argv[3], NULL, 0);
2968 struct fdisk_context *cxt;
2969
2970 cxt = fdisk_new_context();
2971 fdisk_assign_device(cxt, disk, 0);
2972
2973 if (!fdisk_is_label(cxt, GPT))
2974 return EXIT_FAILURE;
2975
2976 if (fdisk_gpt_set_partition_attrs(cxt, part, atters))
2977 return EXIT_FAILURE;
2978
2979 if (fdisk_write_disklabel(cxt))
2980 return EXIT_FAILURE;
2981
2982 fdisk_unref_context(cxt);
2983 return 0;
2984 }
2985
2986 int main(int argc, char *argv[])
2987 {
2988 struct fdisk_test tss[] = {
2989 { "--getattr", test_getattr, "<disk> <partition> print attributes" },
2990 { "--setattr", test_setattr, "<disk> <partition> <value> set attributes" },
2991 { NULL }
2992 };
2993
2994 return fdisk_run_test(tss, argc, argv);
2995 }
2996
2997 #endif