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