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