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