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