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