]> git.ipfire.org Git - thirdparty/util-linux.git/blob - libfdisk/src/gpt.c
libfdisk: (gpt) initialize last_lba, cleanup pa->{start,size} usage
[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
31 #define GPT_HEADER_SIGNATURE 0x5452415020494645LL /* EFI PART */
32 #define GPT_HEADER_REVISION_V1_02 0x00010200
33 #define GPT_HEADER_REVISION_V1_00 0x00010000
34 #define GPT_HEADER_REVISION_V0_99 0x00009900
35 #define GPT_HEADER_MINSZ 92 /* bytes */
36
37 #define GPT_PMBR_LBA 0
38 #define GPT_MBR_PROTECTIVE 1
39 #define GPT_MBR_HYBRID 2
40
41 #define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001
42
43 #define EFI_PMBR_OSTYPE 0xEE
44 #define MSDOS_MBR_SIGNATURE 0xAA55
45 #define GPT_PART_NAME_LEN (72 / sizeof(uint16_t))
46 #define GPT_NPARTITIONS 128
47
48 /* Globally unique identifier */
49 struct gpt_guid {
50 uint32_t time_low;
51 uint16_t time_mid;
52 uint16_t time_hi_and_version;
53 uint8_t clock_seq_hi;
54 uint8_t clock_seq_low;
55 uint8_t node[6];
56 };
57
58
59 /* only checking that the GUID is 0 is enough to verify an empty partition. */
60 #define GPT_UNUSED_ENTRY_GUID \
61 ((struct gpt_guid) { 0x00000000, 0x0000, 0x0000, 0x00, 0x00, \
62 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }})
63
64 /* Linux native partition type */
65 #define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
66
67 /*
68 * Attribute bits
69 */
70 struct gpt_attr {
71 uint64_t required_to_function:1;
72 uint64_t no_blockio_protocol:1;
73 uint64_t legacy_bios_bootable:1;
74 uint64_t reserved:45;
75 uint64_t guid_secific:16;
76 } __attribute__ ((packed));
77
78
79
80
81 /* The GPT Partition entry array contains an array of GPT entries. */
82 struct gpt_entry {
83 struct gpt_guid type; /* purpose and type of the partition */
84 struct gpt_guid partition_guid;
85 uint64_t lba_start;
86 uint64_t lba_end;
87 struct gpt_attr attr;
88 uint16_t name[GPT_PART_NAME_LEN];
89 } __attribute__ ((packed));
90
91 /* GPT header */
92 struct gpt_header {
93 uint64_t signature; /* header identification */
94 uint32_t revision; /* header version */
95 uint32_t size; /* in bytes */
96 uint32_t crc32; /* header CRC checksum */
97 uint32_t reserved1; /* must be 0 */
98 uint64_t my_lba; /* LBA that contains this struct (LBA 1) */
99 uint64_t alternative_lba; /* backup GPT header */
100 uint64_t first_usable_lba; /* first usable logical block for partitions */
101 uint64_t last_usable_lba; /* last usable logical block for partitions */
102 struct gpt_guid disk_guid; /* unique disk identifier */
103 uint64_t partition_entry_lba; /* stat LBA of the partition entry array */
104 uint32_t npartition_entries; /* total partition entries - normally 128 */
105 uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
106 uint32_t partition_entry_array_crc32; /* partition CRC checksum */
107 uint8_t reserved2[512 - 92]; /* must be 0 */
108 } __attribute__ ((packed));
109
110 struct gpt_record {
111 uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
112 uint8_t start_head; /* unused by EFI, pt start in CHS */
113 uint8_t start_sector; /* unused by EFI, pt start in CHS */
114 uint8_t start_track;
115 uint8_t os_type; /* EFI and legacy non-EFI OS types */
116 uint8_t end_head; /* unused by EFI, pt end in CHS */
117 uint8_t end_sector; /* unused by EFI, pt end in CHS */
118 uint8_t end_track; /* unused by EFI, pt end in CHS */
119 uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
120 uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
121 } __attribute__ ((packed));
122
123 /* Protected MBR and legacy MBR share same structure */
124 struct gpt_legacy_mbr {
125 uint8_t boot_code[440];
126 uint32_t unique_mbr_signature;
127 uint16_t unknown;
128 struct gpt_record partition_record[4];
129 uint16_t signature;
130 } __attribute__ ((packed));
131
132 /*
133 * Here be dragons!
134 * See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
135 */
136 #define DEF_GUID(_u, _n) \
137 { \
138 .typestr = (_u), \
139 .name = (_n), \
140 }
141
142 static struct fdisk_parttype gpt_parttypes[] =
143 {
144 /* Generic OS */
145 DEF_GUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", N_("EFI System")),
146
147 DEF_GUID("024DEE41-33E7-11D3-9D69-0008C781F39F", N_("MBR partition scheme")),
148 DEF_GUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593", N_("Intel Fast Flash")),
149
150 /* Hah!IdontneedEFI */
151 DEF_GUID("21686148-6449-6E6F-744E-656564454649", N_("BIOS boot partition")),
152
153 /* Windows */
154 DEF_GUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE", N_("Microsoft reserved")),
155 DEF_GUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", N_("Microsoft basic data")),
156 DEF_GUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3", N_("Microsoft LDM metadata")),
157 DEF_GUID("AF9B60A0-1431-4F62-BC68-3311714A69AD", N_("Microsoft LDM data")),
158 DEF_GUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC", N_("Windows recovery environment")),
159 DEF_GUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174", N_("IBM General Parallel Fs")),
160
161 /* HP-UX */
162 DEF_GUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000", N_("HP-UX data partition")),
163 DEF_GUID("E2A1E728-32E3-11D6-A682-7B03A0000000", N_("HP-UX service partition")),
164
165 /* Linux */
166 DEF_GUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4", N_("Linux filesystem")),
167 DEF_GUID("A19D880F-05FC-4D3B-A006-743F0F84911E", N_("Linux RAID")),
168 DEF_GUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", N_("Linux swap")),
169 DEF_GUID("E6D6D379-F507-44C2-A23C-238F2A3DF928", N_("Linux LVM")),
170 DEF_GUID("8DA63339-0007-60C0-C436-083AC8230908", N_("Linux reserved")),
171 DEF_GUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915", N_("Linux /home partition")),
172
173 /* FreeBSD */
174 DEF_GUID("516E7CB4-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD data")),
175 DEF_GUID("83BD6B9D-7F41-11DC-BE0B-001560B84F0F", N_("FreeBSD boot")),
176 DEF_GUID("516E7CB5-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD swap")),
177 DEF_GUID("516E7CB6-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD UFS")),
178 DEF_GUID("516E7CBA-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD ZFS")),
179 DEF_GUID("516E7CB8-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD Vinum")),
180
181 /* Apple OSX */
182 DEF_GUID("48465300-0000-11AA-AA11-00306543ECAC", N_("Apple HFS/HFS+")),
183 DEF_GUID("55465300-0000-11AA-AA11-00306543ECAC", N_("Apple UFS")),
184 DEF_GUID("52414944-0000-11AA-AA11-00306543ECAC", N_("Apple RAID")),
185 DEF_GUID("52414944-5F4F-11AA-AA11-00306543ECAC", N_("Apple RAID offline")),
186 DEF_GUID("426F6F74-0000-11AA-AA11-00306543ECAC", N_("Apple boot")),
187 DEF_GUID("4C616265-6C00-11AA-AA11-00306543ECAC", N_("Apple label")),
188 DEF_GUID("5265636F-7665-11AA-AA11-00306543ECAC", N_("Apple TV recovery")),
189 DEF_GUID("53746F72-6167-11AA-AA11-00306543ECAC", N_("Apple Core storage")),
190
191 /* Solaris */
192 DEF_GUID("6A82CB45-1DD2-11B2-99A6-080020736631", N_("Solaris boot")),
193 DEF_GUID("6A85CF4D-1DD2-11B2-99A6-080020736631", N_("Solaris root")),
194 /* same as Apple ZFS */
195 DEF_GUID("6A898CC3-1DD2-11B2-99A6-080020736631", N_("Solaris /usr & Apple ZFS")),
196 DEF_GUID("6A87C46F-1DD2-11B2-99A6-080020736631", N_("Solaris swap")),
197 DEF_GUID("6A8B642B-1DD2-11B2-99A6-080020736631", N_("Solaris backup")),
198 DEF_GUID("6A8EF2E9-1DD2-11B2-99A6-080020736631", N_("Solaris /var")),
199 DEF_GUID("6A90BA39-1DD2-11B2-99A6-080020736631", N_("Solaris /home")),
200 DEF_GUID("6A9283A5-1DD2-11B2-99A6-080020736631", N_("Solaris alternate sector")),
201 DEF_GUID("6A945A3B-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 1")),
202 DEF_GUID("6A9630D1-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 2")),
203 DEF_GUID("6A980767-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 3")),
204 DEF_GUID("6A96237F-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 4")),
205 DEF_GUID("6A8D2AC7-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 5")),
206
207 /* NetBSD */
208 DEF_GUID("49F48D32-B10E-11DC-B99B-0019D1879648", N_("NetBSD swap")),
209 DEF_GUID("49F48D5A-B10E-11DC-B99B-0019D1879648", N_("NetBSD FFS")),
210 DEF_GUID("49F48D82-B10E-11DC-B99B-0019D1879648", N_("NetBSD LFS")),
211 DEF_GUID("2DB519C4-B10E-11DC-B99B-0019D1879648", N_("NetBSD concatenated")),
212 DEF_GUID("2DB519EC-B10E-11DC-B99B-0019D1879648", N_("NetBSD encrypted")),
213 DEF_GUID("49F48DAA-B10E-11DC-B99B-0019D1879648", N_("NetBSD RAID")),
214
215 /* ChromeOS */
216 DEF_GUID("FE3A2A5D-4F32-41A7-B725-ACCC3285A309", N_("ChromeOS kernel")),
217 DEF_GUID("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC", N_("ChromeOS root fs")),
218 DEF_GUID("2E0A753D-9E48-43B0-8337-B15192CB1B5E", N_("ChromeOS reserved")),
219
220 /* MidnightBSD */
221 DEF_GUID("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD data")),
222 DEF_GUID("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD boot")),
223 DEF_GUID("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD swap")),
224 DEF_GUID("0394Ef8B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD UFS")),
225 DEF_GUID("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD ZFS")),
226 DEF_GUID("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD Vinum")),
227 };
228
229 /* gpt_entry macros */
230 #define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
231 #define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
232
233 /*
234 * in-memory fdisk GPT stuff
235 */
236 struct fdisk_gpt_label {
237 struct fdisk_label head; /* generic part */
238
239 /* gpt specific part */
240 struct gpt_header *pheader; /* primary header */
241 struct gpt_header *bheader; /* backup header */
242 struct gpt_entry *ents; /* entries (partitions) */
243 };
244
245 static void gpt_deinit(struct fdisk_label *lb);
246
247 static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
248 {
249 return (struct fdisk_gpt_label *) cxt->label;
250 }
251
252 /*
253 * Returns the partition length, or 0 if end is before beginning.
254 */
255 static uint64_t gpt_partition_size(const struct gpt_entry *e)
256 {
257 uint64_t start = gpt_partition_start(e);
258 uint64_t end = gpt_partition_end(e);
259
260 return start > end ? 0 : end - start + 1ULL;
261 }
262
263 #ifdef CONFIG_LIBFDISK_DEBUG
264 /* prints UUID in the real byte order! */
265 static void dbgprint_uuid(const char *mesg, struct gpt_guid *guid)
266 {
267 const unsigned char *uuid = (unsigned char *) guid;
268
269 fprintf(stderr, "%s: "
270 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
271 mesg,
272 uuid[0], uuid[1], uuid[2], uuid[3],
273 uuid[4], uuid[5],
274 uuid[6], uuid[7],
275 uuid[8], uuid[9],
276 uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
277 }
278 #endif
279
280 /*
281 * UUID is traditionally 16 byte big-endian array, except Intel EFI
282 * specification where the UUID is a structure of little-endian fields.
283 */
284 static void swap_efi_guid(struct gpt_guid *uid)
285 {
286 uid->time_low = swab32(uid->time_low);
287 uid->time_mid = swab16(uid->time_mid);
288 uid->time_hi_and_version = swab16(uid->time_hi_and_version);
289 }
290
291 static int string_to_guid(const char *in, struct gpt_guid *guid)
292 {
293 if (uuid_parse(in, (unsigned char *) guid)) /* BE */
294 return -1;
295 swap_efi_guid(guid); /* LE */
296 return 0;
297 }
298
299 static char *guid_to_string(const struct gpt_guid *guid, char *out)
300 {
301 struct gpt_guid u = *guid; /* LE */
302
303 swap_efi_guid(&u); /* BE */
304 uuid_unparse_upper((unsigned char *) &u, out);
305
306 return out;
307 }
308
309 static struct fdisk_parttype *gpt_partition_parttype(
310 struct fdisk_context *cxt,
311 const struct gpt_entry *e)
312 {
313 struct fdisk_parttype *t;
314 char str[37];
315
316 guid_to_string(&e->type, str);
317 t = fdisk_get_parttype_from_string(cxt, str);
318 return t ? : fdisk_new_unknown_parttype(0, str);
319 }
320
321
322
323 static const char *gpt_get_header_revstr(struct gpt_header *header)
324 {
325 if (!header)
326 goto unknown;
327
328 switch (header->revision) {
329 case GPT_HEADER_REVISION_V1_02:
330 return "1.2";
331 case GPT_HEADER_REVISION_V1_00:
332 return "1.0";
333 case GPT_HEADER_REVISION_V0_99:
334 return "0.99";
335 default:
336 goto unknown;
337 }
338
339 unknown:
340 return "unknown";
341 }
342
343 static inline int partition_unused(const struct gpt_entry *e)
344 {
345 return !memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
346 sizeof(struct gpt_guid));
347 }
348
349 /*
350 * Builds a clean new valid protective MBR - will wipe out any existing data.
351 * Returns 0 on success, otherwise < 0 on error.
352 */
353 static int gpt_mknew_pmbr(struct fdisk_context *cxt)
354 {
355 struct gpt_legacy_mbr *pmbr = NULL;
356
357 if (!cxt || !cxt->firstsector)
358 return -ENOSYS;
359
360 fdisk_zeroize_firstsector(cxt);
361
362 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
363
364 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
365 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
366 pmbr->partition_record[0].start_sector = 1;
367 pmbr->partition_record[0].end_head = 0xFE;
368 pmbr->partition_record[0].end_sector = 0xFF;
369 pmbr->partition_record[0].end_track = 0xFF;
370 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
371 pmbr->partition_record[0].size_in_lba =
372 cpu_to_le32(min((uint32_t) cxt->total_sectors - 1, 0xFFFFFFFF));
373
374 return 0;
375 }
376
377 /* some universal differences between the headers */
378 static void gpt_mknew_header_common(struct fdisk_context *cxt,
379 struct gpt_header *header, uint64_t lba)
380 {
381 if (!cxt || !header)
382 return;
383
384 header->my_lba = cpu_to_le64(lba);
385
386 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) { /* primary */
387 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1);
388 header->partition_entry_lba = cpu_to_le64(2);
389 } else { /* backup */
390 uint64_t esz = le32_to_cpu(header->npartition_entries) * sizeof(struct gpt_entry);
391 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
392
393 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
394 header->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1 - esects);
395 }
396 }
397
398 /*
399 * Builds a new GPT header (at sector lba) from a backup header2.
400 * If building a primary header, then backup is the secondary, and vice versa.
401 *
402 * Always pass a new (zeroized) header to build upon as we don't
403 * explicitly zero-set some values such as CRCs and reserved.
404 *
405 * Returns 0 on success, otherwise < 0 on error.
406 */
407 static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
408 struct gpt_header *header,
409 uint64_t lba,
410 struct gpt_header *header2)
411 {
412 if (!cxt || !header || !header2)
413 return -ENOSYS;
414
415 header->signature = header2->signature;
416 header->revision = header2->revision;
417 header->size = header2->size;
418 header->npartition_entries = header2->npartition_entries;
419 header->sizeof_partition_entry = header2->sizeof_partition_entry;
420 header->first_usable_lba = header2->first_usable_lba;
421 header->last_usable_lba = header2->last_usable_lba;
422
423 memcpy(&header->disk_guid,
424 &header2->disk_guid, sizeof(header2->disk_guid));
425 gpt_mknew_header_common(cxt, header, lba);
426
427 return 0;
428 }
429
430 static struct gpt_header *gpt_copy_header(struct fdisk_context *cxt,
431 struct gpt_header *src)
432 {
433 struct gpt_header *res;
434
435 if (!cxt || !src)
436 return NULL;
437
438 res = calloc(1, sizeof(*res));
439 if (!res) {
440 fdisk_warn(cxt, _("failed to allocate GPT header"));
441 return NULL;
442 }
443
444 res->my_lba = src->alternative_lba;
445 res->alternative_lba = src->my_lba;
446
447 res->signature = src->signature;
448 res->revision = src->revision;
449 res->size = src->size;
450 res->npartition_entries = src->npartition_entries;
451 res->sizeof_partition_entry = src->sizeof_partition_entry;
452 res->first_usable_lba = src->first_usable_lba;
453 res->last_usable_lba = src->last_usable_lba;
454
455 memcpy(&res->disk_guid, &src->disk_guid, sizeof(src->disk_guid));
456
457
458 if (res->my_lba == GPT_PRIMARY_PARTITION_TABLE_LBA)
459 res->partition_entry_lba = cpu_to_le64(2);
460 else {
461 uint64_t esz = le32_to_cpu(src->npartition_entries) * sizeof(struct gpt_entry);
462 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
463
464 res->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1 - esects);
465 }
466
467 return res;
468 }
469
470 static void count_first_last_lba(struct fdisk_context *cxt,
471 uint64_t *first, uint64_t *last)
472 {
473 uint64_t esz = 0;
474
475 assert(cxt);
476
477 esz = sizeof(struct gpt_entry) * GPT_NPARTITIONS / cxt->sector_size;
478 *last = cxt->total_sectors - 2 - esz;
479 *first = esz + 2;
480
481 if (*first < cxt->first_lba && cxt->first_lba < *last)
482 /* Align according to topology */
483 *first = cxt->first_lba;
484 }
485
486 /*
487 * Builds a clean new GPT header (currently under revision 1.0).
488 *
489 * Always pass a new (zeroized) header to build upon as we don't
490 * explicitly zero-set some values such as CRCs and reserved.
491 *
492 * Returns 0 on success, otherwise < 0 on error.
493 */
494 static int gpt_mknew_header(struct fdisk_context *cxt,
495 struct gpt_header *header, uint64_t lba)
496 {
497 uint64_t first, last;
498
499 if (!cxt || !header)
500 return -ENOSYS;
501
502 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
503 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
504 header->size = cpu_to_le32(sizeof(struct gpt_header));
505
506 /*
507 * 128 partitions is the default. It can go behond this, however,
508 * we're creating a de facto header here, so no funny business.
509 */
510 header->npartition_entries = cpu_to_le32(GPT_NPARTITIONS);
511 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
512
513 count_first_last_lba(cxt, &first, &last);
514 header->first_usable_lba = cpu_to_le64(first);
515 header->last_usable_lba = cpu_to_le64(last);
516
517 gpt_mknew_header_common(cxt, header, lba);
518 uuid_generate_random((unsigned char *) &header->disk_guid);
519 swap_efi_guid(&header->disk_guid);
520
521 return 0;
522 }
523
524 /*
525 * Checks if there is a valid protective MBR partition table.
526 * Returns 0 if it is invalid or failure. Otherwise, return
527 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depeding on the detection.
528 */
529 static int valid_pmbr(struct fdisk_context *cxt)
530 {
531 int i, part = 0, ret = 0; /* invalid by default */
532 struct gpt_legacy_mbr *pmbr = NULL;
533 uint32_t sz_lba = 0;
534
535 if (!cxt->firstsector)
536 goto done;
537
538 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
539
540 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
541 goto done;
542
543 /* LBA of the GPT partition header */
544 if (pmbr->partition_record[0].starting_lba !=
545 cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
546 goto done;
547
548 /* seems like a valid MBR was found, check DOS primary partitions */
549 for (i = 0; i < 4; i++) {
550 if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
551 /*
552 * Ok, we at least know that there's a protective MBR,
553 * now check if there are other partition types for
554 * hybrid MBR.
555 */
556 part = i;
557 ret = GPT_MBR_PROTECTIVE;
558 goto check_hybrid;
559 }
560 }
561
562 if (ret != GPT_MBR_PROTECTIVE)
563 goto done;
564 check_hybrid:
565 for (i = 0 ; i < 4; i++) {
566 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
567 (pmbr->partition_record[i].os_type != 0x00))
568 ret = GPT_MBR_HYBRID;
569 }
570
571 /*
572 * Protective MBRs take up the lesser of the whole disk
573 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
574 * Some partitioning programs, nonetheless, choose to set
575 * the size to the maximum 32-bit limitation, disregarding
576 * the disk size.
577 *
578 * Hybrid MBRs do not necessarily comply with this.
579 *
580 * Consider a bad value here to be a warning to support dd-ing
581 * an image from a smaller disk to a bigger disk.
582 */
583 if (ret == GPT_MBR_PROTECTIVE) {
584 sz_lba = le32_to_cpu(pmbr->partition_record[part].size_in_lba);
585 if (sz_lba != (uint32_t) cxt->total_sectors - 1 && sz_lba != 0xFFFFFFFF) {
586 fdisk_warnx(cxt, _("GPT PMBR size mismatch (%u != %u) "
587 "will be corrected by w(rite)."),
588 sz_lba,
589 (uint32_t) cxt->total_sectors - 1);
590 fdisk_label_set_changed(cxt->label, 1);
591 }
592 }
593 done:
594 return ret;
595 }
596
597 static uint64_t last_lba(struct fdisk_context *cxt)
598 {
599 struct stat s;
600
601 memset(&s, 0, sizeof(s));
602 if (fstat(cxt->dev_fd, &s) == -1) {
603 fdisk_warn(cxt, _("gpt: stat() failed"));
604 return 0;
605 }
606
607 if (S_ISBLK(s.st_mode))
608 return cxt->total_sectors - 1;
609 else if (S_ISREG(s.st_mode)) {
610 uint64_t sectors = s.st_size >> cxt->sector_size;
611 return (sectors / cxt->sector_size) - 1ULL;
612 } else
613 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
614 return 0;
615 }
616
617 static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
618 void *buffer, const size_t bytes)
619 {
620 off_t offset = lba * cxt->sector_size;
621
622 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
623 return -1;
624 return read(cxt->dev_fd, buffer, bytes) != bytes;
625 }
626
627
628 /* Returns the GPT entry array */
629 static struct gpt_entry *gpt_read_entries(struct fdisk_context *cxt,
630 struct gpt_header *header)
631 {
632 ssize_t sz;
633 struct gpt_entry *ret = NULL;
634 off_t offset;
635
636 assert(cxt);
637 assert(header);
638
639 sz = le32_to_cpu(header->npartition_entries) *
640 le32_to_cpu(header->sizeof_partition_entry);
641
642 ret = calloc(1, sz);
643 if (!ret)
644 return NULL;
645 offset = le64_to_cpu(header->partition_entry_lba) *
646 cxt->sector_size;
647
648 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
649 goto fail;
650 if (sz != read(cxt->dev_fd, ret, sz))
651 goto fail;
652
653 return ret;
654
655 fail:
656 free(ret);
657 return NULL;
658 }
659
660 static inline uint32_t count_crc32(const unsigned char *buf, size_t len)
661 {
662 return (crc32(~0L, buf, len) ^ ~0L);
663 }
664
665 /*
666 * Recompute header and partition array 32bit CRC checksums.
667 * This function does not fail - if there's corruption, then it
668 * will be reported when checksuming it again (ie: probing or verify).
669 */
670 static void gpt_recompute_crc(struct gpt_header *header, struct gpt_entry *ents)
671 {
672 uint32_t crc = 0;
673 size_t entry_sz = 0;
674
675 if (!header)
676 return;
677
678 /* header CRC */
679 header->crc32 = 0;
680 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
681 header->crc32 = cpu_to_le32(crc);
682
683 /* partition entry array CRC */
684 header->partition_entry_array_crc32 = 0;
685 entry_sz = le32_to_cpu(header->npartition_entries) *
686 le32_to_cpu(header->sizeof_partition_entry);
687
688 crc = count_crc32((unsigned char *) ents, entry_sz);
689 header->partition_entry_array_crc32 = cpu_to_le32(crc);
690 }
691
692 /*
693 * Compute the 32bit CRC checksum of the partition table header.
694 * Returns 1 if it is valid, otherwise 0.
695 */
696 static int gpt_check_header_crc(struct gpt_header *header, struct gpt_entry *ents)
697 {
698 uint32_t crc, orgcrc = le32_to_cpu(header->crc32);
699
700 header->crc32 = 0;
701 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
702 header->crc32 = cpu_to_le32(orgcrc);
703
704 if (crc == le32_to_cpu(header->crc32))
705 return 1;
706
707 /*
708 * If we have checksum mismatch it may be due to stale data,
709 * like a partition being added or deleted. Recompute the CRC again
710 * and make sure this is not the case.
711 */
712 if (ents) {
713 gpt_recompute_crc(header, ents);
714 orgcrc = le32_to_cpu(header->crc32);
715 header->crc32 = 0;
716 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
717 header->crc32 = cpu_to_le32(orgcrc);
718
719 return crc == le32_to_cpu(header->crc32);
720 }
721
722 return 0;
723 }
724
725 /*
726 * It initializes the partition entry array.
727 * Returns 1 if the checksum is valid, otherwise 0.
728 */
729 static int gpt_check_entryarr_crc(struct gpt_header *header,
730 struct gpt_entry *ents)
731 {
732 int ret = 0;
733 ssize_t entry_sz;
734 uint32_t crc;
735
736 if (!header || !ents)
737 goto done;
738
739 entry_sz = le32_to_cpu(header->npartition_entries) *
740 le32_to_cpu(header->sizeof_partition_entry);
741
742 if (!entry_sz)
743 goto done;
744
745 crc = count_crc32((unsigned char *) ents, entry_sz);
746 ret = (crc == le32_to_cpu(header->partition_entry_array_crc32));
747 done:
748 return ret;
749 }
750
751 static int gpt_check_lba_sanity(struct fdisk_context *cxt, struct gpt_header *header)
752 {
753 int ret = 0;
754 uint64_t lu, fu, lastlba = last_lba(cxt);
755
756 fu = le64_to_cpu(header->first_usable_lba);
757 lu = le64_to_cpu(header->last_usable_lba);
758
759 /* check if first and last usable LBA make sense */
760 if (lu < fu) {
761 DBG(LABEL, dbgprint("error: header last LBA is before first LBA"));
762 goto done;
763 }
764
765 /* check if first and last usable LBAs with the disk's last LBA */
766 if (fu > lastlba || lu > lastlba) {
767 DBG(LABEL, dbgprint("error: header LBAs are after the disk's last LBA"));
768 goto done;
769 }
770
771 /* the header has to be outside usable range */
772 if (fu < GPT_PRIMARY_PARTITION_TABLE_LBA &&
773 GPT_PRIMARY_PARTITION_TABLE_LBA < lu) {
774 DBG(LABEL, dbgprint("error: header outside of usable range"));
775 goto done;
776 }
777
778 ret = 1; /* sane */
779 done:
780 return ret;
781 }
782
783 /* Check if there is a valid header signature */
784 static int gpt_check_signature(struct gpt_header *header)
785 {
786 return header->signature == cpu_to_le64(GPT_HEADER_SIGNATURE);
787 }
788
789 /*
790 * Return the specified GPT Header, or NULL upon failure/invalid.
791 * Note that all tests must pass to ensure a valid header,
792 * we do not rely on only testing the signature for a valid probe.
793 */
794 static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
795 uint64_t lba,
796 struct gpt_entry **_ents)
797 {
798 struct gpt_header *header = NULL;
799 struct gpt_entry *ents = NULL;
800 uint32_t hsz;
801
802 if (!cxt)
803 return NULL;
804
805 header = calloc(1, sizeof(*header));
806 if (!header)
807 return NULL;
808
809 /* read and verify header */
810 if (read_lba(cxt, lba, header, sizeof(struct gpt_header)) != 0)
811 goto invalid;
812
813 if (!gpt_check_signature(header))
814 goto invalid;
815
816 if (!gpt_check_header_crc(header, NULL))
817 goto invalid;
818
819 /* read and verify entries */
820 ents = gpt_read_entries(cxt, header);
821 if (!ents)
822 goto invalid;
823
824 if (!gpt_check_entryarr_crc(header, ents))
825 goto invalid;
826
827 if (!gpt_check_lba_sanity(cxt, header))
828 goto invalid;
829
830 /* valid header must be at MyLBA */
831 if (le64_to_cpu(header->my_lba) != lba)
832 goto invalid;
833
834 /* make sure header size is between 92 and sector size bytes */
835 hsz = le32_to_cpu(header->size);
836 if (hsz < GPT_HEADER_MINSZ || hsz > cxt->sector_size)
837 goto invalid;
838
839 if (_ents)
840 *_ents = ents;
841 else
842 free(ents);
843
844 DBG(LABEL, dbgprint("found valid GPT Header on LBA %ju", lba));
845 return header;
846 invalid:
847 free(header);
848 free(ents);
849
850 DBG(LABEL, dbgprint("read GPT Header on LBA %ju failed", lba));
851 return NULL;
852 }
853
854
855 static int gpt_locate_disklabel(struct fdisk_context *cxt, int n,
856 const char **name, off_t *offset, size_t *size)
857 {
858 struct fdisk_gpt_label *gpt;
859
860 assert(cxt);
861
862 *name = NULL;
863 *offset = 0;
864 *size = 0;
865
866 switch (n) {
867 case 0:
868 *name = "PMBR";
869 *offset = 0;
870 *size = 512;
871 break;
872 case 1:
873 *name = _("GPT Header");
874 *offset = GPT_PRIMARY_PARTITION_TABLE_LBA * cxt->sector_size;
875 *size = sizeof(struct gpt_header);
876 break;
877 case 2:
878 *name = _("GPT Entries");
879 gpt = self_label(cxt);
880 *offset = le64_to_cpu(gpt->pheader->partition_entry_lba) * cxt->sector_size;
881 *size = le32_to_cpu(gpt->pheader->npartition_entries) *
882 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
883 break;
884 default:
885 return 1; /* no more chunks */
886 }
887
888 return 0;
889 }
890
891
892
893 /*
894 * Returns the number of partitions that are in use.
895 */
896 static unsigned partitions_in_use(struct gpt_header *header, struct gpt_entry *e)
897 {
898 uint32_t i, used = 0;
899
900 if (!header || ! e)
901 return 0;
902
903 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
904 if (!partition_unused(&e[i]))
905 used++;
906 return used;
907 }
908
909
910 /*
911 * Check if a partition is too big for the disk (sectors).
912 * Returns the faulting partition number, otherwise 0.
913 */
914 static uint32_t partition_check_too_big(struct gpt_header *header,
915 struct gpt_entry *e, uint64_t sectors)
916 {
917 uint32_t i;
918
919 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
920 if (partition_unused(&e[i]))
921 continue;
922 if (gpt_partition_end(&e[i]) >= sectors)
923 return i + 1;
924 }
925
926 return 0;
927 }
928
929 /*
930 * Check if a partition ends before it begins
931 * Returns the faulting partition number, otherwise 0.
932 */
933 static uint32_t partition_start_after_end(struct gpt_header *header, struct gpt_entry *e)
934 {
935 uint32_t i;
936
937 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
938 if (partition_unused(&e[i]))
939 continue;
940 if (gpt_partition_start(&e[i]) > gpt_partition_end(&e[i]))
941 return i + 1;
942 }
943
944 return 0;
945 }
946
947 /*
948 * Check if partition e1 overlaps with partition e2
949 */
950 static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
951 {
952 uint64_t start1 = gpt_partition_start(e1);
953 uint64_t end1 = gpt_partition_end(e1);
954 uint64_t start2 = gpt_partition_start(e2);
955 uint64_t end2 = gpt_partition_end(e2);
956
957 return (start1 && start2 && (start1 <= end2) != (end1 < start2));
958 }
959
960 /*
961 * Find any paritions that overlap.
962 */
963 static uint32_t partition_check_overlaps(struct gpt_header *header, struct gpt_entry *e)
964 {
965 uint32_t i, j;
966
967 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
968 for (j = 0; j < i; j++) {
969 if (partition_unused(&e[i]) ||
970 partition_unused(&e[j]))
971 continue;
972 if (partition_overlap(&e[i], &e[j])) {
973 DBG(LABEL, dbgprint("GPT partitions overlap detected [%u vs. %u]", i, j));
974 return i + 1;
975 }
976 }
977
978 return 0;
979 }
980
981 /*
982 * Find the first available block after the starting point; returns 0 if
983 * there are no available blocks left, or error. From gdisk.
984 */
985 static uint64_t find_first_available(struct gpt_header *header,
986 struct gpt_entry *e, uint64_t start)
987 {
988 uint64_t first;
989 uint32_t i, first_moved = 0;
990
991 uint64_t fu, lu;
992
993 if (!header || !e)
994 return 0;
995
996 fu = le64_to_cpu(header->first_usable_lba);
997 lu = le64_to_cpu(header->last_usable_lba);
998
999 /*
1000 * Begin from the specified starting point or from the first usable
1001 * LBA, whichever is greater...
1002 */
1003 first = start < fu ? fu : start;
1004
1005 /*
1006 * Now search through all partitions; if first is within an
1007 * existing partition, move it to the next sector after that
1008 * partition and repeat. If first was moved, set firstMoved
1009 * flag; repeat until firstMoved is not set, so as to catch
1010 * cases where partitions are out of sequential order....
1011 */
1012 do {
1013 first_moved = 0;
1014 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1015 if (partition_unused(&e[i]))
1016 continue;
1017 if (first < gpt_partition_start(&e[i]))
1018 continue;
1019 if (first <= gpt_partition_end(&e[i])) {
1020 first = gpt_partition_end(&e[i]) + 1;
1021 first_moved = 1;
1022 }
1023 }
1024 } while (first_moved == 1);
1025
1026 if (first > lu)
1027 first = 0;
1028
1029 return first;
1030 }
1031
1032
1033 /* Returns last available sector in the free space pointed to by start. From gdisk. */
1034 static uint64_t find_last_free(struct gpt_header *header,
1035 struct gpt_entry *e, uint64_t start)
1036 {
1037 uint32_t i;
1038 uint64_t nearest_start;
1039
1040 if (!header || !e)
1041 return 0;
1042
1043 nearest_start = le64_to_cpu(header->last_usable_lba);
1044
1045 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1046 uint64_t ps = gpt_partition_start(&e[i]);
1047
1048 if (nearest_start > ps && ps > start)
1049 nearest_start = ps - 1;
1050 }
1051
1052 return nearest_start;
1053 }
1054
1055 /* Returns the last free sector on the disk. From gdisk. */
1056 static uint64_t find_last_free_sector(struct gpt_header *header,
1057 struct gpt_entry *e)
1058 {
1059 uint32_t i, last_moved;
1060 uint64_t last = 0;
1061
1062 if (!header || !e)
1063 goto done;
1064
1065 /* start by assuming the last usable LBA is available */
1066 last = le64_to_cpu(header->last_usable_lba);
1067 do {
1068 last_moved = 0;
1069 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
1070 if ((last >= gpt_partition_start(&e[i])) &&
1071 (last <= gpt_partition_end(&e[i]))) {
1072 last = gpt_partition_start(&e[i]) - 1;
1073 last_moved = 1;
1074 }
1075 }
1076 } while (last_moved == 1);
1077 done:
1078 return last;
1079 }
1080
1081 /*
1082 * Finds the first available sector in the largest block of unallocated
1083 * space on the disk. Returns 0 if there are no available blocks left.
1084 * From gdisk.
1085 */
1086 static uint64_t find_first_in_largest(struct gpt_header *header, struct gpt_entry *e)
1087 {
1088 uint64_t start = 0, first_sect, last_sect;
1089 uint64_t segment_size, selected_size = 0, selected_segment = 0;
1090
1091 if (!header || !e)
1092 goto done;
1093
1094 do {
1095 first_sect = find_first_available(header, e, start);
1096 if (first_sect != 0) {
1097 last_sect = find_last_free(header, e, first_sect);
1098 segment_size = last_sect - first_sect + 1;
1099
1100 if (segment_size > selected_size) {
1101 selected_size = segment_size;
1102 selected_segment = first_sect;
1103 }
1104 start = last_sect + 1;
1105 }
1106 } while (first_sect != 0);
1107
1108 done:
1109 return selected_segment;
1110 }
1111
1112 /*
1113 * Find the total number of free sectors, the number of segments in which
1114 * they reside, and the size of the largest of those segments. From gdisk.
1115 */
1116 static uint64_t get_free_sectors(struct fdisk_context *cxt, struct gpt_header *header,
1117 struct gpt_entry *e, uint32_t *nsegments,
1118 uint64_t *largest_segment)
1119 {
1120 uint32_t num = 0;
1121 uint64_t first_sect, last_sect;
1122 uint64_t largest_seg = 0, segment_sz;
1123 uint64_t totfound = 0, start = 0; /* starting point for each search */
1124
1125 if (!cxt->total_sectors)
1126 goto done;
1127
1128 do {
1129 first_sect = find_first_available(header, e, start);
1130 if (first_sect) {
1131 last_sect = find_last_free(header, e, first_sect);
1132 segment_sz = last_sect - first_sect + 1;
1133
1134 if (segment_sz > largest_seg)
1135 largest_seg = segment_sz;
1136 totfound += segment_sz;
1137 num++;
1138 start = last_sect + 1;
1139 }
1140 } while (first_sect);
1141
1142 done:
1143 if (nsegments)
1144 *nsegments = num;
1145 if (largest_segment)
1146 *largest_segment = largest_seg;
1147
1148 return totfound;
1149 }
1150
1151 static int gpt_probe_label(struct fdisk_context *cxt)
1152 {
1153 int mbr_type;
1154 struct fdisk_gpt_label *gpt;
1155
1156 assert(cxt);
1157 assert(cxt->label);
1158 assert(fdisk_is_disklabel(cxt, GPT));
1159
1160 gpt = self_label(cxt);
1161
1162 /* TODO: it would be nice to support scenario when GPT headers are OK,
1163 * but PMBR is corrupt */
1164 mbr_type = valid_pmbr(cxt);
1165 if (!mbr_type)
1166 goto failed;
1167
1168 DBG(LABEL, dbgprint("found a %s MBR", mbr_type == GPT_MBR_PROTECTIVE ?
1169 "protective" : "hybrid"));
1170
1171 /* primary header */
1172 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1173 &gpt->ents);
1174
1175 if (gpt->pheader)
1176 /* primary OK, try backup from alternative LBA */
1177 gpt->bheader = gpt_read_header(cxt,
1178 le64_to_cpu(gpt->pheader->alternative_lba),
1179 NULL);
1180 else
1181 /* primary corrupted -- try last LBA */
1182 gpt->bheader = gpt_read_header(cxt, last_lba(cxt), &gpt->ents);
1183
1184 if (!gpt->pheader && !gpt->bheader)
1185 goto failed;
1186
1187 /* primary OK, backup corrupted -- recovery */
1188 if (gpt->pheader && !gpt->bheader) {
1189 fdisk_warnx(cxt, _("The backup GPT table is corrupt, but the "
1190 "primary appears OK, so that will be used."));
1191 gpt->bheader = gpt_copy_header(cxt, gpt->pheader);
1192 if (!gpt->bheader)
1193 goto failed;
1194 gpt_recompute_crc(gpt->bheader, gpt->ents);
1195
1196 /* primary corrupted, backup OK -- recovery */
1197 } else if (!gpt->pheader && gpt->bheader) {
1198 fdisk_warnx(cxt, _("The primary GPT table is corrupt, but the "
1199 "backup appears OK, so that will be used."));
1200 gpt->pheader = gpt_copy_header(cxt, gpt->bheader);
1201 if (!gpt->pheader)
1202 goto failed;
1203 gpt_recompute_crc(gpt->pheader, gpt->ents);
1204 }
1205
1206 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1207 cxt->label->nparts_cur = partitions_in_use(gpt->pheader, gpt->ents);
1208 return 1;
1209 failed:
1210 DBG(LABEL, dbgprint("GPT probe failed"));
1211 gpt_deinit(cxt->label);
1212 return 0;
1213 }
1214
1215 /*
1216 * Stolen from libblkid - can be removed once partition semantics
1217 * are added to the fdisk API.
1218 */
1219 static char *encode_to_utf8(unsigned char *src, size_t count)
1220 {
1221 uint16_t c;
1222 char *dest;
1223 size_t i, j, len = count;
1224
1225 dest = calloc(1, count);
1226 if (!dest)
1227 return NULL;
1228
1229 for (j = i = 0; i + 2 <= count; i += 2) {
1230 /* always little endian */
1231 c = (src[i+1] << 8) | src[i];
1232 if (c == 0) {
1233 dest[j] = '\0';
1234 break;
1235 } else if (c < 0x80) {
1236 if (j+1 >= len)
1237 break;
1238 dest[j++] = (uint8_t) c;
1239 } else if (c < 0x800) {
1240 if (j+2 >= len)
1241 break;
1242 dest[j++] = (uint8_t) (0xc0 | (c >> 6));
1243 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1244 } else {
1245 if (j+3 >= len)
1246 break;
1247 dest[j++] = (uint8_t) (0xe0 | (c >> 12));
1248 dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
1249 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1250 }
1251 }
1252 dest[j] = '\0';
1253
1254 return dest;
1255 }
1256
1257 /* convert GUID Specific attributes to string, result is a list of the enabled
1258 * bits (e.g. "60,62,63" for enabled bits 60, 62 and 63).
1259 *
1260 * Returns newly allocated string or NULL in case of error.
1261 *
1262 * see struct gpt_attr definition for more details.
1263 */
1264 static char *guid_attrs_to_string(struct gpt_attr *attr, char **res)
1265 {
1266 char *bits = (char *) attr, *end;
1267 size_t i, count = 0, len;
1268
1269 end = *res = calloc(1, 16 * 3 + 6); /* three bytes for one bit + \0 */
1270 if (!*res)
1271 return NULL;
1272
1273 for (i = 48; i < 64; i++) {
1274 if (!isset(bits, i))
1275 continue;
1276 count++;
1277 if (count > 1)
1278 len = snprintf(end, 4, ",%zu", i);
1279 else
1280 len = snprintf(end, 8, "GUID:%zu", i);
1281 end += len;
1282 }
1283
1284 return *res;
1285 }
1286
1287 static int gpt_get_partition(struct fdisk_context *cxt, size_t n,
1288 struct fdisk_partition *pa)
1289 {
1290 struct fdisk_gpt_label *gpt;
1291 struct gpt_entry *e;
1292 char u_str[37], *buf = NULL;
1293
1294 assert(cxt);
1295 assert(cxt->label);
1296 assert(fdisk_is_disklabel(cxt, GPT));
1297
1298 gpt = self_label(cxt);
1299
1300 if ((uint32_t) n >= le32_to_cpu(gpt->pheader->npartition_entries))
1301 return -EINVAL;
1302
1303 gpt = self_label(cxt);
1304 e = &gpt->ents[n];
1305
1306 pa->used = !partition_unused(e) || gpt_partition_start(e);
1307 if (!pa->used)
1308 return 0;
1309
1310 pa->start = gpt_partition_start(e);
1311 pa->end = gpt_partition_end(e);
1312 pa->size = gpt_partition_size(e);
1313 pa->type = gpt_partition_parttype(cxt, e);
1314
1315 if (guid_to_string(&e->partition_guid, u_str)) {
1316 pa->uuid = strdup(u_str);
1317 if (!pa->uuid)
1318 goto nomem;
1319 } else
1320 pa->uuid = NULL;
1321
1322 if (asprintf(&pa->attrs, "%s%s%s%s",
1323 e->attr.required_to_function ? "Required " : "",
1324 e->attr.legacy_bios_bootable ? "LegacyBoot " : "",
1325 e->attr.no_blockio_protocol ? "NoBlockIO " : "",
1326 guid_attrs_to_string(&e->attr, &buf)) < 0)
1327 goto nomem;
1328
1329 pa->name = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1330
1331 return 0;
1332 nomem:
1333 fdisk_reset_partition(pa);
1334 return -ENOMEM;
1335 }
1336
1337 /*
1338 * List label partitions.
1339 */
1340 static int gpt_list_disklabel(struct fdisk_context *cxt)
1341 {
1342 assert(cxt);
1343 assert(cxt->label);
1344 assert(fdisk_is_disklabel(cxt, GPT));
1345
1346 if (fdisk_context_display_details(cxt)) {
1347 struct gpt_header *h = self_label(cxt)->pheader;
1348
1349 fdisk_colon(cxt, _("First LBA: %ju"), h->first_usable_lba);
1350 fdisk_colon(cxt, _("Last LBA: %ju"), h->last_usable_lba);
1351 fdisk_colon(cxt, _("Alternative LBA: %ju"), h->alternative_lba);
1352 fdisk_colon(cxt, _("Partitions entries LBA: %ju"), h->partition_entry_lba);
1353 fdisk_colon(cxt, _("Allocated partition entries: %u"), h->npartition_entries);
1354 }
1355
1356 return 0;
1357 }
1358
1359 /*
1360 * Write partitions.
1361 * Returns 0 on success, or corresponding error otherwise.
1362 */
1363 static int gpt_write_partitions(struct fdisk_context *cxt,
1364 struct gpt_header *header, struct gpt_entry *ents)
1365 {
1366 off_t offset = le64_to_cpu(header->partition_entry_lba) * cxt->sector_size;
1367 uint32_t nparts = le32_to_cpu(header->npartition_entries);
1368 uint32_t totwrite = nparts * le32_to_cpu(header->sizeof_partition_entry);
1369 ssize_t rc;
1370
1371 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1372 goto fail;
1373
1374 rc = write(cxt->dev_fd, ents, totwrite);
1375 if (rc > 0 && totwrite == (uint32_t) rc)
1376 return 0;
1377 fail:
1378 return -errno;
1379 }
1380
1381 /*
1382 * Write a GPT header to a specified LBA
1383 * Returns 0 on success, or corresponding error otherwise.
1384 */
1385 static int gpt_write_header(struct fdisk_context *cxt,
1386 struct gpt_header *header, uint64_t lba)
1387 {
1388 off_t offset = lba * cxt->sector_size;
1389
1390 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1391 goto fail;
1392 if (cxt->sector_size ==
1393 (size_t) write(cxt->dev_fd, header, cxt->sector_size))
1394 return 0;
1395 fail:
1396 return -errno;
1397 }
1398
1399 /*
1400 * Write the protective MBR.
1401 * Returns 0 on success, or corresponding error otherwise.
1402 */
1403 static int gpt_write_pmbr(struct fdisk_context *cxt)
1404 {
1405 off_t offset;
1406 struct gpt_legacy_mbr *pmbr = NULL;
1407
1408 assert(cxt);
1409 assert(cxt->firstsector);
1410
1411 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
1412
1413 /* zero out the legacy partitions */
1414 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
1415
1416 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
1417 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
1418 pmbr->partition_record[0].start_sector = 1;
1419 pmbr->partition_record[0].end_head = 0xFE;
1420 pmbr->partition_record[0].end_sector = 0xFF;
1421 pmbr->partition_record[0].end_track = 0xFF;
1422 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
1423
1424 /*
1425 * Set size_in_lba to the size of the disk minus one. If the size of the disk
1426 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
1427 */
1428 if (cxt->total_sectors - 1 > 0xFFFFFFFFULL)
1429 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
1430 else
1431 pmbr->partition_record[0].size_in_lba =
1432 cpu_to_le32(cxt->total_sectors - 1UL);
1433
1434 offset = GPT_PMBR_LBA * cxt->sector_size;
1435 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1436 goto fail;
1437
1438 /* pMBR covers the first sector (LBA) of the disk */
1439 if (write_all(cxt->dev_fd, pmbr, cxt->sector_size))
1440 goto fail;
1441 return 0;
1442 fail:
1443 return -errno;
1444 }
1445
1446 /*
1447 * Writes in-memory GPT and pMBR data to disk.
1448 * Returns 0 if successful write, otherwise, a corresponding error.
1449 * Any indication of error will abort the operation.
1450 */
1451 static int gpt_write_disklabel(struct fdisk_context *cxt)
1452 {
1453 struct fdisk_gpt_label *gpt;
1454 int mbr_type;
1455
1456 assert(cxt);
1457 assert(cxt->label);
1458 assert(fdisk_is_disklabel(cxt, GPT));
1459
1460 gpt = self_label(cxt);
1461 mbr_type = valid_pmbr(cxt);
1462
1463 /* check that disk is big enough to handle the backup header */
1464 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
1465 goto err0;
1466
1467 /* check that the backup header is properly placed */
1468 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1)
1469 /* TODO: correct this (with user authorization) and write */
1470 goto err0;
1471
1472 if (partition_check_overlaps(gpt->pheader, gpt->ents))
1473 goto err0;
1474
1475 /* recompute CRCs for both headers */
1476 gpt_recompute_crc(gpt->pheader, gpt->ents);
1477 gpt_recompute_crc(gpt->bheader, gpt->ents);
1478
1479 /*
1480 * UEFI requires writing in this specific order:
1481 * 1) backup partition tables
1482 * 2) backup GPT header
1483 * 3) primary partition tables
1484 * 4) primary GPT header
1485 * 5) protective MBR
1486 *
1487 * If any write fails, we abort the rest.
1488 */
1489 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
1490 goto err1;
1491 if (gpt_write_header(cxt, gpt->bheader,
1492 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
1493 goto err1;
1494 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
1495 goto err1;
1496 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
1497 goto err1;
1498
1499 if (mbr_type == GPT_MBR_HYBRID)
1500 fdisk_warnx(cxt, _("The device contains hybrid MBR -- writing GPT only. "
1501 "You have to sync the MBR manually."));
1502 else if (gpt_write_pmbr(cxt) != 0)
1503 goto err1;
1504
1505 DBG(LABEL, dbgprint("GPT write success"));
1506 return 0;
1507 err0:
1508 DBG(LABEL, dbgprint("GPT write failed: incorrect input"));
1509 errno = EINVAL;
1510 return -EINVAL;
1511 err1:
1512 DBG(LABEL, dbgprint("GPT write failed: %m"));
1513 return -errno;
1514 }
1515
1516 /*
1517 * Verify data integrity and report any found problems for:
1518 * - primary and backup header validations
1519 * - paritition validations
1520 */
1521 static int gpt_verify_disklabel(struct fdisk_context *cxt)
1522 {
1523 int nerror = 0;
1524 unsigned int ptnum;
1525 struct fdisk_gpt_label *gpt;
1526
1527 assert(cxt);
1528 assert(cxt->label);
1529 assert(fdisk_is_disklabel(cxt, GPT));
1530
1531 gpt = self_label(cxt);
1532
1533 if (!gpt || !gpt->bheader) {
1534 nerror++;
1535 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
1536 }
1537
1538 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
1539 nerror++;
1540 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
1541 }
1542 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
1543 nerror++;
1544 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
1545 }
1546
1547 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
1548 nerror++;
1549 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
1550 }
1551
1552 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
1553 nerror++;
1554 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
1555 }
1556 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
1557 nerror++;
1558 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
1559 }
1560
1561 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
1562 nerror++;
1563 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
1564 }
1565 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
1566 nerror++;
1567 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
1568
1569 }
1570 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
1571 nerror++;
1572 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
1573 }
1574
1575 /*
1576 * if the GPT is the primary table, check the alternateLBA
1577 * to see if it is a valid GPT
1578 */
1579 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
1580 le64_to_cpu(gpt->bheader->alternative_lba))) {
1581 nerror++;
1582 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
1583 }
1584
1585 ptnum = partition_check_overlaps(gpt->pheader, gpt->ents);
1586 if (ptnum) {
1587 nerror++;
1588 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
1589 ptnum, ptnum+1);
1590 }
1591
1592 ptnum = partition_check_too_big(gpt->pheader, gpt->ents, cxt->total_sectors);
1593 if (ptnum) {
1594 nerror++;
1595 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
1596 ptnum);
1597 }
1598
1599 ptnum = partition_start_after_end(gpt->pheader, gpt->ents);
1600 if (ptnum) {
1601 nerror++;
1602 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
1603 ptnum);
1604 }
1605
1606 if (!nerror) { /* yay :-) */
1607 uint32_t nsegments = 0;
1608 uint64_t free_sectors = 0, largest_segment = 0;
1609 char *strsz = NULL;
1610
1611 fdisk_info(cxt, _("No errors detected."));
1612 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
1613 fdisk_info(cxt, _("Using %u out of %d partitions."),
1614 partitions_in_use(gpt->pheader, gpt->ents),
1615 le32_to_cpu(gpt->pheader->npartition_entries));
1616
1617 free_sectors = get_free_sectors(cxt, gpt->pheader, gpt->ents,
1618 &nsegments, &largest_segment);
1619 if (largest_segment)
1620 strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER,
1621 largest_segment * cxt->sector_size);
1622
1623 fdisk_info(cxt,
1624 P_("A total of %ju free sectors is available in %u segment.",
1625 "A total of %ju free sectors is available in %u segments "
1626 "(the largest is %s).", nsegments),
1627 free_sectors, nsegments, strsz);
1628 free(strsz);
1629
1630 } else
1631 fdisk_warnx(cxt,
1632 P_("%d error detected.", "%d errors detected.", nerror),
1633 nerror);
1634
1635 return 0;
1636 }
1637
1638 /* Delete a single GPT partition, specified by partnum. */
1639 static int gpt_delete_partition(struct fdisk_context *cxt,
1640 size_t partnum)
1641 {
1642 struct fdisk_gpt_label *gpt;
1643
1644 assert(cxt);
1645 assert(cxt->label);
1646 assert(fdisk_is_disklabel(cxt, GPT));
1647
1648 gpt = self_label(cxt);
1649
1650 if (partnum >= cxt->label->nparts_max
1651 || partition_unused(&gpt->ents[partnum]))
1652 return -EINVAL;
1653
1654 /* hasta la vista, baby! */
1655 memset(&gpt->ents[partnum], 0, sizeof(struct gpt_entry));
1656 if (!partition_unused(&gpt->ents[partnum]))
1657 return -EINVAL;
1658 else {
1659 gpt_recompute_crc(gpt->pheader, gpt->ents);
1660 gpt_recompute_crc(gpt->bheader, gpt->ents);
1661 cxt->label->nparts_cur--;
1662 fdisk_label_set_changed(cxt->label, 1);
1663 }
1664
1665 return 0;
1666 }
1667
1668 static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
1669 {
1670 e->type = *uuid;
1671 DBG(LABEL, dbgprint_uuid("new type", &(e->type)));
1672 }
1673
1674 /*
1675 * Create a new GPT partition entry, specified by partnum, and with a range
1676 * of fsect to lsenct sectors, of type t.
1677 * Returns 0 on success, or negative upon failure.
1678 */
1679 static int gpt_create_new_partition(struct fdisk_context *cxt,
1680 size_t partnum, uint64_t fsect, uint64_t lsect,
1681 struct gpt_guid *type,
1682 struct gpt_entry *entries)
1683 {
1684 struct gpt_entry *e = NULL;
1685 struct fdisk_gpt_label *gpt;
1686
1687 assert(cxt);
1688 assert(cxt->label);
1689 assert(fdisk_is_disklabel(cxt, GPT));
1690
1691 DBG(LABEL, dbgprint("GPT new partition: partno=%zu, start=%ju, end=%ju",
1692 partnum, fsect, lsect));
1693
1694 gpt = self_label(cxt);
1695
1696 if (fsect > lsect || partnum >= cxt->label->nparts_max)
1697 return -EINVAL;
1698
1699 e = calloc(1, sizeof(*e));
1700 if (!e)
1701 return -ENOMEM;
1702 e->lba_end = cpu_to_le64(lsect);
1703 e->lba_start = cpu_to_le64(fsect);
1704
1705 gpt_entry_set_type(e, type);
1706
1707 /*
1708 * Any time a new partition entry is created a new GUID must be
1709 * generated for that partition, and every partition is guaranteed
1710 * to have a unique GUID.
1711 */
1712 uuid_generate_random((unsigned char *) &e->partition_guid);
1713 swap_efi_guid(&e->partition_guid);
1714
1715 memcpy(&entries[partnum], e, sizeof(*e));
1716
1717 gpt_recompute_crc(gpt->pheader, entries);
1718 gpt_recompute_crc(gpt->bheader, entries);
1719
1720 free(e);
1721 return 0;
1722 }
1723
1724 /* Performs logical checks to add a new partition entry */
1725 static int gpt_add_partition(
1726 struct fdisk_context *cxt,
1727 struct fdisk_partition *pa)
1728 {
1729 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
1730 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
1731 uint64_t dflt_f, dflt_l; /* largest segment (default) */
1732 struct gpt_guid typeid;
1733 struct fdisk_gpt_label *gpt;
1734 struct gpt_header *pheader;
1735 struct gpt_entry *ents;
1736 struct fdisk_ask *ask = NULL;
1737 size_t partnum;
1738 int rc;
1739
1740 assert(cxt);
1741 assert(cxt->label);
1742 assert(fdisk_is_disklabel(cxt, GPT));
1743
1744 gpt = self_label(cxt);
1745 pheader = gpt->pheader;
1746 ents = gpt->ents;
1747
1748 rc = fdisk_partition_next_partno(pa, cxt, &partnum);
1749 if (rc) {
1750 DBG(LABEL, dbgprint("GPT failed to get next partno"));
1751 return rc;
1752 }
1753 if (!partition_unused(&ents[partnum])) {
1754 fdisk_warnx(cxt, _("Partition %zu is already defined. "
1755 "Delete it before re-adding it."), partnum +1);
1756 return -ERANGE;
1757 }
1758 if (le32_to_cpu(pheader->npartition_entries) ==
1759 partitions_in_use(pheader, ents)) {
1760 fdisk_warnx(cxt, _("All partitions are already in use."));
1761 return -ENOSPC;
1762 }
1763 if (!get_free_sectors(cxt, pheader, ents, NULL, NULL)) {
1764 fdisk_warnx(cxt, _("No free sectors available."));
1765 return -ENOSPC;
1766 }
1767
1768 string_to_guid(pa && pa->type && pa->type->typestr ?
1769 pa->type->typestr:
1770 GPT_DEFAULT_ENTRY_TYPE, &typeid);
1771
1772 disk_f = find_first_available(pheader, ents, 0);
1773 disk_l = find_last_free_sector(pheader, ents);
1774
1775 /* the default is the largest free space */
1776 dflt_f = find_first_in_largest(pheader, ents);
1777 dflt_l = find_last_free(pheader, ents, dflt_f);
1778
1779 /* align the default in range <dflt_f,dflt_l>*/
1780 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
1781
1782 /* first sector */
1783 if (pa && pa->start) {
1784 if (pa->start != find_first_available(pheader, ents, pa->start)) {
1785 fdisk_warnx(cxt, _("Sector %ju already used."), pa->start);
1786 return -ERANGE;
1787 }
1788 user_f = pa->start;
1789 } else if (pa && pa->start_follow_default) {
1790 user_f = dflt_f;
1791 } else {
1792 /* ask by dialog */
1793 for (;;) {
1794 if (!ask)
1795 ask = fdisk_new_ask();
1796 else
1797 fdisk_reset_ask(ask);
1798
1799 /* First sector */
1800 fdisk_ask_set_query(ask, _("First sector"));
1801 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
1802 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
1803 fdisk_ask_number_set_default(ask, dflt_f); /* default */
1804 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
1805
1806 rc = fdisk_do_ask(cxt, ask);
1807 if (rc)
1808 goto done;
1809
1810 user_f = fdisk_ask_number_get_result(ask);
1811 if (user_f != find_first_available(pheader, ents, user_f)) {
1812 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
1813 continue;
1814 }
1815 break;
1816 }
1817 }
1818
1819
1820 /* Last sector */
1821 dflt_l = find_last_free(pheader, ents, user_f);
1822
1823 if (pa && pa->size) {
1824 user_l = user_f + pa->size;
1825 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l) - 1;
1826
1827 if (user_l + (cxt->grain / cxt->sector_size) > dflt_l)
1828 user_l = dflt_l; /* no space for anything useful, use all space */
1829
1830 } else if (pa && pa->end_follow_default) {
1831 user_l = dflt_l;
1832 } else {
1833 for (;;) {
1834 if (!ask)
1835 ask = fdisk_new_ask();
1836 else
1837 fdisk_reset_ask(ask);
1838
1839 fdisk_ask_set_query(ask, _("Last sector, +sectors or +size{K,M,G,T,P}"));
1840 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
1841 fdisk_ask_number_set_low(ask, user_f); /* minimal */
1842 fdisk_ask_number_set_default(ask, dflt_l); /* default */
1843 fdisk_ask_number_set_high(ask, dflt_l); /* maximal */
1844 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
1845 fdisk_ask_number_set_unit(ask, cxt->sector_size);
1846
1847 rc = fdisk_do_ask(cxt, ask);
1848 if (rc)
1849 goto done;
1850
1851 user_l = fdisk_ask_number_get_result(ask);
1852 if (fdisk_ask_number_is_relative(ask)) {
1853 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l) - 1;
1854 if (user_l + (cxt->grain / cxt->sector_size) > dflt_l)
1855 user_l = dflt_l; /* no space for anything useful, use all space */
1856 } if (user_l > user_f && user_l <= disk_l)
1857 break;
1858 }
1859 }
1860
1861 if ((rc = gpt_create_new_partition(cxt, partnum,
1862 user_f, user_l, &typeid, ents) != 0)) {
1863 fdisk_warnx(cxt, _("Could not create partition %ju"), partnum + 1);
1864 goto done;
1865 } else {
1866 struct fdisk_parttype *t;
1867
1868 cxt->label->nparts_cur++;
1869 fdisk_label_set_changed(cxt->label, 1);
1870
1871 t = gpt_partition_parttype(cxt, &ents[partnum]);
1872 fdisk_info_new_partition(cxt, partnum + 1, user_f, user_l, t);
1873 fdisk_free_parttype(t);
1874 }
1875
1876 rc = 0;
1877 done:
1878 fdisk_free_ask(ask);
1879 return rc;
1880 }
1881
1882 /*
1883 * Create a new GPT disklabel - destroys any previous data.
1884 */
1885 static int gpt_create_disklabel(struct fdisk_context *cxt)
1886 {
1887 int rc = 0;
1888 ssize_t esz = 0;
1889 char str[37];
1890 struct fdisk_gpt_label *gpt;
1891
1892 assert(cxt);
1893 assert(cxt->label);
1894 assert(fdisk_is_disklabel(cxt, GPT));
1895
1896 gpt = self_label(cxt);
1897
1898 /* label private stuff has to be empty, see gpt_deinit() */
1899 assert(gpt->pheader == NULL);
1900 assert(gpt->bheader == NULL);
1901
1902 /*
1903 * When no header, entries or pmbr is set, we're probably
1904 * dealing with a new, empty disk - so always allocate memory
1905 * to deal with the data structures whatever the case is.
1906 */
1907 rc = gpt_mknew_pmbr(cxt);
1908 if (rc < 0)
1909 goto done;
1910
1911 /* primary */
1912 gpt->pheader = calloc(1, sizeof(*gpt->pheader));
1913 if (!gpt->pheader) {
1914 rc = -ENOMEM;
1915 goto done;
1916 }
1917 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
1918 if (rc < 0)
1919 goto done;
1920
1921 /* backup ("copy" primary) */
1922 gpt->bheader = calloc(1, sizeof(*gpt->bheader));
1923 if (!gpt->bheader) {
1924 rc = -ENOMEM;
1925 goto done;
1926 }
1927 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
1928 last_lba(cxt), gpt->pheader);
1929 if (rc < 0)
1930 goto done;
1931
1932 esz = le32_to_cpu(gpt->pheader->npartition_entries) *
1933 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
1934 gpt->ents = calloc(1, esz);
1935 if (!gpt->ents) {
1936 rc = -ENOMEM;
1937 goto done;
1938 }
1939 gpt_recompute_crc(gpt->pheader, gpt->ents);
1940 gpt_recompute_crc(gpt->bheader, gpt->ents);
1941
1942 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1943 cxt->label->nparts_cur = 0;
1944
1945 guid_to_string(&gpt->pheader->disk_guid, str);
1946 fdisk_label_set_changed(cxt->label, 1);
1947 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
1948 _("Created a new GPT disklabel (GUID: %s)."), str);
1949 done:
1950 return rc;
1951 }
1952
1953 static int gpt_get_disklabel_id(struct fdisk_context *cxt, char **id)
1954 {
1955 struct fdisk_gpt_label *gpt;
1956 char str[37];
1957
1958 assert(cxt);
1959 assert(id);
1960 assert(cxt->label);
1961 assert(fdisk_is_disklabel(cxt, GPT));
1962
1963 gpt = self_label(cxt);
1964 guid_to_string(&gpt->pheader->disk_guid, str);
1965
1966 *id = strdup(str);
1967 if (!*id)
1968 return -ENOMEM;
1969 return 0;
1970 }
1971
1972 static int gpt_set_disklabel_id(struct fdisk_context *cxt)
1973 {
1974 struct fdisk_gpt_label *gpt;
1975 struct gpt_guid uuid;
1976 char *str, *old, *new;
1977 int rc;
1978
1979 assert(cxt);
1980 assert(cxt->label);
1981 assert(fdisk_is_disklabel(cxt, GPT));
1982
1983 gpt = self_label(cxt);
1984 if (fdisk_ask_string(cxt,
1985 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &str))
1986 return -EINVAL;
1987
1988 rc = string_to_guid(str, &uuid);
1989 free(str);
1990
1991 if (rc) {
1992 fdisk_warnx(cxt, _("Failed to parse your UUID."));
1993 return rc;
1994 }
1995
1996 gpt_get_disklabel_id(cxt, &old);
1997
1998 gpt->pheader->disk_guid = uuid;
1999 gpt->bheader->disk_guid = uuid;
2000
2001 gpt_recompute_crc(gpt->pheader, gpt->ents);
2002 gpt_recompute_crc(gpt->bheader, gpt->ents);
2003
2004 gpt_get_disklabel_id(cxt, &new);
2005
2006 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2007 _("Disk identifier changed from %s to %s."), old, new);
2008
2009 free(old);
2010 free(new);
2011 fdisk_label_set_changed(cxt->label, 1);
2012 return 0;
2013 }
2014
2015 static int gpt_set_partition_type(
2016 struct fdisk_context *cxt,
2017 size_t i,
2018 struct fdisk_parttype *t)
2019 {
2020 struct gpt_guid uuid;
2021 struct fdisk_gpt_label *gpt;
2022
2023 assert(cxt);
2024 assert(cxt->label);
2025 assert(fdisk_is_disklabel(cxt, GPT));
2026
2027 gpt = self_label(cxt);
2028 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries)
2029 || !t || !t->typestr || string_to_guid(t->typestr, &uuid) != 0)
2030 return -EINVAL;
2031
2032 gpt_entry_set_type(&gpt->ents[i], &uuid);
2033 gpt_recompute_crc(gpt->pheader, gpt->ents);
2034 gpt_recompute_crc(gpt->bheader, gpt->ents);
2035
2036 fdisk_label_set_changed(cxt->label, 1);
2037 return 0;
2038 }
2039
2040 static int gpt_part_is_used(struct fdisk_context *cxt, size_t i)
2041 {
2042 struct fdisk_gpt_label *gpt;
2043 struct gpt_entry *e;
2044
2045 assert(cxt);
2046 assert(cxt->label);
2047 assert(fdisk_is_disklabel(cxt, GPT));
2048
2049 gpt = self_label(cxt);
2050
2051 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2052 return 0;
2053 e = &gpt->ents[i];
2054
2055 return !partition_unused(e) || gpt_partition_start(e);
2056 }
2057
2058 int fdisk_gpt_partition_set_uuid(struct fdisk_context *cxt, size_t i)
2059 {
2060 struct fdisk_gpt_label *gpt;
2061 struct gpt_entry *e;
2062 struct gpt_guid uuid;
2063 char *str, new_u[37], old_u[37];
2064 int rc;
2065
2066 assert(cxt);
2067 assert(cxt->label);
2068 assert(fdisk_is_disklabel(cxt, GPT));
2069
2070 DBG(LABEL, dbgprint("UUID change requested partno=%zu", i));
2071
2072 gpt = self_label(cxt);
2073
2074 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2075 return -EINVAL;
2076
2077 if (fdisk_ask_string(cxt,
2078 _("New UUID (in 8-4-4-4-12 format)"), &str))
2079 return -EINVAL;
2080
2081 rc = string_to_guid(str, &uuid);
2082 free(str);
2083
2084 if (rc) {
2085 fdisk_warnx(cxt, _("Failed to parse your UUID."));
2086 return rc;
2087 }
2088
2089 e = &gpt->ents[i];
2090
2091 guid_to_string(&e->partition_guid, old_u);
2092 guid_to_string(&uuid, new_u);
2093
2094 e->partition_guid = uuid;
2095 gpt_recompute_crc(gpt->pheader, gpt->ents);
2096 gpt_recompute_crc(gpt->bheader, gpt->ents);
2097 fdisk_label_set_changed(cxt->label, 1);
2098
2099 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2100 _("Partition UUID changed from %s to %s."),
2101 old_u, new_u);
2102 return 0;
2103 }
2104
2105 int fdisk_gpt_partition_set_name(struct fdisk_context *cxt, size_t i)
2106 {
2107 struct fdisk_gpt_label *gpt;
2108 struct gpt_entry *e;
2109 char *str, *old, name[GPT_PART_NAME_LEN] = { 0 };
2110 size_t sz;
2111
2112 assert(cxt);
2113 assert(cxt->label);
2114 assert(fdisk_is_disklabel(cxt, GPT));
2115
2116 DBG(LABEL, dbgprint("NAME change requested partno=%zu", i));
2117
2118 gpt = self_label(cxt);
2119
2120 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2121 return -EINVAL;
2122
2123 if (fdisk_ask_string(cxt, _("New name"), &str))
2124 return -EINVAL;
2125
2126 e = &gpt->ents[i];
2127 old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
2128
2129 sz = strlen(str);
2130 if (sz) {
2131 if (sz > GPT_PART_NAME_LEN)
2132 sz = GPT_PART_NAME_LEN;
2133 memcpy(name, str, sz);
2134 }
2135
2136 for (i = 0; i < GPT_PART_NAME_LEN; i++)
2137 e->name[i] = cpu_to_le16((uint16_t) name[i]);
2138
2139 gpt_recompute_crc(gpt->pheader, gpt->ents);
2140 gpt_recompute_crc(gpt->bheader, gpt->ents);
2141
2142 fdisk_label_set_changed(cxt->label, 1);
2143
2144 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2145 _("Partition name changed from '%s' to '%.*s'."),
2146 old, (int) GPT_PART_NAME_LEN, str);
2147 free(str);
2148 free(old);
2149
2150 return 0;
2151 }
2152
2153 int fdisk_gpt_is_hybrid(struct fdisk_context *cxt)
2154 {
2155 assert(cxt);
2156 return valid_pmbr(cxt) == GPT_MBR_HYBRID;
2157 }
2158
2159 static int gpt_toggle_partition_flag(
2160 struct fdisk_context *cxt,
2161 size_t i,
2162 unsigned long flag)
2163 {
2164 struct fdisk_gpt_label *gpt;
2165 struct gpt_entry *e;
2166
2167 assert(cxt);
2168 assert(cxt->label);
2169 assert(fdisk_is_disklabel(cxt, GPT));
2170
2171 DBG(LABEL, dbgprint("GPT entry attribute change requested partno=%zu", i));
2172
2173 gpt = self_label(cxt);
2174
2175 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2176 return -EINVAL;
2177
2178 e = &gpt->ents[i];
2179
2180 switch (flag) {
2181 case GPT_FLAG_REQUIRED:
2182 e->attr.required_to_function = !e->attr.required_to_function;
2183 fdisk_label_set_changed(cxt->label, 1);
2184 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2185 e->attr.required_to_function ?
2186 _("The RequiredPartiton flag on partition %zu is enabled now.") :
2187 _("The RequiredPartiton flag on partition %zu is disabled now."),
2188 i + 1);
2189 break;
2190 case GPT_FLAG_NOBLOCK:
2191 e->attr.no_blockio_protocol = !e->attr.no_blockio_protocol;
2192 fdisk_label_set_changed(cxt->label, 1);
2193 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2194 e->attr.no_blockio_protocol ?
2195 _("The NoBlockIOProtocol flag on partition %zu is enabled now.") :
2196 _("The NoBlockIOProtocol flag on partition %zu is disabled now."),
2197 i + 1);
2198 break;
2199 case GPT_FLAG_LEGACYBOOT:
2200 e->attr.legacy_bios_bootable = !e->attr.legacy_bios_bootable;
2201 fdisk_label_set_changed(cxt->label, 1);
2202 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2203 e->attr.legacy_bios_bootable ?
2204 _("The LegacyBIOSBootable flag on partition %zu is enabled now.") :
2205 _("The LegacyBIOSBootable flag on partition %zu is disabled now."),
2206 i + 1);
2207 break;
2208 case GPT_FLAG_GUIDSPECIFIC:
2209 {
2210 char *attrs = (char *) &e->attr;
2211 uint64_t bit = 0;
2212 int rc = fdisk_ask_number(cxt, 48, 48, 63,
2213 _("Enter GUID specific bit"),
2214 &bit);
2215 if (rc)
2216 return rc;
2217 if (!isset(attrs, bit))
2218 setbit(attrs, bit);
2219 else
2220 clrbit(attrs, bit);
2221
2222 fdisk_label_set_changed(cxt->label, 1);
2223 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2224 isset(attrs, bit) ?
2225 _("The GUID specific bit %ju on partition %zu is enabled now.") :
2226 _("The GUID specific bit %ju on partition %zu is disabled now."),
2227 bit, i + 1);
2228 break;
2229 }
2230 default:
2231 return 1;
2232 }
2233
2234 gpt_recompute_crc(gpt->pheader, gpt->ents);
2235 gpt_recompute_crc(gpt->bheader, gpt->ents);
2236
2237 return 0;
2238 }
2239
2240 static int gpt_reset_alignment(struct fdisk_context *cxt)
2241 {
2242 struct fdisk_gpt_label *gpt;
2243 struct gpt_header *h;
2244
2245 assert(cxt);
2246 assert(cxt->label);
2247 assert(fdisk_is_disklabel(cxt, GPT));
2248
2249 gpt = self_label(cxt);
2250 h = gpt ? gpt->pheader : NULL;
2251
2252 if (h) {
2253 /* always follow existing table */
2254 cxt->first_lba = h->first_usable_lba;
2255 cxt->last_lba = h->last_usable_lba;
2256 } else {
2257 /* estimate ranges for GPT */
2258 uint64_t first, last;
2259
2260 count_first_last_lba(cxt, &first, &last);
2261
2262 if (cxt->first_lba < first)
2263 cxt->first_lba = first;
2264 if (cxt->last_lba > last)
2265 cxt->last_lba = last;
2266 }
2267
2268 return 0;
2269 }
2270 /*
2271 * Deinitialize fdisk-specific variables
2272 */
2273 static void gpt_deinit(struct fdisk_label *lb)
2274 {
2275 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
2276
2277 if (!gpt)
2278 return;
2279
2280 free(gpt->ents);
2281 free(gpt->pheader);
2282 free(gpt->bheader);
2283
2284 gpt->ents = NULL;
2285 gpt->pheader = NULL;
2286 gpt->bheader = NULL;
2287 }
2288
2289 static const struct fdisk_label_operations gpt_operations =
2290 {
2291 .probe = gpt_probe_label,
2292 .write = gpt_write_disklabel,
2293 .verify = gpt_verify_disklabel,
2294 .create = gpt_create_disklabel,
2295 .list = gpt_list_disklabel,
2296 .locate = gpt_locate_disklabel,
2297 .get_id = gpt_get_disklabel_id,
2298 .set_id = gpt_set_disklabel_id,
2299
2300 .get_part = gpt_get_partition,
2301 .add_part = gpt_add_partition,
2302
2303 .part_delete = gpt_delete_partition,
2304
2305 .part_is_used = gpt_part_is_used,
2306 .part_set_type = gpt_set_partition_type,
2307 .part_toggle_flag = gpt_toggle_partition_flag,
2308
2309 .deinit = gpt_deinit,
2310
2311 .reset_alignment = gpt_reset_alignment
2312 };
2313
2314 static const struct fdisk_column gpt_columns[] =
2315 {
2316 /* basic */
2317 { FDISK_COL_DEVICE, N_("Device"), 10, 0 },
2318 { FDISK_COL_START, N_("Start"), 5, TT_FL_RIGHT },
2319 { FDISK_COL_END, N_("End"), 5, TT_FL_RIGHT },
2320 { FDISK_COL_SECTORS, N_("Sectors"), 5, TT_FL_RIGHT },
2321 { FDISK_COL_CYLINDERS, N_("Cylinders"), 5, TT_FL_RIGHT },
2322 { FDISK_COL_SIZE, N_("Size"), 5, TT_FL_RIGHT, FDISK_COLFL_EYECANDY },
2323 { FDISK_COL_TYPE, N_("Type"), 0.1, TT_FL_TRUNC, FDISK_COLFL_EYECANDY },
2324 /* expert */
2325 { FDISK_COL_TYPEID, N_("Type-UUID"), 36, 0, FDISK_COLFL_DETAIL },
2326 { FDISK_COL_UUID, N_("UUID"), 36, 0, FDISK_COLFL_DETAIL },
2327 { FDISK_COL_NAME, N_("Name"), 0.2, TT_FL_TRUNC, FDISK_COLFL_DETAIL },
2328 { FDISK_COL_ATTR, N_("Attrs"), 0, 0, FDISK_COLFL_DETAIL }
2329 };
2330
2331 /*
2332 * allocates GPT in-memory stuff
2333 */
2334 struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt)
2335 {
2336 struct fdisk_label *lb;
2337 struct fdisk_gpt_label *gpt;
2338
2339 assert(cxt);
2340
2341 gpt = calloc(1, sizeof(*gpt));
2342 if (!gpt)
2343 return NULL;
2344
2345 /* initialize generic part of the driver */
2346 lb = (struct fdisk_label *) gpt;
2347 lb->name = "gpt";
2348 lb->id = FDISK_DISKLABEL_GPT;
2349 lb->op = &gpt_operations;
2350 lb->parttypes = gpt_parttypes;
2351 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
2352
2353 lb->columns = gpt_columns;
2354 lb->ncolumns = ARRAY_SIZE(gpt_columns);
2355
2356 return lb;
2357 }