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