Debian Codegraph @

libfdisk/src/gpt.c

raw
1 /*
2 * Copyright (C) 2007 Karel Zak <[email protected]>
3 * Copyright (C) 2012 Davidlohr Bueso <[email protected]>
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 <stdint.h>
14 #include <sys/stat.h>
15 #include <sys/utsname.h>
16 #include <sys/types.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <errno.h>
20 #include <ctype.h>
21 #include <uuid.h>
22
23 #include "fdiskP.h"
24
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 #include "encode.h"
32
33 /**
34 * SECTION: gpt
35 * @title: UEFI GPT
36 * @short_description: specific functionality
37 */
38
39 #define GPT_HEADER_SIGNATURE 0x5452415020494645LL /* EFI PART */
40 #define GPT_HEADER_REVISION_V1_02 0x00010200
41 #define GPT_HEADER_REVISION_V1_00 0x00010000
42 #define GPT_HEADER_REVISION_V0_99 0x00009900
43 #define GPT_HEADER_MINSZ 92 /* bytes */
44
45 #define GPT_PMBR_LBA 0
46 #define GPT_MBR_PROTECTIVE 1
47 #define GPT_MBR_HYBRID 2
48
49 #define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001ULL
50
51 #define EFI_PMBR_OSTYPE 0xEE
52 #define MSDOS_MBR_SIGNATURE 0xAA55
53 #define GPT_PART_NAME_LEN (72 / sizeof(uint16_t))
54 #define GPT_NPARTITIONS ((size_t) FDISK_GPT_NPARTITIONS_DEFAULT)
55
56 /* Globally unique identifier */
57 struct gpt_guid {
58 uint32_t time_low;
59 uint16_t time_mid;
60 uint16_t time_hi_and_version;
61 uint8_t clock_seq_hi;
62 uint8_t clock_seq_low;
63 uint8_t node[6];
64 };
65
66
67 /* only checking that the GUID is 0 is enough to verify an empty partition. */
68 #define GPT_UNUSED_ENTRY_GUID \
69 ((struct gpt_guid) { 0x00000000, 0x0000, 0x0000, 0x00, 0x00, \
70 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }})
71
72 /* Linux native partition type */
73 #define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
74
75 /*
76 * Attribute bits
77 */
78 enum {
79 /* UEFI specific */
80 GPT_ATTRBIT_REQ = 0,
81 GPT_ATTRBIT_NOBLOCK = 1,
82 GPT_ATTRBIT_LEGACY = 2,
83
84 /* GUID specific (range 48..64)*/
85 GPT_ATTRBIT_GUID_FIRST = 48,
86 GPT_ATTRBIT_GUID_COUNT = 16
87 };
88
89 #define GPT_ATTRSTR_REQ "RequiredPartition"
90 #define GPT_ATTRSTR_REQ_TYPO "RequiredPartiton"
91 #define GPT_ATTRSTR_NOBLOCK "NoBlockIOProtocol"
92 #define GPT_ATTRSTR_LEGACY "LegacyBIOSBootable"
93
94 /* The GPT Partition entry array contains an array of GPT entries. */
95 struct gpt_entry {
96 struct gpt_guid type; /* purpose and type of the partition */
97 struct gpt_guid partition_guid;
98 uint64_t lba_start;
99 uint64_t lba_end;
100 uint64_t attrs;
101 uint16_t name[GPT_PART_NAME_LEN];
102 } __attribute__ ((packed));
103
104 /* GPT header */
105 struct gpt_header {
106 uint64_t signature; /* header identification */
107 uint32_t revision; /* header version */
108 uint32_t size; /* in bytes */
109 uint32_t crc32; /* header CRC checksum */
110 uint32_t reserved1; /* must be 0 */
111 uint64_t my_lba; /* LBA of block that contains this struct (LBA 1) */
112 uint64_t alternative_lba; /* backup GPT header */
113 uint64_t first_usable_lba; /* first usable logical block for partitions */
114 uint64_t last_usable_lba; /* last usable logical block for partitions */
115 struct gpt_guid disk_guid; /* unique disk identifier */
116 uint64_t partition_entry_lba; /* LBA of start of partition entries array */
117 uint32_t npartition_entries; /* total partition entries - normally 128 */
118 uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
119 uint32_t partition_entry_array_crc32; /* partition CRC checksum */
120 uint8_t reserved2[512 - 92]; /* must all be 0 */
121 } __attribute__ ((packed));
122
123 struct gpt_record {
124 uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
125 uint8_t start_head; /* unused by EFI, pt start in CHS */
126 uint8_t start_sector; /* unused by EFI, pt start in CHS */
127 uint8_t start_track;
128 uint8_t os_type; /* EFI and legacy non-EFI OS types */
129 uint8_t end_head; /* unused by EFI, pt end in CHS */
130 uint8_t end_sector; /* unused by EFI, pt end in CHS */
131 uint8_t end_track; /* unused by EFI, pt end in CHS */
132 uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
133 uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
134 } __attribute__ ((packed));
135
136 /* Protected MBR and legacy MBR share same structure */
137 struct gpt_legacy_mbr {
138 uint8_t boot_code[440];
139 uint32_t unique_mbr_signature;
140 uint16_t unknown;
141 struct gpt_record partition_record[4];
142 uint16_t signature;
143 } __attribute__ ((packed));
144
145 /*
146 * Here be dragons!
147 * See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
148 */
149 #define DEF_GUID(_u, _n) \
150 { \
151 .typestr = (_u), \
152 .name = (_n), \
153 }
154
155 static const struct fdisk_parttype gpt_parttypes[] =
156 {
157 #include "pt-gpt-partnames.h"
158 };
159
160 static const struct fdisk_shortcut gpt_parttype_cuts[] =
161 {
162 { .shortcut = "L", .alias = "linux", .data = "0FC63DAF-8483-4772-8E79-3D69D8477DE4" }, /* Linux */
163 { .shortcut = "S", .alias = "swap", .data = "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F" }, /* Swap */
164 { .shortcut = "H", .alias = "home", .data = "933AC7E1-2EB4-4F13-B844-0E14E2AEF915" }, /* Home */
165 { .shortcut = "U", .alias = "uefi", .data = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B" }, /* UEFI system */
166 { .shortcut = "R", .alias = "raid", .data = "A19D880F-05FC-4D3B-A006-743F0F84911E" }, /* Linux RAID */
167 { .shortcut = "V", .alias = "lvm", .data = "E6D6D379-F507-44C2-A23C-238F2A3DF928" }, /* LVM */
168 { .shortcut = "X", .alias = "xbootldr", .data = "BC13C2FF-59E6-4262-A352-B275FD6F7172" }, /* Linux extended boot */
169 };
170
171 #define alignment_required(_x) ((_x)->grain != (_x)->sector_size)
172
173 /* gpt_entry macros */
174 #define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
175 #define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
176
177 /*
178 * in-memory fdisk GPT stuff
179 */
180 struct fdisk_gpt_label {
181 struct fdisk_label head; /* generic part */
182
183 /* gpt specific part */
184 struct gpt_header *pheader; /* primary header */
185 struct gpt_header *bheader; /* backup header */
186
187 unsigned char *ents; /* entries (partitions) */
188
189 unsigned int no_relocate :1, /* do not fix backup location */
190 minimize :1;
191 };
192
193 static void gpt_deinit(struct fdisk_label *lb);
194
195 static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
196 {
197 return (struct fdisk_gpt_label *) cxt->label;
198 }
199
200 /*
201 * Returns the partition length, or 0 if end is before beginning.
202 */
203 static uint64_t gpt_partition_size(const struct gpt_entry *e)
204 {
205 uint64_t start = gpt_partition_start(e);
206 uint64_t end = gpt_partition_end(e);
207
208 return start > end ? 0 : end - start + 1ULL;
209 }
210
211 /* prints UUID in the real byte order! */
212 static void gpt_debug_uuid(const char *mesg, struct gpt_guid *guid)
213 {
214 const unsigned char *uuid = (unsigned char *) guid;
215
216 fprintf(stderr, "%s: "
217 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
218 mesg,
219 uuid[0], uuid[1], uuid[2], uuid[3],
220 uuid[4], uuid[5],
221 uuid[6], uuid[7],
222 uuid[8], uuid[9],
223 uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
224 }
225
226 /*
227 * UUID is traditionally 16 byte big-endian array, except Intel EFI
228 * specification where the UUID is a structure of little-endian fields.
229 */
230 static void swap_efi_guid(struct gpt_guid *uid)
231 {
232 uid->time_low = swab32(uid->time_low);
233 uid->time_mid = swab16(uid->time_mid);
234 uid->time_hi_and_version = swab16(uid->time_hi_and_version);
235 }
236
237 static int string_to_guid(const char *in, struct gpt_guid *guid)
238 {
239 if (uuid_parse(in, (unsigned char *) guid)) { /* BE */
240 DBG(GPT, ul_debug("failed to parse GUID: %s", in));
241 return -EINVAL;
242 }
243 swap_efi_guid(guid); /* LE */
244 return 0;
245 }
246
247 static char *guid_to_string(const struct gpt_guid *guid, char *out)
248 {
249 struct gpt_guid u = *guid; /* LE */
250
251 swap_efi_guid(&u); /* BE */
252 uuid_unparse_upper((unsigned char *) &u, out);
253
254 return out;
255 }
256
257 static struct fdisk_parttype *gpt_partition_parttype(
258 struct fdisk_context *cxt,
259 const struct gpt_entry *e)
260 {
261 struct fdisk_parttype *t;
262 char str[UUID_STR_LEN];
263 struct gpt_guid guid = e->type;
264
265 guid_to_string(&guid, str);
266 t = fdisk_label_get_parttype_from_string(cxt->label, str);
267 return t ? : fdisk_new_unknown_parttype(0, str);
268 }
269
270 static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
271 {
272 e->type = *uuid;
273 DBG(GPT, gpt_debug_uuid("new type", uuid));
274 }
275
276 static int gpt_entry_set_name(struct gpt_entry *e, char *str)
277 {
278 uint16_t name[GPT_PART_NAME_LEN] = { 0 };
279 size_t i, mblen = 0;
280 uint8_t *in = (uint8_t *) str;
281
282 for (i = 0; *in && i < GPT_PART_NAME_LEN; in++) {
283 if (!mblen) {
284 if (!(*in & 0x80)) {
285 name[i++] = *in;
286 } else if ((*in & 0xE0) == 0xC0) {
287 mblen = 1;
288 name[i] = (uint16_t)(*in & 0x1F) << (mblen *6);
289 } else if ((*in & 0xF0) == 0xE0) {
290 mblen = 2;
291 name[i] = (uint16_t)(*in & 0x0F) << (mblen *6);
292 } else {
293 /* broken UTF-8 or code point greater than U+FFFF */
294 return -EILSEQ;
295 }
296 } else {
297 /* incomplete UTF-8 sequence */
298 if ((*in & 0xC0) != 0x80)
299 return -EILSEQ;
300
301 name[i] |= (uint16_t)(*in & 0x3F) << (--mblen *6);
302 if (!mblen) {
303 /* check for code points reserved for surrogate pairs*/
304 if ((name[i] & 0xF800) == 0xD800)
305 return -EILSEQ;
306 i++;
307 }
308 }
309 }
310
311 for (i = 0; i < GPT_PART_NAME_LEN; i++)
312 e->name[i] = cpu_to_le16(name[i]);
313
314 return (int)((char *) in - str);
315 }
316
317 static int gpt_entry_set_uuid(struct gpt_entry *e, char *str)
318 {
319 struct gpt_guid uuid;
320 int rc;
321
322 rc = string_to_guid(str, &uuid);
323 if (rc)
324 return rc;
325
326 e->partition_guid = uuid;
327 return 0;
328 }
329
330 static inline int gpt_entry_is_used(const struct gpt_entry *e)
331 {
332 return memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
333 sizeof(struct gpt_guid)) != 0;
334 }
335
336
337 static const char *gpt_get_header_revstr(struct gpt_header *header)
338 {
339 if (!header)
340 goto unknown;
341
342 switch (le32_to_cpu(header->revision)) {
343 case GPT_HEADER_REVISION_V1_02:
344 return "1.2";
345 case GPT_HEADER_REVISION_V1_00:
346 return "1.0";
347 case GPT_HEADER_REVISION_V0_99:
348 return "0.99";
349 default:
350 goto unknown;
351 }
352
353 unknown:
354 return "unknown";
355 }
356
357 static inline unsigned char *gpt_get_entry_ptr(struct fdisk_gpt_label *gpt, size_t i)
358 {
359 return gpt->ents + le32_to_cpu(gpt->pheader->sizeof_partition_entry) * i;
360 }
361
362 static inline struct gpt_entry *gpt_get_entry(struct fdisk_gpt_label *gpt, size_t i)
363 {
364 return (struct gpt_entry *) gpt_get_entry_ptr(gpt, i);
365 }
366
367 static inline struct gpt_entry *gpt_zeroize_entry(struct fdisk_gpt_label *gpt, size_t i)
368 {
369 return (struct gpt_entry *) memset(gpt_get_entry_ptr(gpt, i),
370 0, le32_to_cpu(gpt->pheader->sizeof_partition_entry));
371 }
372
373 /* Use to access array of entries, for() loops, etc. But don't use when
374 * you directly do something with GPT header, then use uint32_t.
375 */
376 static inline size_t gpt_get_nentries(struct fdisk_gpt_label *gpt)
377 {
378 return (size_t) le32_to_cpu(gpt->pheader->npartition_entries);
379 }
380
381 /* calculate size of entries array in bytes for specified number of entries */
382 static inline int gpt_calculate_sizeof_entries(
383 struct gpt_header *hdr,
384 uint32_t nents, size_t *sz)
385 {
386 uint32_t esz = hdr ? le32_to_cpu(hdr->sizeof_partition_entry) :
387 sizeof(struct gpt_entry);
388
389 if (nents == 0 || esz == 0 || SIZE_MAX/esz < nents) {
390 DBG(GPT, ul_debug("entries array size check failed"));
391 return -ERANGE;
392 }
393
394 *sz = (size_t) nents * esz;
395 return 0;
396 }
397
398 /* calculate size of entries array in sectors for specified number of entries */
399 static inline int gpt_calculate_sectorsof_entries(
400 struct gpt_header *hdr,
401 uint32_t nents, uint64_t *sz,
402 struct fdisk_context *cxt)
403 {
404 size_t esz = 0;
405 int rc = gpt_calculate_sizeof_entries(hdr, nents, &esz); /* in bytes */
406
407 if (rc == 0)
408 *sz = (esz + cxt->sector_size - 1) / cxt->sector_size;
409 return rc;
410 }
411
412 /* calculate alternative (backup) entries array offset from primary header */
413 static inline int gpt_calculate_alternative_entries_lba(
414 struct gpt_header *hdr,
415 uint32_t nents,
416 uint64_t *sz,
417 struct fdisk_context *cxt)
418 {
419 uint64_t esects = 0;
420 int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
421
422 if (rc)
423 return rc;
424 if (cxt->total_sectors < 1ULL + esects)
425 return -ENOSPC;
426
427 *sz = cxt->total_sectors - 1ULL - esects;
428 return 0;
429 }
430
431 static inline int gpt_calculate_last_lba(
432 struct gpt_header *hdr,
433 uint32_t nents,
434 uint64_t *sz,
435 struct fdisk_context *cxt)
436 {
437 uint64_t esects = 0;
438 int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
439
440 if (rc)
441 return rc;
442 if (cxt->total_sectors < 2ULL + esects)
443 return -ENOSPC;
444
445 *sz = cxt->total_sectors - 2ULL - esects;
446 return 0;
447 }
448
449 static inline int gpt_calculate_first_lba(
450 struct gpt_header *hdr,
451 uint32_t nents,
452 uint64_t *sz,
453 struct fdisk_context *cxt)
454 {
455 uint64_t esects = 0;
456 int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
457
458 if (rc == 0)
459 *sz = esects + 2ULL;
460 return rc;
461 }
462
463 /* the current size of entries array in bytes */
464 static inline int gpt_sizeof_entries(struct gpt_header *hdr, size_t *sz)
465 {
466 return gpt_calculate_sizeof_entries(hdr, le32_to_cpu(hdr->npartition_entries), sz);
467 }
468
469 static char *gpt_get_header_id(struct gpt_header *header)
470 {
471 char str[UUID_STR_LEN];
472 struct gpt_guid guid = header->disk_guid;
473
474 guid_to_string(&guid, str);
475
476 return strdup(str);
477 }
478
479 /*
480 * Builds a clean new valid protective MBR - will wipe out any existing data.
481 * Returns 0 on success, otherwise < 0 on error.
482 */
483 static int gpt_mknew_pmbr(struct fdisk_context *cxt)
484 {
485 struct gpt_legacy_mbr *pmbr = NULL;
486 int rc;
487
488 if (!cxt || !cxt->firstsector)
489 return -ENOSYS;
490
491 if (fdisk_has_protected_bootbits(cxt))
492 rc = fdisk_init_firstsector_buffer(cxt, 0, MBR_PT_BOOTBITS_SIZE);
493 else
494 rc = fdisk_init_firstsector_buffer(cxt, 0, 0);
495 if (rc)
496 return rc;
497
498 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
499 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
500
501 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
502 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
503 pmbr->partition_record[0].start_sector = 2;
504 pmbr->partition_record[0].end_head = 0xFF;
505 pmbr->partition_record[0].end_sector = 0xFF;
506 pmbr->partition_record[0].end_track = 0xFF;
507 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
508 pmbr->partition_record[0].size_in_lba =
509 cpu_to_le32((uint32_t) min( cxt->total_sectors - 1ULL, 0xFFFFFFFFULL) );
510
511 return 0;
512 }
513
514
515 /* Move backup header to the end of the device */
516 static int gpt_fix_alternative_lba(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
517 {
518 struct gpt_header *p, *b;
519 uint64_t x = 0, orig;
520 size_t nents;
521 int rc;
522
523 if (!cxt)
524 return -EINVAL;
525
526 p = gpt->pheader; /* primary */
527 b = gpt->bheader; /* backup */
528
529 nents = le32_to_cpu(p->npartition_entries);
530 orig = le64_to_cpu(p->alternative_lba);
531
532 /* reference from primary to backup */
533 p->alternative_lba = cpu_to_le64(cxt->total_sectors - 1ULL);
534
535 /* reference from backup to primary */
536 b->alternative_lba = p->my_lba;
537 b->my_lba = p->alternative_lba;
538
539 /* fix backup partitions array address */
540 rc = gpt_calculate_alternative_entries_lba(p, nents, &x, cxt);
541 if (rc)
542 goto failed;
543
544 b->partition_entry_lba = cpu_to_le64(x);
545
546 /* update last usable LBA */
547 rc = gpt_calculate_last_lba(p, nents, &x, cxt);
548 if (rc)
549 goto failed;
550
551 p->last_usable_lba = cpu_to_le64(x);
552 b->last_usable_lba = cpu_to_le64(x);
553
554 DBG(GPT, ul_debug("Alternative-LBA updated from %"PRIu64" to %"PRIu64,
555 orig, le64_to_cpu(p->alternative_lba)));
556 return 0;
557 failed:
558 DBG(GPT, ul_debug("failed to fix alternative-LBA [rc=%d]", rc));
559 return rc;
560 }
561
562 static uint64_t gpt_calculate_minimal_size(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
563 {
564 size_t i;
565 uint64_t x = 0, total = 0;
566 struct gpt_header *hdr;
567
568 assert(cxt);
569 assert(gpt);
570 assert(gpt->pheader);
571 assert(gpt->ents);
572
573 hdr = gpt->pheader;
574
575 /* LBA behind the last partition */
576 for (i = 0; i < gpt_get_nentries(gpt); i++) {
577 struct gpt_entry *e = gpt_get_entry(gpt, i);
578
579 if (gpt_entry_is_used(e)) {
580 uint64_t end = gpt_partition_end(e);
581 if (end > x)
582 x = end;
583 }
584 }
585 total = x + 1;
586
587 /* the current last LBA usable for partitions */
588 gpt_calculate_last_lba(hdr, le32_to_cpu(hdr->npartition_entries), &x, cxt);
589
590 /* size of all stuff at the end of the device */
591 total += cxt->total_sectors - x;
592
593 DBG(GPT, ul_debug("minimal device is %"PRIu64, total));
594 return total;
595 }
596
597 static int gpt_possible_minimize(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
598 {
599 struct gpt_header *hdr = gpt->pheader;
600 uint64_t total = gpt_calculate_minimal_size(cxt, gpt);
601
602 return le64_to_cpu(hdr->alternative_lba) > (total - 1ULL);
603 }
604
605 /* move backup header behind the last partition */
606 static int gpt_minimize_alternative_lba(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
607 {
608 uint64_t total = gpt_calculate_minimal_size(cxt, gpt);
609 uint64_t orig = cxt->total_sectors;
610 int rc;
611
612 /* Let's temporary change size of the device to recalculate backup header */
613 cxt->total_sectors = total;
614 rc = gpt_fix_alternative_lba(cxt, gpt);
615 if (rc)
616 return rc;
617
618 cxt->total_sectors = orig;
619 fdisk_label_set_changed(cxt->label, 1);
620 return 0;
621 }
622
623 /* some universal differences between the headers */
624 static void gpt_mknew_header_common(struct fdisk_context *cxt,
625 struct gpt_header *header, uint64_t lba)
626 {
627 if (!cxt || !header)
628 return;
629
630 header->my_lba = cpu_to_le64(lba);
631
632 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) {
633 /* primary */
634 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1ULL);
635 header->partition_entry_lba = cpu_to_le64(2ULL);
636
637 } else {
638 /* backup */
639 uint64_t x = 0;
640 gpt_calculate_alternative_entries_lba(header,
641 le32_to_cpu(header->npartition_entries), &x, cxt);
642
643 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
644 header->partition_entry_lba = cpu_to_le64(x);
645 }
646 }
647
648 /*
649 * Builds a new GPT header (at sector lba) from a backup header2.
650 * If building a primary header, then backup is the secondary, and vice versa.
651 *
652 * Always pass a new (zeroized) header to build upon as we don't
653 * explicitly zero-set some values such as CRCs and reserved.
654 *
655 * Returns 0 on success, otherwise < 0 on error.
656 */
657 static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
658 struct gpt_header *header,
659 uint64_t lba,
660 struct gpt_header *header2)
661 {
662 if (!cxt || !header || !header2)
663 return -ENOSYS;
664
665 header->signature = header2->signature;
666 header->revision = header2->revision;
667 header->size = header2->size;
668 header->npartition_entries = header2->npartition_entries;
669 header->sizeof_partition_entry = header2->sizeof_partition_entry;
670 header->first_usable_lba = header2->first_usable_lba;
671 header->last_usable_lba = header2->last_usable_lba;
672
673 memcpy(&header->disk_guid,
674 &header2->disk_guid, sizeof(header2->disk_guid));
675 gpt_mknew_header_common(cxt, header, lba);
676
677 return 0;
678 }
679
680 static struct gpt_header *gpt_copy_header(struct fdisk_context *cxt,
681 struct gpt_header *src)
682 {
683 struct gpt_header *res;
684
685 if (!cxt || !src)
686 return NULL;
687
688 assert(cxt->sector_size >= sizeof(struct gpt_header));
689
690 res = calloc(1, cxt->sector_size);
691 if (!res) {
692 fdisk_warn(cxt, _("failed to allocate GPT header"));
693 return NULL;
694 }
695
696 res->my_lba = src->alternative_lba;
697 res->alternative_lba = src->my_lba;
698
699 res->signature = src->signature;
700 res->revision = src->revision;
701 res->size = src->size;
702 res->npartition_entries = src->npartition_entries;
703 res->sizeof_partition_entry = src->sizeof_partition_entry;
704 res->first_usable_lba = src->first_usable_lba;
705 res->last_usable_lba = src->last_usable_lba;
706
707 memcpy(&res->disk_guid, &src->disk_guid, sizeof(src->disk_guid));
708
709
710 if (res->my_lba == GPT_PRIMARY_PARTITION_TABLE_LBA)
711 res->partition_entry_lba = cpu_to_le64(2ULL);
712 else {
713 uint64_t esz = (uint64_t) le32_to_cpu(src->npartition_entries) * sizeof(struct gpt_entry);
714 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
715
716 res->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1ULL - esects);
717 }
718
719 return res;
720 }
721
722 static int get_script_u64(struct fdisk_context *cxt, uint64_t *num, const char *name)
723 {
724 const char *str;
725 int pwr = 0, rc = 0;
726
727 assert(cxt);
728
729 *num = 0;
730
731 if (!cxt->script)
732 return 1;
733
734 str = fdisk_script_get_header(cxt->script, name);
735 if (!str)
736 return 1;
737
738 rc = ul_parse_size(str, (uintmax_t *) num, &pwr);
739 if (rc < 0)
740 return rc;
741 if (pwr)
742 *num /= cxt->sector_size;
743 return 0;
744 }
745
746 static int count_first_last_lba(struct fdisk_context *cxt,
747 uint64_t *first, uint64_t *last,
748 uint32_t *maxents)
749 {
750 int rc = 0;
751 uint64_t flba = 0, llba = 0;
752 uint64_t nents = GPT_NPARTITIONS;
753
754 assert(cxt);
755 assert(first);
756 assert(last);
757
758 *first = *last = 0;
759
760 /* Get the table length from the script, if given */
761 if (cxt->script) {
762 rc = get_script_u64(cxt, &nents, "table-length");
763 if (rc == 1)
764 nents = GPT_NPARTITIONS; /* undefined by script */
765 else if (rc < 0)
766 return rc;
767 }
768
769 /* The table length was not changed by the script, compute it. */
770 if (flba == 0) {
771 /* If the device is not large enough reduce this number of
772 * partitions and try to recalculate it again, until we get
773 * something useful or return error.
774 */
775 for (; nents > 0; nents--) {
776 rc = gpt_calculate_last_lba(NULL, nents, &llba, cxt);
777 if (rc == 0)
778 rc = gpt_calculate_first_lba(NULL, nents, &flba, cxt);
779 if (llba < flba)
780 rc = -ENOSPC;
781 else if (rc == 0)
782 break;
783 }
784 }
785
786 if (rc)
787 return rc;
788 if (maxents)
789 *maxents = nents;
790
791 /* script default */
792 if (cxt->script) {
793 rc = get_script_u64(cxt, first, "first-lba");
794 if (rc < 0)
795 return rc;
796
797 DBG(GPT, ul_debug("FirstLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
798 *first, flba, (uintmax_t)cxt->first_lba));
799
800 if (rc == 0 && (*first < flba || *first > llba)) {
801 fdisk_warnx(cxt, _("First LBA specified by script is out of range."));
802 return -ERANGE;
803 }
804
805 rc = get_script_u64(cxt, last, "last-lba");
806 if (rc < 0)
807 return rc;
808
809 DBG(GPT, ul_debug("LastLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
810 *last, llba, (uintmax_t)cxt->last_lba));
811
812 if (rc == 0 && (*last > llba || *last < flba)) {
813 fdisk_warnx(cxt, _("Last LBA specified by script is out of range."));
814 return -ERANGE;
815 }
816 }
817
818 if (!*last)
819 *last = llba;
820
821 /* default by topology */
822 if (!*first)
823 *first = flba < cxt->first_lba &&
824 cxt->first_lba < *last ? cxt->first_lba : flba;
825 return 0;
826 }
827
828 /*
829 * Builds a clean new GPT header (currently under revision 1.0).
830 *
831 * Always pass a new (zeroized) header to build upon as we don't
832 * explicitly zero-set some values such as CRCs and reserved.
833 *
834 * Returns 0 on success, otherwise < 0 on error.
835 */
836 static int gpt_mknew_header(struct fdisk_context *cxt,
837 struct gpt_header *header, uint64_t lba)
838 {
839 uint64_t first, last;
840 uint32_t nents = 0;
841 int has_id = 0, rc;
842
843 if (!cxt || !header)
844 return -ENOSYS;
845
846 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
847 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
848
849 /* According to EFI standard it's valid to count all the first
850 * sector into header size, but some tools may have a problem
851 * to accept it, so use the header without the zeroed area.
852 * This does not have any impact to CRC, etc. --kzak Jan-2015
853 */
854 header->size = cpu_to_le32(sizeof(struct gpt_header)
855 - sizeof(header->reserved2));
856
857 /* Set {First,Last}LBA and number of the partitions
858 * (default is GPT_NPARTITIONS) */
859 rc = count_first_last_lba(cxt, &first, &last, &nents);
860 if (rc)
861 return rc;
862
863 header->npartition_entries = cpu_to_le32(nents);
864 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
865
866 header->first_usable_lba = cpu_to_le64(first);
867 header->last_usable_lba = cpu_to_le64(last);
868
869 gpt_mknew_header_common(cxt, header, lba);
870
871 if (cxt->script) {
872 const char *id = fdisk_script_get_header(cxt->script, "label-id");
873 struct gpt_guid guid = header->disk_guid;
874 if (id && string_to_guid(id, &guid) == 0)
875 has_id = 1;
876 header->disk_guid = guid;
877 }
878
879 if (!has_id) {
880 struct gpt_guid guid;
881
882 uuid_generate_random((unsigned char *) &guid);
883 swap_efi_guid(&guid);
884 header->disk_guid = guid;
885 }
886 return 0;
887 }
888
889 /*
890 * Checks if there is a valid protective MBR partition table.
891 * Returns 0 if it is invalid or failure. Otherwise, return
892 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depending on the detection.
893 */
894 static int valid_pmbr(struct fdisk_context *cxt)
895 {
896 int i, part = 0, ret = 0; /* invalid by default */
897 struct gpt_legacy_mbr *pmbr = NULL;
898
899 if (!cxt->firstsector)
900 goto done;
901
902 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
903
904 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
905 goto done;
906
907 /* seems like a valid MBR was found, check DOS primary partitions */
908 for (i = 0; i < 4; i++) {
909 if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
910 /*
911 * Ok, we at least know that there's a protective MBR,
912 * now check if there are other partition types for
913 * hybrid MBR.
914 */
915 part = i;
916 ret = GPT_MBR_PROTECTIVE;
917 break;
918 }
919 }
920
921 if (ret != GPT_MBR_PROTECTIVE)
922 goto done;
923
924
925 for (i = 0 ; i < 4; i++) {
926 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
927 (pmbr->partition_record[i].os_type != 0x00)) {
928 ret = GPT_MBR_HYBRID;
929 goto done;
930 }
931 }
932
933 /* LBA of the GPT partition header */
934 if (pmbr->partition_record[part].starting_lba !=
935 cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
936 goto done;
937
938 /*
939 * Protective MBRs take up the lesser of the whole disk
940 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
941 * Some partitioning programs, nonetheless, choose to set
942 * the size to the maximum 32-bit limitation, disregarding
943 * the disk size.
944 *
945 * Hybrid MBRs do not necessarily comply with this.
946 *
947 * Consider a bad value here to be a warning to support dd-ing
948 * an image from a smaller disk to a bigger disk.
949 */
950 if (ret == GPT_MBR_PROTECTIVE) {
951 uint64_t sz_lba = (uint64_t) le32_to_cpu(pmbr->partition_record[part].size_in_lba);
952 if (sz_lba != cxt->total_sectors - 1ULL && sz_lba != 0xFFFFFFFFULL) {
953
954 fdisk_warnx(cxt, _("GPT PMBR size mismatch (%"PRIu64" != %"PRIu64") "
955 "will be corrected by write."),
956 sz_lba, cxt->total_sectors - (uint64_t) 1);
957
958 /* Note that gpt_write_pmbr() overwrites PMBR, but we want to keep it valid already
959 * in memory too to disable warnings when valid_pmbr() called next time */
960 pmbr->partition_record[part].size_in_lba =
961 cpu_to_le32((uint32_t) min( cxt->total_sectors - 1ULL, 0xFFFFFFFFULL) );
962 fdisk_label_set_changed(cxt->label, 1);
963 }
964 }
965 done:
966 DBG(GPT, ul_debug("PMBR type: %s",
967 ret == GPT_MBR_PROTECTIVE ? "protective" :
968 ret == GPT_MBR_HYBRID ? "hybrid" : "???" ));
969 return ret;
970 }
971
972 static uint64_t last_lba(struct fdisk_context *cxt)
973 {
974 struct stat s;
975 uint64_t sectors = 0;
976
977 memset(&s, 0, sizeof(s));
978 if (fstat(cxt->dev_fd, &s) == -1) {
979 fdisk_warn(cxt, _("gpt: stat() failed"));
980 return 0;
981 }
982
983 if (S_ISBLK(s.st_mode))
984 sectors = cxt->total_sectors - 1ULL;
985 else if (S_ISREG(s.st_mode))
986 sectors = ((uint64_t) s.st_size /
987 (uint64_t) cxt->sector_size) - 1ULL;
988 else
989 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
990
991 DBG(GPT, ul_debug("last LBA: %"PRIu64"", sectors));
992 return sectors;
993 }
994
995 static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
996 void *buffer, const size_t bytes)
997 {
998 off_t offset = lba * cxt->sector_size;
999
1000 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
1001 return -1;
1002 return (size_t)read(cxt->dev_fd, buffer, bytes) != bytes;
1003 }
1004
1005
1006 /* Returns the GPT entry array */
1007 static unsigned char *gpt_read_entries(struct fdisk_context *cxt,
1008 struct gpt_header *header)
1009 {
1010 size_t sz = 0;
1011 ssize_t ssz;
1012
1013 unsigned char *ret = NULL;
1014 off_t offset;
1015
1016 assert(cxt);
1017 assert(header);
1018
1019 if (gpt_sizeof_entries(header, &sz))
1020 return NULL;
1021
1022 ret = calloc(1, sz);
1023 if (!ret)
1024 return NULL;
1025
1026 offset = (off_t) le64_to_cpu(header->partition_entry_lba) *
1027 cxt->sector_size;
1028
1029 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1030 goto fail;
1031
1032 ssz = read(cxt->dev_fd, ret, sz);
1033 if (ssz < 0 || (size_t) ssz != sz)
1034 goto fail;
1035
1036 return ret;
1037
1038 fail:
1039 free(ret);
1040 return NULL;
1041 }
1042
1043 static inline uint32_t count_crc32(const unsigned char *buf, size_t len,
1044 size_t ex_off, size_t ex_len)
1045 {
1046 return (ul_crc32_exclude_offset(~0L, buf, len, ex_off, ex_len, 0) ^ ~0L);
1047 }
1048
1049 static inline uint32_t gpt_header_count_crc32(struct gpt_header *header)
1050 {
1051 return count_crc32((unsigned char *) header, /* buffer */
1052 le32_to_cpu(header->size), /* size of buffer */
1053 offsetof(struct gpt_header, crc32), /* exclude */
1054 sizeof(header->crc32)); /* size of excluded area */
1055 }
1056
1057 static inline uint32_t gpt_entryarr_count_crc32(struct gpt_header *header, unsigned char *ents)
1058 {
1059 size_t arysz = 0;
1060
1061 if (gpt_sizeof_entries(header, &arysz))
1062 return 0;
1063
1064 return count_crc32(ents, arysz, 0, 0);
1065 }
1066
1067
1068 /*
1069 * Recompute header and partition array 32bit CRC checksums.
1070 * This function does not fail - if there's corruption, then it
1071 * will be reported when checksumming it again (ie: probing or verify).
1072 */
1073 static void gpt_recompute_crc(struct gpt_header *header, unsigned char *ents)
1074 {
1075 if (!header)
1076 return;
1077
1078 header->partition_entry_array_crc32 =
1079 cpu_to_le32( gpt_entryarr_count_crc32(header, ents) );
1080
1081 header->crc32 = cpu_to_le32( gpt_header_count_crc32(header) );
1082 }
1083
1084 /*
1085 * Compute the 32bit CRC checksum of the partition table header.
1086 * Returns 1 if it is valid, otherwise 0.
1087 */
1088 static int gpt_check_header_crc(struct gpt_header *header, unsigned char *ents)
1089 {
1090 uint32_t orgcrc = le32_to_cpu(header->crc32),
1091 crc = gpt_header_count_crc32(header);
1092
1093 if (crc == orgcrc)
1094 return 1;
1095
1096 /*
1097 * If we have checksum mismatch it may be due to stale data, like a
1098 * partition being added or deleted. Recompute the CRC again and make
1099 * sure this is not the case.
1100 */
1101 if (ents) {
1102 gpt_recompute_crc(header, ents);
1103 return gpt_header_count_crc32(header) == orgcrc;
1104 }
1105
1106 return 0;
1107 }
1108
1109 /*
1110 * It initializes the partition entry array.
1111 * Returns 1 if the checksum is valid, otherwise 0.
1112 */
1113 static int gpt_check_entryarr_crc(struct gpt_header *header, unsigned char *ents)
1114 {
1115 if (!header || !ents)
1116 return 0;
1117
1118 return gpt_entryarr_count_crc32(header, ents) ==
1119 le32_to_cpu(header->partition_entry_array_crc32);
1120 }
1121
1122 static int gpt_check_lba_sanity(struct fdisk_context *cxt, struct gpt_header *header)
1123 {
1124 int ret = 0;
1125 uint64_t lu, fu, lastlba = last_lba(cxt);
1126
1127 fu = le64_to_cpu(header->first_usable_lba);
1128 lu = le64_to_cpu(header->last_usable_lba);
1129
1130 /* check if first and last usable LBA make sense */
1131 if (lu < fu) {
1132 DBG(GPT, ul_debug("error: header last LBA is before first LBA"));
1133 goto done;
1134 }
1135
1136 /* check if first and last usable LBAs with the disk's last LBA */
1137 if (fu > lastlba || lu > lastlba) {
1138 DBG(GPT, ul_debug("error: header LBAs are after the disk's last LBA (%ju..%ju)",
1139 (uintmax_t) fu, (uintmax_t) lu));
1140 goto done;
1141 }
1142
1143 /* the header has to be outside usable range */
1144 if (fu < GPT_PRIMARY_PARTITION_TABLE_LBA &&
1145 GPT_PRIMARY_PARTITION_TABLE_LBA < lu) {
1146 DBG(GPT, ul_debug("error: header outside of usable range"));
1147 goto done;
1148 }
1149
1150 ret = 1; /* sane */
1151 done:
1152 return ret;
1153 }
1154
1155 /* Check if there is a valid header signature */
1156 static int gpt_check_signature(struct gpt_header *header)
1157 {
1158 return header->signature == cpu_to_le64(GPT_HEADER_SIGNATURE);
1159 }
1160
1161 /*
1162 * Return the specified GPT Header, or NULL upon failure/invalid.
1163 * Note that all tests must pass to ensure a valid header,
1164 * we do not rely on only testing the signature for a valid probe.
1165 */
1166 static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
1167 uint64_t lba,
1168 unsigned char **_ents)
1169 {
1170 struct gpt_header *header = NULL;
1171 unsigned char *ents = NULL;
1172 uint32_t hsz;
1173
1174 if (!cxt)
1175 return NULL;
1176
1177 /* always allocate all sector, the area after GPT header
1178 * has to be fill by zeros */
1179 assert(cxt->sector_size >= sizeof(struct gpt_header));
1180
1181 header = calloc(1, cxt->sector_size);
1182 if (!header)
1183 return NULL;
1184
1185 /* read and verify header */
1186 if (read_lba(cxt, lba, header, cxt->sector_size) != 0)
1187 goto invalid;
1188
1189 if (!gpt_check_signature(header))
1190 goto invalid;
1191
1192 /* make sure header size is between 92 and sector size bytes */
1193 hsz = le32_to_cpu(header->size);
1194 if (hsz < GPT_HEADER_MINSZ || hsz > cxt->sector_size)
1195 goto invalid;
1196
1197 if (!gpt_check_header_crc(header, NULL))
1198 goto invalid;
1199
1200 /* read and verify entries */
1201 ents = gpt_read_entries(cxt, header);
1202 if (!ents)
1203 goto invalid;
1204
1205 if (!gpt_check_entryarr_crc(header, ents))
1206 goto invalid;
1207
1208 if (!gpt_check_lba_sanity(cxt, header))
1209 goto invalid;
1210
1211 /* valid header must be at MyLBA */
1212 if (le64_to_cpu(header->my_lba) != lba)
1213 goto invalid;
1214
1215 if (_ents)
1216 *_ents = ents;
1217 else
1218 free(ents);
1219
1220 DBG(GPT, ul_debug("found valid header on LBA %"PRIu64"", lba));
1221 return header;
1222 invalid:
1223 free(header);
1224 free(ents);
1225
1226 DBG(GPT, ul_debug("read header on LBA %"PRIu64" failed", lba));
1227 return NULL;
1228 }
1229
1230
1231 static int gpt_locate_disklabel(struct fdisk_context *cxt, int n,
1232 const char **name, uint64_t *offset, size_t *size)
1233 {
1234 struct fdisk_gpt_label *gpt;
1235
1236 assert(cxt);
1237
1238 *name = NULL;
1239 *offset = 0;
1240 *size = 0;
1241
1242 switch (n) {
1243 case 0:
1244 *name = "PMBR";
1245 *offset = 0;
1246 *size = 512;
1247 break;
1248 case 1:
1249 *name = _("GPT Header");
1250 *offset = (uint64_t) GPT_PRIMARY_PARTITION_TABLE_LBA * cxt->sector_size;
1251 *size = sizeof(struct gpt_header);
1252 break;
1253 case 2:
1254 *name = _("GPT Entries");
1255 gpt = self_label(cxt);
1256 *offset = (uint64_t) le64_to_cpu(gpt->pheader->partition_entry_lba) *
1257 cxt->sector_size;
1258 return gpt_sizeof_entries(gpt->pheader, size);
1259 case 3:
1260 *name = _("GPT Backup Entries");
1261 gpt = self_label(cxt);
1262 *offset = (uint64_t) le64_to_cpu(gpt->bheader->partition_entry_lba) *
1263 cxt->sector_size;
1264 return gpt_sizeof_entries(gpt->bheader, size);
1265 case 4:
1266 *name = _("GPT Backup Header");
1267 gpt = self_label(cxt);
1268 *offset = (uint64_t) le64_to_cpu(gpt->pheader->alternative_lba) * cxt->sector_size;
1269 *size = sizeof(struct gpt_header);
1270 break;
1271 default:
1272 return 1; /* no more chunks */
1273 }
1274
1275 return 0;
1276 }
1277
1278 static int gpt_get_disklabel_item(struct fdisk_context *cxt, struct fdisk_labelitem *item)
1279 {
1280 struct gpt_header *h;
1281 int rc = 0;
1282 uint64_t x = 0;
1283
1284 assert(cxt);
1285 assert(cxt->label);
1286 assert(fdisk_is_label(cxt, GPT));
1287
1288 h = self_label(cxt)->pheader;
1289
1290 switch (item->id) {
1291 case GPT_LABELITEM_ID:
1292 item->name = _("Disk identifier");
1293 item->type = 's';
1294 item->data.str = gpt_get_header_id(h);
1295 if (!item->data.str)
1296 rc = -ENOMEM;
1297 break;
1298 case GPT_LABELITEM_FIRSTLBA:
1299 item->name = _("First usable LBA");
1300 item->type = 'j';
1301 item->data.num64 = le64_to_cpu(h->first_usable_lba);
1302 break;
1303 case GPT_LABELITEM_LASTLBA:
1304 item->name = _("Last usable LBA");
1305 item->type = 'j';
1306 item->data.num64 = le64_to_cpu(h->last_usable_lba);
1307 break;
1308 case GPT_LABELITEM_ALTLBA:
1309 /* TRANSLATORS: The LBA (Logical Block Address) of the backup GPT header. */
1310 item->name = _("Alternative LBA");
1311 item->type = 'j';
1312 item->data.num64 = le64_to_cpu(h->alternative_lba);
1313 break;
1314 case GPT_LABELITEM_ENTRIESLBA:
1315 /* TRANSLATORS: The start of the array of partition entries. */
1316 item->name = _("Partition entries starting LBA");
1317 item->type = 'j';
1318 item->data.num64 = le64_to_cpu(h->partition_entry_lba);
1319 break;
1320 case GPT_LABELITEM_ENTRIESLASTLBA:
1321 /* TRANSLATORS: The end of the array of partition entries. */
1322 item->name = _("Partition entries ending LBA");
1323 item->type = 'j';
1324 gpt_calculate_sectorsof_entries(h,
1325 le32_to_cpu(h->npartition_entries), &x, cxt);
1326 item->data.num64 = le64_to_cpu(h->partition_entry_lba) + x - 1;
1327 break;
1328 case GPT_LABELITEM_ENTRIESALLOC:
1329 item->name = _("Allocated partition entries");
1330 item->type = 'j';
1331 item->data.num64 = le32_to_cpu(h->npartition_entries);
1332 break;
1333 default:
1334 if (item->id < __FDISK_NLABELITEMS)
1335 rc = 1; /* unsupported generic item */
1336 else
1337 rc = 2; /* out of range */
1338 break;
1339 }
1340
1341 return rc;
1342 }
1343
1344 /*
1345 * Returns the number of partitions that are in use.
1346 */
1347 static size_t partitions_in_use(struct fdisk_gpt_label *gpt)
1348 {
1349 size_t i, used = 0;
1350
1351 assert(gpt);
1352 assert(gpt->pheader);
1353 assert(gpt->ents);
1354
1355 for (i = 0; i < gpt_get_nentries(gpt); i++) {
1356 struct gpt_entry *e = gpt_get_entry(gpt, i);
1357
1358 if (gpt_entry_is_used(e))
1359 used++;
1360 }
1361 return used;
1362 }
1363
1364
1365 /*
1366 * Check if a partition is too big for the disk (sectors).
1367 * Returns the faulting partition number, otherwise 0.
1368 */
1369 static uint32_t check_too_big_partitions(struct fdisk_gpt_label *gpt, uint64_t sectors)
1370 {
1371 size_t i;
1372
1373 assert(gpt);
1374 assert(gpt->pheader);
1375 assert(gpt->ents);
1376
1377 for (i = 0; i < gpt_get_nentries(gpt); i++) {
1378 struct gpt_entry *e = gpt_get_entry(gpt, i);
1379
1380 if (!gpt_entry_is_used(e))
1381 continue;
1382 if (gpt_partition_end(e) >= sectors)
1383 return i + 1;
1384 }
1385
1386 return 0;
1387 }
1388
1389 /*
1390 * Check if a partition ends before it begins
1391 * Returns the faulting partition number, otherwise 0.
1392 */
1393 static uint32_t check_start_after_end_partitions(struct fdisk_gpt_label *gpt)
1394 {
1395 size_t i;
1396
1397 assert(gpt);
1398 assert(gpt->pheader);
1399 assert(gpt->ents);
1400
1401 for (i = 0; i < gpt_get_nentries(gpt); i++) {
1402 struct gpt_entry *e = gpt_get_entry(gpt, i);
1403
1404 if (!gpt_entry_is_used(e))
1405 continue;
1406 if (gpt_partition_start(e) > gpt_partition_end(e))
1407 return i + 1;
1408 }
1409
1410 return 0;
1411 }
1412
1413 /*
1414 * Check if partition e1 overlaps with partition e2.
1415 */
1416 static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
1417 {
1418 uint64_t start1 = gpt_partition_start(e1);
1419 uint64_t end1 = gpt_partition_end(e1);
1420 uint64_t start2 = gpt_partition_start(e2);
1421 uint64_t end2 = gpt_partition_end(e2);
1422
1423 return (start1 && start2 && (start1 <= end2) != (end1 < start2));
1424 }
1425
1426 /*
1427 * Find any partitions that overlap.
1428 */
1429 static uint32_t check_overlap_partitions(struct fdisk_gpt_label *gpt)
1430 {
1431 size_t i, j;
1432
1433 assert(gpt);
1434 assert(gpt->pheader);
1435 assert(gpt->ents);
1436
1437 for (i = 0; i < gpt_get_nentries(gpt); i++)
1438 for (j = 0; j < i; j++) {
1439 struct gpt_entry *ei = gpt_get_entry(gpt, i);
1440 struct gpt_entry *ej = gpt_get_entry(gpt, j);
1441
1442 if (!gpt_entry_is_used(ei) || !gpt_entry_is_used(ej))
1443 continue;
1444 if (partition_overlap(ei, ej)) {
1445 DBG(GPT, ul_debug("partitions overlap detected [%zu vs. %zu]", i, j));
1446 return i + 1;
1447 }
1448 }
1449
1450 return 0;
1451 }
1452
1453 /*
1454 * Find the first available block after the starting point; returns 0 if
1455 * there are no available blocks left, or error. From gdisk.
1456 */
1457 static uint64_t find_first_available(struct fdisk_gpt_label *gpt, uint64_t start)
1458 {
1459 int first_moved = 0;
1460 uint64_t first;
1461 uint64_t fu, lu;
1462
1463 assert(gpt);
1464 assert(gpt->pheader);
1465 assert(gpt->ents);
1466
1467 fu = le64_to_cpu(gpt->pheader->first_usable_lba);
1468 lu = le64_to_cpu(gpt->pheader->last_usable_lba);
1469
1470 /*
1471 * Begin from the specified starting point or from the first usable
1472 * LBA, whichever is greater...
1473 */
1474 first = start < fu ? fu : start;
1475
1476 /*
1477 * Now search through all partitions; if first is within an
1478 * existing partition, move it to the next sector after that
1479 * partition and repeat. If first was moved, set firstMoved
1480 * flag; repeat until firstMoved is not set, so as to catch
1481 * cases where partitions are out of sequential order....
1482 */
1483 do {
1484 size_t i;
1485
1486 first_moved = 0;
1487 for (i = 0; i < gpt_get_nentries(gpt); i++) {
1488 struct gpt_entry *e = gpt_get_entry(gpt, i);
1489
1490 if (!gpt_entry_is_used(e))
1491 continue;
1492 if (first < gpt_partition_start(e))
1493 continue;
1494 if (first <= gpt_partition_end(e)) {
1495 first = gpt_partition_end(e) + 1;
1496 first_moved = 1;
1497 }
1498 }
1499 } while (first_moved == 1);
1500
1501 if (first > lu)
1502 first = 0;
1503
1504 return first;
1505 }
1506
1507
1508 /* Returns last available sector in the free space pointed to by start. From gdisk. */
1509 static uint64_t find_last_free(struct fdisk_gpt_label *gpt, uint64_t start)
1510 {
1511 size_t i;
1512 uint64_t nearest_start;
1513
1514 assert(gpt);
1515 assert(gpt->pheader);
1516 assert(gpt->ents);
1517
1518 nearest_start = le64_to_cpu(gpt->pheader->last_usable_lba);
1519
1520 for (i = 0; i < gpt_get_nentries(gpt); i++) {
1521 struct gpt_entry *e = gpt_get_entry(gpt, i);
1522 uint64_t ps = gpt_partition_start(e);
1523
1524 if (nearest_start > ps && ps > start)
1525 nearest_start = ps - 1ULL;
1526 }
1527
1528 return nearest_start;
1529 }
1530
1531 /* Returns the last free sector on the disk. From gdisk. */
1532 static uint64_t find_last_free_sector(struct fdisk_gpt_label *gpt)
1533 {
1534 int last_moved;
1535 uint64_t last = 0;
1536
1537 assert(gpt);
1538 assert(gpt->pheader);
1539 assert(gpt->ents);
1540
1541 /* start by assuming the last usable LBA is available */
1542 last = le64_to_cpu(gpt->pheader->last_usable_lba);
1543 do {
1544 size_t i;
1545
1546 last_moved = 0;
1547 for (i = 0; i < gpt_get_nentries(gpt); i++) {
1548 struct gpt_entry *e = gpt_get_entry(gpt, i);
1549
1550 if (last >= gpt_partition_start(e) &&
1551 last <= gpt_partition_end(e)) {
1552 last = gpt_partition_start(e) - 1ULL;
1553 last_moved = 1;
1554 }
1555 }
1556 } while (last_moved == 1);
1557
1558 return last;
1559 }
1560
1561 /*
1562 * Finds the first available sector in the largest block of unallocated
1563 * space on the disk. Returns 0 if there are no available blocks left.
1564 * From gdisk.
1565 */
1566 static uint64_t find_first_in_largest(struct fdisk_gpt_label *gpt)
1567 {
1568 uint64_t start = 0, first_sect, last_sect;
1569 uint64_t segment_size, selected_size = 0, selected_segment = 0;
1570
1571 assert(gpt);
1572 assert(gpt->pheader);
1573 assert(gpt->ents);
1574
1575 do {
1576 first_sect = find_first_available(gpt, start);
1577 if (first_sect != 0) {
1578 last_sect = find_last_free(gpt, first_sect);
1579 segment_size = last_sect - first_sect + 1ULL;
1580
1581 if (segment_size > selected_size) {
1582 selected_size = segment_size;
1583 selected_segment = first_sect;
1584 }
1585 start = last_sect + 1ULL;
1586 }
1587 } while (first_sect != 0);
1588
1589 return selected_segment;
1590 }
1591
1592 /*
1593 * Find the total number of free sectors, the number of segments in which
1594 * they reside, and the size of the largest of those segments. From gdisk.
1595 */
1596 static uint64_t get_free_sectors(struct fdisk_context *cxt,
1597 struct fdisk_gpt_label *gpt,
1598 uint32_t *nsegments,
1599 uint64_t *largest_segment)
1600 {
1601 uint32_t num = 0;
1602 uint64_t first_sect, last_sect;
1603 uint64_t largest_seg = 0, segment_sz;
1604 uint64_t totfound = 0, start = 0; /* starting point for each search */
1605
1606 if (!cxt->total_sectors)
1607 goto done;
1608
1609 assert(gpt);
1610 assert(gpt->pheader);
1611 assert(gpt->ents);
1612
1613 do {
1614 first_sect = find_first_available(gpt, start);
1615 if (first_sect) {
1616 last_sect = find_last_free(gpt, first_sect);
1617 segment_sz = last_sect - first_sect + 1;
1618
1619 if (segment_sz > largest_seg)
1620 largest_seg = segment_sz;
1621 totfound += segment_sz;
1622 num++;
1623 start = last_sect + 1ULL;
1624 }
1625 } while (first_sect);
1626
1627 done:
1628 if (nsegments)
1629 *nsegments = num;
1630 if (largest_segment)
1631 *largest_segment = largest_seg;
1632
1633 return totfound;
1634 }
1635
1636 static int gpt_probe_label(struct fdisk_context *cxt)
1637 {
1638 int mbr_type;
1639 struct fdisk_gpt_label *gpt;
1640
1641 assert(cxt);
1642 assert(cxt->label);
1643 assert(fdisk_is_label(cxt, GPT));
1644
1645 gpt = self_label(cxt);
1646
1647 /* TODO: it would be nice to support scenario when GPT headers are OK,
1648 * but PMBR is corrupt */
1649 mbr_type = valid_pmbr(cxt);
1650 if (!mbr_type)
1651 goto failed;
1652
1653 /* primary header */
1654 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1655 &gpt->ents);
1656
1657 if (gpt->pheader)
1658 /* primary OK, try backup from alternative LBA */
1659 gpt->bheader = gpt_read_header(cxt,
1660 le64_to_cpu(gpt->pheader->alternative_lba),
1661 NULL);
1662 else
1663 /* primary corrupted -- try last LBA */
1664 gpt->bheader = gpt_read_header(cxt, last_lba(cxt), &gpt->ents);
1665
1666 if (!gpt->pheader && !gpt->bheader)
1667 goto failed;
1668
1669 /* primary OK, backup corrupted -- recovery */
1670 if (gpt->pheader && !gpt->bheader) {
1671 fdisk_warnx(cxt, _("The backup GPT table is corrupt, but the "
1672 "primary appears OK, so that will be used."));
1673 gpt->bheader = gpt_copy_header(cxt, gpt->pheader);
1674 if (!gpt->bheader)
1675 goto failed;
1676 gpt_recompute_crc(gpt->bheader, gpt->ents);
1677 fdisk_label_set_changed(cxt->label, 1);
1678
1679 /* primary corrupted, backup OK -- recovery */
1680 } else if (!gpt->pheader && gpt->bheader) {
1681 fdisk_warnx(cxt, _("The primary GPT table is corrupt, but the "
1682 "backup appears OK, so that will be used."));
1683 gpt->pheader = gpt_copy_header(cxt, gpt->bheader);
1684 if (!gpt->pheader)
1685 goto failed;
1686 gpt_recompute_crc(gpt->pheader, gpt->ents);
1687 fdisk_label_set_changed(cxt->label, 1);
1688 }
1689
1690 /* The headers make be correct, but Backup do not have to be on the end
1691 * of the device (due to device resize, etc.). Let's fix this issue. */
1692 if (gpt->minimize == 0 &&
1693 (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors ||
1694 le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1ULL)) {
1695
1696 if (gpt->no_relocate || fdisk_is_readonly(cxt))
1697 fdisk_warnx(cxt, _("The backup GPT table is not on the end of the device."));
1698
1699 else {
1700 fdisk_warnx(cxt, _("The backup GPT table is not on the end of the device. "
1701 "This problem will be corrected by write."));
1702
1703 if (gpt_fix_alternative_lba(cxt, gpt) != 0)
1704 fdisk_warnx(cxt, _("Failed to recalculate backup GPT table location"));
1705 gpt_recompute_crc(gpt->bheader, gpt->ents);
1706 gpt_recompute_crc(gpt->pheader, gpt->ents);
1707 fdisk_label_set_changed(cxt->label, 1);
1708 }
1709 }
1710
1711 if (gpt->minimize && gpt_possible_minimize(cxt, gpt))
1712 fdisk_label_set_changed(cxt->label, 1);
1713
1714 cxt->label->nparts_max = gpt_get_nentries(gpt);
1715 cxt->label->nparts_cur = partitions_in_use(gpt);
1716 return 1;
1717 failed:
1718 DBG(GPT, ul_debug("probe failed"));
1719 gpt_deinit(cxt->label);
1720 return 0;
1721 }
1722
1723 static char *encode_to_utf8(unsigned char *src, size_t count)
1724 {
1725 unsigned char *dest;
1726 size_t len = (count * 3 / 2) + 1;
1727
1728 dest = calloc(1, len);
1729 if (!dest)
1730 return NULL;
1731
1732 ul_encode_to_utf8(UL_ENCODE_UTF16LE, dest, len, src, count);
1733 return (char *) dest;
1734 }
1735
1736 static int gpt_entry_attrs_to_string(struct gpt_entry *e, char **res)
1737 {
1738 unsigned int n, count = 0;
1739 size_t l, res_size;
1740 char *bits, *p;
1741 uint64_t attrs;
1742
1743 assert(e);
1744 assert(res);
1745
1746 *res = NULL;
1747 attrs = e->attrs;
1748 if (!attrs)
1749 return 0; /* no attributes at all */
1750
1751 bits = (char *) &attrs;
1752
1753 /* Note that sizeof() is correct here, we need separators between
1754 * the strings so also count \0 is correct */
1755 res_size = sizeof(GPT_ATTRSTR_NOBLOCK) +
1756 sizeof(GPT_ATTRSTR_REQ) +
1757 sizeof(GPT_ATTRSTR_LEGACY) +
1758 sizeof("GUID:") + (GPT_ATTRBIT_GUID_COUNT * 3);
1759 *res = calloc(1, res_size);
1760 if (!*res)
1761 return -errno;
1762
1763 p = *res;
1764 if (isset(bits, GPT_ATTRBIT_REQ)) {
1765 memcpy(p, GPT_ATTRSTR_REQ, (l = sizeof(GPT_ATTRSTR_REQ)));
1766 p += l - 1;
1767 }
1768 if (isset(bits, GPT_ATTRBIT_NOBLOCK)) {
1769 if (p != *res)
1770 *p++ = ' ';
1771 memcpy(p, GPT_ATTRSTR_NOBLOCK, (l = sizeof(GPT_ATTRSTR_NOBLOCK)));
1772 p += l - 1;
1773 }
1774 if (isset(bits, GPT_ATTRBIT_LEGACY)) {
1775 if (p != *res)
1776 *p++ = ' ';
1777 memcpy(p, GPT_ATTRSTR_LEGACY, (l = sizeof(GPT_ATTRSTR_LEGACY)));
1778 p += l - 1;
1779 }
1780
1781 for (n = GPT_ATTRBIT_GUID_FIRST;
1782 n < GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT; n++) {
1783 int rc;
1784
1785 if (!isset(bits, n))
1786 continue;
1787 if (!count) {
1788 if (p != *res)
1789 *p++ = ' ';
1790 rc = snprintf(p, res_size - (p - *res), "GUID:%u", n);
1791 } else
1792 rc = snprintf(p, res_size - (p - *res), ",%u", n);
1793
1794 if (rc < 0 || (size_t) rc >= res_size - (p - *res))
1795 break;
1796 p += rc;
1797 count++;
1798 }
1799
1800 return 0;
1801 }
1802
1803 static int gpt_entry_attrs_from_string(
1804 struct fdisk_context *cxt,
1805 struct gpt_entry *e,
1806 const char *str)
1807 {
1808 const char *p = str;
1809 uint64_t attrs = 0;
1810 char *bits;
1811
1812 assert(e);
1813 assert(p);
1814
1815 DBG(GPT, ul_debug("parsing string attributes '%s'", p));
1816
1817 bits = (char *) &attrs;
1818
1819 while (p && *p) {
1820 int bit = -1;
1821
1822 while (isblank(*p)) p++;
1823 if (!*p)
1824 break;
1825
1826 DBG(GPT, ul_debug(" item '%s'", p));
1827
1828 if (strncmp(p, GPT_ATTRSTR_REQ,
1829 sizeof(GPT_ATTRSTR_REQ) - 1) == 0) {
1830 bit = GPT_ATTRBIT_REQ;
1831 p += sizeof(GPT_ATTRSTR_REQ) - 1;
1832 } else if (strncmp(p, GPT_ATTRSTR_REQ_TYPO,
1833 sizeof(GPT_ATTRSTR_REQ_TYPO) - 1) == 0) {
1834 bit = GPT_ATTRBIT_REQ;
1835 p += sizeof(GPT_ATTRSTR_REQ_TYPO) - 1;
1836 } else if (strncmp(p, GPT_ATTRSTR_LEGACY,
1837 sizeof(GPT_ATTRSTR_LEGACY) - 1) == 0) {
1838 bit = GPT_ATTRBIT_LEGACY;
1839 p += sizeof(GPT_ATTRSTR_LEGACY) - 1;
1840 } else if (strncmp(p, GPT_ATTRSTR_NOBLOCK,
1841 sizeof(GPT_ATTRSTR_NOBLOCK) - 1) == 0) {
1842 bit = GPT_ATTRBIT_NOBLOCK;
1843 p += sizeof(GPT_ATTRSTR_NOBLOCK) - 1;
1844
1845 /* GUID:<bit> as well as <bit> */
1846 } else if (isdigit((unsigned char) *p)
1847 || (strncmp(p, "GUID:", 5) == 0
1848 && isdigit((unsigned char) *(p + 5)))) {
1849 char *end = NULL;
1850
1851 if (*p == 'G')
1852 p += 5;
1853
1854 errno = 0;
1855 bit = strtol(p, &end, 0);
1856 if (errno || !end || end == str
1857 || bit < GPT_ATTRBIT_GUID_FIRST
1858 || bit >= GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT)
1859 bit = -1;
1860 else
1861 p = end;
1862 }
1863
1864 if (bit < 0) {
1865 fdisk_warnx(cxt, _("unsupported GPT attribute bit '%s'"), p);
1866 return -EINVAL;
1867 }
1868
1869 if (*p && *p != ',' && !isblank(*p)) {
1870 fdisk_warnx(cxt, _("failed to parse GPT attribute string '%s'"), str);
1871 return -EINVAL;
1872 }
1873
1874 setbit(bits, bit);
1875
1876 while (isblank(*p)) p++;
1877 if (*p == ',')
1878 p++;
1879 }
1880
1881 e->attrs = attrs;
1882 return 0;
1883 }
1884
1885 static int gpt_get_partition(struct fdisk_context *cxt, size_t n,
1886 struct fdisk_partition *pa)
1887 {
1888 struct fdisk_gpt_label *gpt;
1889 struct gpt_entry *e;
1890 char u_str[UUID_STR_LEN];
1891 int rc = 0;
1892 struct gpt_guid guid;
1893
1894 assert(cxt);
1895 assert(cxt->label);
1896 assert(fdisk_is_label(cxt, GPT));
1897
1898 gpt = self_label(cxt);
1899
1900 if (n >= gpt_get_nentries(gpt))
1901 return -EINVAL;
1902
1903 gpt = self_label(cxt);
1904 e = gpt_get_entry(gpt, n);
1905
1906 pa->used = gpt_entry_is_used(e) || gpt_partition_start(e);
1907 if (!pa->used)
1908 return 0;
1909
1910 pa->start = gpt_partition_start(e);
1911 pa->size = gpt_partition_size(e);
1912 pa->type = gpt_partition_parttype(cxt, e);
1913
1914 guid = e->partition_guid;
1915 if (guid_to_string(&guid, u_str)) {
1916 pa->uuid = strdup(u_str);
1917 if (!pa->uuid) {
1918 rc = -errno;
1919 goto done;
1920 }
1921 } else
1922 pa->uuid = NULL;
1923
1924 rc = gpt_entry_attrs_to_string(e, &pa->attrs);
1925 if (rc)
1926 goto done;
1927
1928 pa->name = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1929 return 0;
1930 done:
1931 fdisk_reset_partition(pa);
1932 return rc;
1933 }
1934
1935
1936 static int gpt_set_partition(struct fdisk_context *cxt, size_t n,
1937 struct fdisk_partition *pa)
1938 {
1939 struct fdisk_gpt_label *gpt;
1940 struct gpt_entry *e;
1941 int rc = 0;
1942 uint64_t start, end;
1943
1944 assert(cxt);
1945 assert(cxt->label);
1946 assert(fdisk_is_label(cxt, GPT));
1947
1948 gpt = self_label(cxt);
1949
1950 if (n >= gpt_get_nentries(gpt))
1951 return -EINVAL;
1952
1953 FDISK_INIT_UNDEF(start);
1954 FDISK_INIT_UNDEF(end);
1955
1956 gpt = self_label(cxt);
1957 e = gpt_get_entry(gpt, n);
1958
1959 if (pa->uuid) {
1960 char new_u[UUID_STR_LEN], old_u[UUID_STR_LEN];
1961 struct gpt_guid guid;
1962
1963 guid = e->partition_guid;
1964 guid_to_string(&guid, old_u);
1965 rc = gpt_entry_set_uuid(e, pa->uuid);
1966 if (rc)
1967 return rc;
1968 guid = e->partition_guid;
1969 guid_to_string(&guid, new_u);
1970 fdisk_info(cxt, _("Partition UUID changed from %s to %s."),
1971 old_u, new_u);
1972 }
1973
1974 if (pa->name) {
1975 int len;
1976 char *old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1977 len = gpt_entry_set_name(e, pa->name);
1978 if (len < 0)
1979 fdisk_warn(cxt, _("Failed to translate partition name, name not changed."));
1980 else
1981 fdisk_info(cxt, _("Partition name changed from '%s' to '%.*s'."),
1982 old, len, pa->name);
1983 free(old);
1984 }
1985
1986 if (pa->type && pa->type->typestr) {
1987 struct gpt_guid typeid;
1988
1989 rc = string_to_guid(pa->type->typestr, &typeid);
1990 if (rc)
1991 return rc;
1992 gpt_entry_set_type(e, &typeid);
1993 }
1994 if (pa->attrs) {
1995 rc = gpt_entry_attrs_from_string(cxt, e, pa->attrs);
1996 if (rc)
1997 return rc;
1998 }
1999
2000 if (fdisk_partition_has_start(pa))
2001 start = pa->start;
2002 if (fdisk_partition_has_size(pa) || fdisk_partition_has_start(pa)) {
2003 uint64_t xstart = fdisk_partition_has_start(pa) ? pa->start : gpt_partition_start(e);
2004 uint64_t xsize = fdisk_partition_has_size(pa) ? pa->size : gpt_partition_size(e);
2005 end = xstart + xsize - 1ULL;
2006 }
2007
2008 if (!FDISK_IS_UNDEF(start)) {
2009 if (start < le64_to_cpu(gpt->pheader->first_usable_lba)) {
2010 fdisk_warnx(cxt, _("The start of the partition understeps FirstUsableLBA."));
2011 return -EINVAL;
2012 }
2013 e->lba_start = cpu_to_le64(start);
2014 }
2015 if (!FDISK_IS_UNDEF(end)) {
2016 if (end > le64_to_cpu(gpt->pheader->last_usable_lba)) {
2017 fdisk_warnx(cxt, _("The end of the partition oversteps LastUsableLBA."));
2018 return -EINVAL;
2019 }
2020 e->lba_end = cpu_to_le64(end);
2021 }
2022 gpt_recompute_crc(gpt->pheader, gpt->ents);
2023 gpt_recompute_crc(gpt->bheader, gpt->ents);
2024
2025 fdisk_label_set_changed(cxt->label, 1);
2026 return rc;
2027 }
2028
2029 static int gpt_read(struct fdisk_context *cxt, off_t offset, void *buf, size_t count)
2030 {
2031 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
2032 return -errno;
2033
2034 if (read_all(cxt->dev_fd, buf, count))
2035 return -errno;
2036
2037 DBG(GPT, ul_debug(" read OK [offset=%zu, size=%zu]",
2038 (size_t) offset, count));
2039 return 0;
2040 }
2041
2042 static int gpt_write(struct fdisk_context *cxt, off_t offset, void *buf, size_t count)
2043 {
2044 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
2045 return -errno;
2046
2047 if (write_all(cxt->dev_fd, buf, count))
2048 return -errno;
2049
2050 if (fsync(cxt->dev_fd) != 0)
2051 return -errno;
2052
2053 DBG(GPT, ul_debug(" write OK [offset=%zu, size=%zu]",
2054 (size_t) offset, count));
2055 return 0;
2056 }
2057
2058 /*
2059 * Write partitions.
2060 * Returns 0 on success, or corresponding error otherwise.
2061 */
2062 static int gpt_write_partitions(struct fdisk_context *cxt,
2063 struct gpt_header *header, unsigned char *ents)
2064 {
2065 size_t esz = 0;
2066 int rc;
2067
2068 rc = gpt_sizeof_entries(header, &esz);
2069 if (rc)
2070 return rc;
2071
2072 return gpt_write(cxt,
2073 (off_t) le64_to_cpu(header->partition_entry_lba) * cxt->sector_size,
2074 ents, esz);
2075 }
2076
2077 /*
2078 * Write a GPT header to a specified LBA.
2079 *
2080 * We read all sector, so we have to write all sector back
2081 * to the device -- never ever rely on sizeof(struct gpt_header)!
2082 *
2083 * Returns 0 on success, or corresponding error otherwise.
2084 */
2085 static int gpt_write_header(struct fdisk_context *cxt,
2086 struct gpt_header *header, uint64_t lba)
2087 {
2088 return gpt_write(cxt, lba * cxt->sector_size, header, cxt->sector_size);
2089 }
2090
2091 /*
2092 * Write the protective MBR.
2093 * Returns 0 on success, or corresponding error otherwise.
2094 */
2095 static int gpt_write_pmbr(struct fdisk_context *cxt)
2096 {
2097 struct gpt_legacy_mbr *pmbr;
2098 struct gpt_legacy_mbr *current;
2099 int rc;
2100
2101 assert(cxt);
2102 assert(cxt->firstsector);
2103
2104 DBG(GPT, ul_debug("(over)writing PMBR"));
2105 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
2106
2107 /* zero out the legacy partitions */
2108 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
2109
2110 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
2111 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
2112 pmbr->partition_record[0].start_sector = 2;
2113 pmbr->partition_record[0].end_head = 0xFF;
2114 pmbr->partition_record[0].end_sector = 0xFF;
2115 pmbr->partition_record[0].end_track = 0xFF;
2116 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
2117
2118 /*
2119 * Set size_in_lba to the size of the disk minus one. If the size of the disk
2120 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
2121 */
2122 if (cxt->total_sectors - 1ULL > 0xFFFFFFFFULL)
2123 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
2124 else
2125 pmbr->partition_record[0].size_in_lba =
2126 cpu_to_le32((uint32_t) (cxt->total_sectors - 1ULL));
2127
2128 /* Read the current PMBR and compare it with the new, don't write if
2129 * the same. */
2130 current = malloc(sizeof(*current));
2131 if (!current)
2132 goto do_write;
2133
2134 rc = gpt_read(cxt, GPT_PMBR_LBA * cxt->sector_size,
2135 current, sizeof(*current));
2136 if (!rc)
2137 rc = memcmp(pmbr, current, sizeof(*current));
2138
2139 free(current);
2140
2141 if (!rc) {
2142 DBG(GPT, ul_debug("Same MBR on disk => don't write it"));
2143 return 0;
2144 }
2145
2146 do_write:
2147 /* pMBR covers the first sector (LBA) of the disk */
2148 return gpt_write(cxt, GPT_PMBR_LBA * cxt->sector_size,
2149 pmbr, cxt->sector_size);
2150 }
2151
2152 /*
2153 * Writes in-memory GPT and pMBR data to disk.
2154 * Returns 0 if successful write, otherwise, a corresponding error.
2155 * Any indication of error will abort the operation.
2156 */
2157 static int gpt_write_disklabel(struct fdisk_context *cxt)
2158 {
2159 struct fdisk_gpt_label *gpt;
2160 int mbr_type;
2161
2162 assert(cxt);
2163 assert(cxt->label);
2164 assert(fdisk_is_label(cxt, GPT));
2165
2166 DBG(GPT, ul_debug("writing..."));
2167
2168 gpt = self_label(cxt);
2169 mbr_type = valid_pmbr(cxt);
2170
2171 /* check that disk is big enough to handle the backup header */
2172 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
2173 goto err0;
2174
2175 /* check that the backup header is properly placed */
2176 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1ULL)
2177 goto err0;
2178
2179 if (check_overlap_partitions(gpt))
2180 goto err0;
2181
2182 if (gpt->minimize)
2183 gpt_minimize_alternative_lba(cxt, gpt);
2184
2185 /* recompute CRCs for both headers */
2186 gpt_recompute_crc(gpt->pheader, gpt->ents);
2187 gpt_recompute_crc(gpt->bheader, gpt->ents);
2188
2189 /*
2190 * UEFI requires writing in this specific order:
2191 * 1) backup partition tables
2192 * 2) backup GPT header
2193 * 3) primary partition tables
2194 * 4) primary GPT header
2195 * 5) protective MBR
2196 *
2197 * If any write fails, we abort the rest.
2198 */
2199 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
2200 goto err1;
2201 if (gpt_write_header(cxt, gpt->bheader,
2202 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
2203 goto err1;
2204 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
2205 goto err1;
2206 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
2207 goto err1;
2208
2209 if (mbr_type == GPT_MBR_HYBRID)
2210 fdisk_warnx(cxt, _("The device contains hybrid MBR -- writing GPT only."));
2211 else if (gpt_write_pmbr(cxt) != 0)
2212 goto err1;
2213
2214 DBG(GPT, ul_debug("...write success"));
2215 return 0;
2216 err0:
2217 DBG(GPT, ul_debug("...write failed: incorrect input"));
2218 errno = EINVAL;
2219 return -EINVAL;
2220 err1:
2221 DBG(GPT, ul_debug("...write failed: %m"));
2222 return -errno;
2223 }
2224
2225 /*
2226 * Verify data integrity and report any found problems for:
2227 * - primary and backup header validations
2228 * - partition validations
2229 */
2230 static int gpt_verify_disklabel(struct fdisk_context *cxt)
2231 {
2232 int nerror = 0;
2233 unsigned int ptnum;
2234 struct fdisk_gpt_label *gpt;
2235
2236 assert(cxt);
2237 assert(cxt->label);
2238 assert(fdisk_is_label(cxt, GPT));
2239
2240 gpt = self_label(cxt);
2241 if (!gpt)
2242 return -EINVAL;
2243
2244 if (!gpt->bheader) {
2245 nerror++;
2246 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
2247 }
2248
2249 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
2250 nerror++;
2251 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
2252 }
2253 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
2254 nerror++;
2255 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
2256 }
2257
2258 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
2259 nerror++;
2260 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
2261 }
2262
2263 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
2264 nerror++;
2265 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
2266 }
2267 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
2268 nerror++;
2269 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
2270 }
2271
2272 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
2273 nerror++;
2274 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
2275 }
2276 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
2277 nerror++;
2278 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
2279
2280 }
2281 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
2282 nerror++;
2283 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
2284 }
2285
2286 /*
2287 * if the GPT is the primary table, check the alternateLBA
2288 * to see if it is a valid GPT
2289 */
2290 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
2291 le64_to_cpu(gpt->bheader->alternative_lba))) {
2292 nerror++;
2293 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
2294 }
2295
2296 ptnum = check_overlap_partitions(gpt);
2297 if (ptnum) {
2298 nerror++;
2299 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
2300 ptnum, ptnum+1);
2301 }
2302
2303 ptnum = check_too_big_partitions(gpt, cxt->total_sectors);
2304 if (ptnum) {
2305 nerror++;
2306 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
2307 ptnum);
2308 }
2309
2310 ptnum = check_start_after_end_partitions(gpt);
2311 if (ptnum) {
2312 nerror++;
2313 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
2314 ptnum);
2315 }
2316
2317 if (!nerror) { /* yay :-) */
2318 uint32_t nsegments = 0;
2319 uint64_t free_sectors = 0, largest_segment = 0;
2320 char *strsz = NULL;
2321
2322 fdisk_info(cxt, _("No errors detected."));
2323 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
2324 fdisk_info(cxt, _("Using %zu out of %zu partitions."),
2325 partitions_in_use(gpt),
2326 gpt_get_nentries(gpt));
2327
2328 free_sectors = get_free_sectors(cxt, gpt, &nsegments, &largest_segment);
2329 if (largest_segment)
2330 strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER,
2331 largest_segment * cxt->sector_size);
2332
2333 fdisk_info(cxt,
2334 P_("A total of %ju free sectors is available in %u segment.",
2335 "A total of %ju free sectors is available in %u segments "
2336 "(the largest is %s).", nsegments),
2337 free_sectors, nsegments, strsz ? : "0 B");
2338 free(strsz);
2339
2340 } else
2341 fdisk_warnx(cxt,
2342 P_("%d error detected.", "%d errors detected.", nerror),
2343 nerror);
2344
2345 return nerror;
2346 }
2347
2348 /* Delete a single GPT partition, specified by partnum. */
2349 static int gpt_delete_partition(struct fdisk_context *cxt,
2350 size_t partnum)
2351 {
2352 struct fdisk_gpt_label *gpt;
2353
2354 assert(cxt);
2355 assert(cxt->label);
2356 assert(fdisk_is_label(cxt, GPT));
2357
2358 gpt = self_label(cxt);
2359
2360 if (partnum >= cxt->label->nparts_max)
2361 return -EINVAL;
2362
2363 if (!gpt_entry_is_used(gpt_get_entry(gpt, partnum)))
2364 return -EINVAL;
2365
2366 /* hasta la vista, baby! */
2367 gpt_zeroize_entry(gpt, partnum);
2368
2369 gpt_recompute_crc(gpt->pheader, gpt->ents);
2370 gpt_recompute_crc(gpt->bheader, gpt->ents);
2371 cxt->label->nparts_cur--;
2372 fdisk_label_set_changed(cxt->label, 1);
2373
2374 return 0;
2375 }
2376
2377
2378 /* Performs logical checks to add a new partition entry */
2379 static int gpt_add_partition(
2380 struct fdisk_context *cxt,
2381 struct fdisk_partition *pa,
2382 size_t *partno)
2383 {
2384 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
2385 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
2386 uint64_t dflt_f, dflt_l, max_l; /* largest segment (default) */
2387 struct gpt_guid typeid;
2388 struct fdisk_gpt_label *gpt;
2389 struct gpt_header *pheader;
2390 struct gpt_entry *e;
2391 struct fdisk_ask *ask = NULL;
2392 size_t partnum;
2393 int rc;
2394
2395 assert(cxt);
2396 assert(cxt->label);
2397 assert(fdisk_is_label(cxt, GPT));
2398
2399 gpt = self_label(cxt);
2400
2401 assert(gpt);
2402 assert(gpt->pheader);
2403 assert(gpt->ents);
2404
2405 pheader = gpt->pheader;
2406
2407 rc = fdisk_partition_next_partno(pa, cxt, &partnum);
2408 if (rc) {
2409 DBG(GPT, ul_debug("failed to get next partno"));
2410 return rc;
2411 }
2412
2413 assert(partnum < gpt_get_nentries(gpt));
2414
2415 if (gpt_entry_is_used(gpt_get_entry(gpt, partnum))) {
2416 fdisk_warnx(cxt, _("Partition %zu is already defined. "
2417 "Delete it before re-adding it."), partnum +1);
2418 return -ERANGE;
2419 }
2420 if (gpt_get_nentries(gpt) == partitions_in_use(gpt)) {
2421 fdisk_warnx(cxt, _("All partitions are already in use."));
2422 return -ENOSPC;
2423 }
2424 if (!get_free_sectors(cxt, gpt, NULL, NULL)) {
2425 fdisk_warnx(cxt, _("No free sectors available."));
2426 return -ENOSPC;
2427 }
2428
2429 rc = string_to_guid(pa && pa->type && pa->type->typestr ?
2430 pa->type->typestr:
2431 GPT_DEFAULT_ENTRY_TYPE, &typeid);
2432 if (rc)
2433 return rc;
2434
2435 disk_f = find_first_available(gpt, le64_to_cpu(pheader->first_usable_lba));
2436 e = gpt_get_entry(gpt, 0);
2437
2438 /* if first sector no explicitly defined then ignore small gaps before
2439 * the first partition */
2440 if ((!pa || !fdisk_partition_has_start(pa))
2441 && gpt_entry_is_used(e)
2442 && disk_f < gpt_partition_start(e)) {
2443
2444 do {
2445 uint64_t x;
2446 DBG(GPT, ul_debug("testing first sector %"PRIu64"", disk_f));
2447 disk_f = find_first_available(gpt, disk_f);
2448 if (!disk_f)
2449 break;
2450 x = find_last_free(gpt, disk_f);
2451 if (x - disk_f >= cxt->grain / cxt->sector_size)
2452 break;
2453 DBG(GPT, ul_debug("first sector %"PRIu64" addresses to small space, continue...", disk_f));
2454 disk_f = x + 1ULL;
2455 } while(1);
2456
2457 if (disk_f == 0)
2458 disk_f = find_first_available(gpt, le64_to_cpu(pheader->first_usable_lba));
2459 }
2460
2461 e = NULL;
2462 disk_l = find_last_free_sector(gpt);
2463
2464 /* the default is the largest free space */
2465 dflt_f = find_first_in_largest(gpt);
2466 dflt_l = find_last_free(gpt, dflt_f);
2467
2468 /* don't offer too small free space by default, this is possible to
2469 * bypass by sfdisk script */
2470 if ((!pa || !fdisk_partition_has_start(pa))
2471 && dflt_l - dflt_f + 1 < cxt->grain / cxt->sector_size) {
2472 fdisk_warnx(cxt, _("No enough free sectors available."));
2473 return -ENOSPC;
2474 }
2475
2476 /* align the default in range <dflt_f,dflt_l>*/
2477 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
2478
2479 /* first sector */
2480 if (pa && pa->start_follow_default) {
2481 user_f = dflt_f;
2482
2483 } else if (pa && fdisk_partition_has_start(pa)) {
2484 DBG(GPT, ul_debug("first sector defined: %ju", (uintmax_t)pa->start));
2485 if (pa->start != find_first_available(gpt, pa->start)) {
2486 fdisk_warnx(cxt, _("Sector %ju already used."), (uintmax_t)pa->start);
2487 return -ERANGE;
2488 }
2489 user_f = pa->start;
2490 } else {
2491 /* ask by dialog */
2492 for (;;) {
2493 if (!ask)
2494 ask = fdisk_new_ask();
2495 else
2496 fdisk_reset_ask(ask);
2497 if (!ask)
2498 return -ENOMEM;
2499
2500 /* First sector */
2501 fdisk_ask_set_query(ask, _("First sector"));
2502 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
2503 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
2504 fdisk_ask_number_set_default(ask, dflt_f); /* default */
2505 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
2506
2507 rc = fdisk_do_ask(cxt, ask);
2508 if (rc)
2509 goto done;
2510
2511 user_f = fdisk_ask_number_get_result(ask);
2512 if (user_f != find_first_available(gpt, user_f)) {
2513 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
2514 continue;
2515 }
2516 break;
2517 }
2518 }
2519
2520
2521 /* Last sector */
2522 dflt_l = max_l = find_last_free(gpt, user_f);
2523
2524 /* Make sure the last partition has aligned size by default because
2525 * range specified by LastUsableLBA may be unaligned on disks where
2526 * logical sector != physical (512/4K) because backup header size is
2527 * calculated from logical sectors. */
2528 if (max_l == le64_to_cpu(gpt->pheader->last_usable_lba))
2529 dflt_l = fdisk_align_lba_in_range(cxt, max_l, user_f, max_l) - 1;
2530
2531 if (pa && pa->end_follow_default) {
2532 user_l = dflt_l;
2533
2534 } else if (pa && fdisk_partition_has_size(pa)) {
2535 user_l = user_f + pa->size - 1;
2536 DBG(GPT, ul_debug("size defined: %ju, end: %"PRIu64
2537 "(last possible: %"PRIu64", optimal: %"PRIu64")",
2538 (uintmax_t)pa->size, user_l, max_l, dflt_l));
2539
2540 if (user_l != dflt_l
2541 && !pa->size_explicit
2542 && alignment_required(cxt)
2543 && user_l - user_f > (cxt->grain / fdisk_get_sector_size(cxt))) {
2544
2545 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2546 if (user_l > user_f)
2547 user_l -= 1ULL;
2548 }
2549 } else {
2550 for (;;) {
2551 if (!ask)
2552 ask = fdisk_new_ask();
2553 else
2554 fdisk_reset_ask(ask);
2555 if (!ask)
2556 return -ENOMEM;
2557
2558 fdisk_ask_set_query(ask, _("Last sector, +/-sectors or +/-size{K,M,G,T,P}"));
2559 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
2560 fdisk_ask_number_set_low(ask, user_f); /* minimal */
2561 fdisk_ask_number_set_default(ask, dflt_l); /* default */
2562 fdisk_ask_number_set_high(ask, max_l); /* maximal */
2563 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
2564 fdisk_ask_number_set_unit(ask, cxt->sector_size);
2565 fdisk_ask_number_set_wrap_negative(ask, 1); /* wrap negative around high */
2566
2567 rc = fdisk_do_ask(cxt, ask);
2568 if (rc)
2569 goto done;
2570
2571 user_l = fdisk_ask_number_get_result(ask);
2572 if (fdisk_ask_number_is_relative(ask)) {
2573 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2574 if (user_l > user_f)
2575 user_l -= 1ULL;
2576 }
2577
2578 if (user_l >= user_f && user_l <= disk_l)
2579 break;
2580
2581 fdisk_warnx(cxt, _("Value out of range."));
2582 }
2583 }
2584
2585
2586 if (user_f > user_l || partnum >= cxt->label->nparts_max) {
2587 fdisk_warnx(cxt, _("Could not create partition %zu"), partnum + 1);
2588 rc = -EINVAL;
2589 goto done;
2590 }
2591
2592 /* Be paranoid and check against on-disk setting rather than against libfdisk cxt */
2593 if (user_l > le64_to_cpu(pheader->last_usable_lba)) {
2594 fdisk_warnx(cxt, _("The last usable GPT sector is %ju, but %ju is requested."),
2595 le64_to_cpu(pheader->last_usable_lba), user_l);
2596 rc = -EINVAL;
2597 goto done;
2598 }
2599
2600 if (user_f < le64_to_cpu(pheader->first_usable_lba)) {
2601 fdisk_warnx(cxt, _("The first usable GPT sector is %ju, but %ju is requested."),
2602 le64_to_cpu(pheader->first_usable_lba), user_f);
2603 rc = -EINVAL;
2604 goto done;
2605 }
2606
2607 assert(!FDISK_IS_UNDEF(user_l));
2608 assert(!FDISK_IS_UNDEF(user_f));
2609 assert(partnum < gpt_get_nentries(gpt));
2610
2611 e = gpt_get_entry(gpt, partnum);
2612 e->lba_end = cpu_to_le64(user_l);
2613 e->lba_start = cpu_to_le64(user_f);
2614
2615 gpt_entry_set_type(e, &typeid);
2616
2617 if (pa && pa->uuid) {
2618 /* Sometimes it's necessary to create a copy of the PT and
2619 * reuse already defined UUID
2620 */
2621 rc = gpt_entry_set_uuid(e, pa->uuid);
2622 if (rc)
2623 goto done;
2624 } else {
2625 /* Any time a new partition entry is created a new GUID must be
2626 * generated for that partition, and every partition is guaranteed
2627 * to have a unique GUID.
2628 */
2629 struct gpt_guid guid;
2630
2631 uuid_generate_random((unsigned char *) &guid);
2632 swap_efi_guid(&guid);
2633 e->partition_guid = guid;
2634 }
2635
2636 if (pa && pa->name && *pa->name)
2637 gpt_entry_set_name(e, pa->name);
2638 if (pa && pa->attrs)
2639 gpt_entry_attrs_from_string(cxt, e, pa->attrs);
2640
2641 DBG(GPT, ul_debug("new partition: partno=%zu, start=%"PRIu64", end=%"PRIu64", size=%"PRIu64"",
2642 partnum,
2643 gpt_partition_start(e),
2644 gpt_partition_end(e),
2645 gpt_partition_size(e)));
2646
2647 gpt_recompute_crc(gpt->pheader, gpt->ents);
2648 gpt_recompute_crc(gpt->bheader, gpt->ents);
2649
2650 /* report result */
2651 {
2652 struct fdisk_parttype *t;
2653
2654 cxt->label->nparts_cur++;
2655 fdisk_label_set_changed(cxt->label, 1);
2656
2657 t = gpt_partition_parttype(cxt, e);
2658 fdisk_info_new_partition(cxt, partnum + 1, user_f, user_l, t);
2659 fdisk_unref_parttype(t);
2660 }
2661
2662 rc = 0;
2663 if (partno)
2664 *partno = partnum;
2665 done:
2666 fdisk_unref_ask(ask);
2667 return rc;
2668 }
2669
2670 /*
2671 * Create a new GPT disklabel - destroys any previous data.
2672 */
2673 static int gpt_create_disklabel(struct fdisk_context *cxt)
2674 {
2675 int rc = 0;
2676 size_t esz = 0;
2677 char str[UUID_STR_LEN];
2678 struct fdisk_gpt_label *gpt;
2679 struct gpt_guid guid;
2680
2681 assert(cxt);
2682 assert(cxt->label);
2683 assert(fdisk_is_label(cxt, GPT));
2684
2685 gpt = self_label(cxt);
2686
2687 /* label private stuff has to be empty, see gpt_deinit() */
2688 assert(gpt->pheader == NULL);
2689 assert(gpt->bheader == NULL);
2690
2691 /*
2692 * When no header, entries or pmbr is set, we're probably
2693 * dealing with a new, empty disk - so always allocate memory
2694 * to deal with the data structures whatever the case is.
2695 */
2696 rc = gpt_mknew_pmbr(cxt);
2697 if (rc < 0)
2698 goto done;
2699
2700 assert(cxt->sector_size >= sizeof(struct gpt_header));
2701
2702 /* primary */
2703 gpt->pheader = calloc(1, cxt->sector_size);
2704 if (!gpt->pheader) {
2705 rc = -ENOMEM;
2706 goto done;
2707 }
2708 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
2709 if (rc < 0)
2710 goto done;
2711
2712 /* backup ("copy" primary) */
2713 gpt->bheader = calloc(1, cxt->sector_size);
2714 if (!gpt->bheader) {
2715 rc = -ENOMEM;
2716 goto done;
2717 }
2718 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
2719 last_lba(cxt), gpt->pheader);
2720 if (rc < 0)
2721 goto done;
2722
2723 rc = gpt_sizeof_entries(gpt->pheader, &esz);
2724 if (rc)
2725 goto done;
2726 gpt->ents = calloc(1, esz);
2727 if (!gpt->ents) {
2728 rc = -ENOMEM;
2729 goto done;
2730 }
2731 gpt_recompute_crc(gpt->pheader, gpt->ents);
2732 gpt_recompute_crc(gpt->bheader, gpt->ents);
2733
2734 cxt->label->nparts_max = gpt_get_nentries(gpt);
2735 cxt->label->nparts_cur = 0;
2736
2737 guid = gpt->pheader->disk_guid;
2738 guid_to_string(&guid, str);
2739 fdisk_label_set_changed(cxt->label, 1);
2740 fdisk_info(cxt, _("Created a new GPT disklabel (GUID: %s)."), str);
2741
2742 if (gpt_get_nentries(gpt) < GPT_NPARTITIONS)
2743 fdisk_info(cxt, _("The maximal number of partitions is %zu (default is %zu)."),
2744 gpt_get_nentries(gpt), GPT_NPARTITIONS);
2745 done:
2746 return rc;
2747 }
2748
2749 static int gpt_set_disklabel_id(struct fdisk_context *cxt, const char *str)
2750 {
2751 struct fdisk_gpt_label *gpt;
2752 struct gpt_guid uuid;
2753 char *old, *new;
2754 int rc;
2755
2756 assert(cxt);
2757 assert(cxt->label);
2758 assert(fdisk_is_label(cxt, GPT));
2759
2760 gpt = self_label(cxt);
2761 if (!str) {
2762 char *buf = NULL;
2763
2764 if (fdisk_ask_string(cxt,
2765 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &buf))
2766 return -EINVAL;
2767 rc = string_to_guid(buf, &uuid);
2768 free(buf);
2769 } else
2770 rc = string_to_guid(str, &uuid);
2771
2772 if (rc) {
2773 fdisk_warnx(cxt, _("Failed to parse your UUID."));
2774 return rc;
2775 }
2776
2777 old = gpt_get_header_id(gpt->pheader);
2778
2779 gpt->pheader->disk_guid = uuid;
2780 gpt->bheader->disk_guid = uuid;
2781
2782 gpt_recompute_crc(gpt->pheader, gpt->ents);
2783 gpt_recompute_crc(gpt->bheader, gpt->ents);
2784
2785 new = gpt_get_header_id(gpt->pheader);
2786
2787 fdisk_info(cxt, _("Disk identifier changed from %s to %s."), old, new);
2788
2789 free(old);
2790 free(new);
2791 fdisk_label_set_changed(cxt->label, 1);
2792 return 0;
2793 }
2794
2795 static int gpt_check_table_overlap(struct fdisk_context *cxt,
2796 uint64_t first_usable,
2797 uint64_t last_usable)
2798 {
2799 struct fdisk_gpt_label *gpt = self_label(cxt);
2800 size_t i;
2801 int rc = 0;
2802
2803 /* First check if there's enough room for the table. last_lba may have wrapped */
2804 if (first_usable > cxt->total_sectors || /* far too little space */
2805 last_usable > cxt->total_sectors || /* wrapped */
2806 first_usable > last_usable) { /* too little space */
2807 fdisk_warnx(cxt, _("Not enough space for new partition table!"));
2808 return -ENOSPC;
2809 }
2810
2811 /* check that all partitions fit in the remaining space */
2812 for (i = 0; i < gpt_get_nentries(gpt); i++) {
2813 struct gpt_entry *e = gpt_get_entry(gpt, i);
2814
2815 if (!gpt_entry_is_used(e))
2816 continue;
2817 if (gpt_partition_start(e) < first_usable) {
2818 fdisk_warnx(cxt, _("Partition #%zu out of range (minimal start is %"PRIu64" sectors)"),
2819 i + 1, first_usable);
2820 rc = -EINVAL;
2821 }
2822 if (gpt_partition_end(e) > last_usable) {
2823 fdisk_warnx(cxt, _("Partition #%zu out of range (maximal end is %"PRIu64" sectors)"),
2824 i + 1, last_usable - (uint64_t) 1);
2825 rc = -EINVAL;
2826 }
2827 }
2828 return rc;
2829 }
2830
2831 /**
2832 * fdisk_gpt_set_npartitions:
2833 * @cxt: context
2834 * @nents: number of wanted entries
2835 *
2836 * Enlarge GPT entries array if possible. The function check if an existing
2837 * partition does not overlap the entries array area. If yes, then it report
2838 * warning and returns -EINVAL.
2839 *
2840 * Returns: 0 on success, < 0 on error.
2841 * Since: 2.29
2842 */
2843 int fdisk_gpt_set_npartitions(struct fdisk_context *cxt, uint32_t nents)
2844 {
2845 struct fdisk_gpt_label *gpt;
2846 size_t new_size = 0;
2847 uint32_t old_nents;
2848 uint64_t first_usable = 0ULL, last_usable = 0ULL;
2849 int rc;
2850
2851 assert(cxt);
2852 assert(cxt->label);
2853
2854 if (!fdisk_is_label(cxt, GPT))
2855 return -EINVAL;
2856
2857 gpt = self_label(cxt);
2858
2859 old_nents = le32_to_cpu(gpt->pheader->npartition_entries);
2860 if (old_nents == nents)
2861 return 0; /* do nothing, say nothing */
2862
2863 /* calculate the size (bytes) of the entries array */
2864 rc = gpt_calculate_sizeof_entries(gpt->pheader, nents, &new_size);
2865 if (rc) {
2866 uint32_t entry_size = le32_to_cpu(gpt->pheader->sizeof_partition_entry);
2867
2868 if (entry_size == 0)
2869 fdisk_warnx(cxt, _("The partition entry size is zero."));
2870 else
2871 fdisk_warnx(cxt, _("The number of the partition has to be smaller than %zu."),
2872 (size_t) UINT32_MAX / entry_size);
2873 return rc;
2874 }
2875
2876 rc = gpt_calculate_first_lba(gpt->pheader, nents, &first_usable, cxt);
2877 if (rc == 0)
2878 rc = gpt_calculate_last_lba(gpt->pheader, nents, &last_usable, cxt);
2879 if (rc)
2880 return rc;
2881
2882 /* if expanding the table, first check that everything fits,
2883 * then allocate more memory and zero. */
2884 if (nents > old_nents) {
2885 unsigned char *ents;
2886 size_t old_size = 0;
2887
2888 rc = gpt_calculate_sizeof_entries(gpt->pheader, old_nents, &old_size);
2889 if (rc == 0)
2890 rc = gpt_check_table_overlap(cxt, first_usable, last_usable);
2891 if (rc)
2892 return rc;
2893 ents = realloc(gpt->ents, new_size);
2894 if (!ents) {
2895 fdisk_warnx(cxt, _("Cannot allocate memory!"));
2896 return -ENOMEM;
2897 }
2898 memset(ents + old_size, 0, new_size - old_size);
2899 gpt->ents = ents;
2900 }
2901
2902 /* everything's ok, apply the new size */
2903 gpt->pheader->npartition_entries = cpu_to_le32(nents);
2904 gpt->bheader->npartition_entries = cpu_to_le32(nents);
2905
2906 /* usable LBA addresses will have changed */
2907 fdisk_set_first_lba(cxt, first_usable);
2908 fdisk_set_last_lba(cxt, last_usable);
2909 gpt->pheader->first_usable_lba = cpu_to_le64(first_usable);
2910 gpt->bheader->first_usable_lba = cpu_to_le64(first_usable);
2911 gpt->pheader->last_usable_lba = cpu_to_le64(last_usable);
2912 gpt->bheader->last_usable_lba = cpu_to_le64(last_usable);
2913
2914 /* The backup header must be recalculated */
2915 gpt_mknew_header_common(cxt, gpt->bheader, le64_to_cpu(gpt->pheader->alternative_lba));
2916
2917 /* CRCs will have changed */
2918 gpt_recompute_crc(gpt->pheader, gpt->ents);
2919 gpt_recompute_crc(gpt->bheader, gpt->ents);
2920
2921 /* update library info */
2922 cxt->label->nparts_max = gpt_get_nentries(gpt);
2923
2924 fdisk_info(cxt, _("Partition table length changed from %"PRIu32" to %"PRIu32"."),
2925 old_nents, nents);
2926
2927 fdisk_label_set_changed(cxt->label, 1);
2928 return 0;
2929 }
2930
2931 static int gpt_part_is_used(struct fdisk_context *cxt, size_t i)
2932 {
2933 struct fdisk_gpt_label *gpt;
2934 struct gpt_entry *e;
2935
2936 assert(cxt);
2937 assert(cxt->label);
2938 assert(fdisk_is_label(cxt, GPT));
2939
2940 gpt = self_label(cxt);
2941
2942 if (i >= gpt_get_nentries(gpt))
2943 return 0;
2944
2945 e = gpt_get_entry(gpt, i);
2946
2947 return gpt_entry_is_used(e) || gpt_partition_start(e);
2948 }
2949
2950 /**
2951 * fdisk_gpt_is_hybrid:
2952 * @cxt: context
2953 *
2954 * The regular GPT contains PMBR (dummy protective MBR) where the protective
2955 * MBR does not address any partitions.
2956 *
2957 * Hybrid GPT contains regular MBR where this partition table addresses the
2958 * same partitions as GPT. It's recommended to not use hybrid GPT due to MBR
2959 * limits.
2960 *
2961 * The libfdisk does not provide functionality to sync GPT and MBR, you have to
2962 * directly access and modify (P)MBR (see fdisk_new_nested_context()).
2963 *
2964 * Returns: 1 if partition table detected as hybrid otherwise return 0
2965 */
2966 int fdisk_gpt_is_hybrid(struct fdisk_context *cxt)
2967 {
2968 assert(cxt);
2969 return valid_pmbr(cxt) == GPT_MBR_HYBRID;
2970 }
2971
2972 /**
2973 * fdisk_gpt_get_partition_attrs:
2974 * @cxt: context
2975 * @partnum: partition number
2976 * @attrs: GPT partition attributes
2977 *
2978 * Sets @attrs for the given partition
2979 *
2980 * Returns: 0 on success, <0 on error.
2981 */
2982 int fdisk_gpt_get_partition_attrs(
2983 struct fdisk_context *cxt,
2984 size_t partnum,
2985 uint64_t *attrs)
2986 {
2987 struct fdisk_gpt_label *gpt;
2988
2989 assert(cxt);
2990 assert(cxt->label);
2991
2992 if (!fdisk_is_label(cxt, GPT))
2993 return -EINVAL;
2994
2995 gpt = self_label(cxt);
2996
2997 if (partnum >= gpt_get_nentries(gpt))
2998 return -EINVAL;
2999
3000 *attrs = le64_to_cpu(gpt_get_entry(gpt, partnum)->attrs);
3001 return 0;
3002 }
3003
3004 /**
3005 * fdisk_gpt_set_partition_attrs:
3006 * @cxt: context
3007 * @partnum: partition number
3008 * @attrs: GPT partition attributes
3009 *
3010 * Sets the GPT partition attributes field to @attrs.
3011 *
3012 * Returns: 0 on success, <0 on error.
3013 */
3014 int fdisk_gpt_set_partition_attrs(
3015 struct fdisk_context *cxt,
3016 size_t partnum,
3017 uint64_t attrs)
3018 {
3019 struct fdisk_gpt_label *gpt;
3020
3021 assert(cxt);
3022 assert(cxt->label);
3023
3024 if (!fdisk_is_label(cxt, GPT))
3025 return -EINVAL;
3026
3027 DBG(GPT, ul_debug("entry attributes change requested partno=%zu", partnum));
3028 gpt = self_label(cxt);
3029
3030 if (partnum >= gpt_get_nentries(gpt))
3031 return -EINVAL;
3032
3033 gpt_get_entry(gpt, partnum)->attrs = cpu_to_le64(attrs);
3034 fdisk_info(cxt, _("The attributes on partition %zu changed to 0x%016" PRIx64 "."),
3035 partnum + 1, attrs);
3036
3037 gpt_recompute_crc(gpt->pheader, gpt->ents);
3038 gpt_recompute_crc(gpt->bheader, gpt->ents);
3039 fdisk_label_set_changed(cxt->label, 1);
3040 return 0;
3041 }
3042
3043 static int gpt_toggle_partition_flag(
3044 struct fdisk_context *cxt,
3045 size_t i,
3046 unsigned long flag)
3047 {
3048 struct fdisk_gpt_label *gpt;
3049 struct gpt_entry *e;
3050 uint64_t attrs;
3051 uintmax_t tmp;
3052 char *bits;
3053 const char *name = NULL;
3054 int bit = -1, rc;
3055
3056 assert(cxt);
3057 assert(cxt->label);
3058 assert(fdisk_is_label(cxt, GPT));
3059
3060 DBG(GPT, ul_debug("entry attribute change requested partno=%zu", i));
3061 gpt = self_label(cxt);
3062
3063 if (i >= gpt_get_nentries(gpt))
3064 return -EINVAL;
3065
3066 e = gpt_get_entry(gpt, i);
3067 attrs = e->attrs;
3068 bits = (char *) &attrs;
3069
3070 switch (flag) {
3071 case GPT_FLAG_REQUIRED:
3072 bit = GPT_ATTRBIT_REQ;
3073 name = GPT_ATTRSTR_REQ;
3074 break;
3075 case GPT_FLAG_NOBLOCK:
3076 bit = GPT_ATTRBIT_NOBLOCK;
3077 name = GPT_ATTRSTR_NOBLOCK;
3078 break;
3079 case GPT_FLAG_LEGACYBOOT:
3080 bit = GPT_ATTRBIT_LEGACY;
3081 name = GPT_ATTRSTR_LEGACY;
3082 break;
3083 case GPT_FLAG_GUIDSPECIFIC:
3084 rc = fdisk_ask_number(cxt, 48, 48, 63, _("Enter GUID specific bit"), &tmp);
3085 if (rc)
3086 return rc;
3087 bit = tmp;
3088 break;
3089 default:
3090 /* already specified PT_FLAG_GUIDSPECIFIC bit */
3091 if (flag >= 48 && flag <= 63) {
3092 bit = flag;
3093 flag = GPT_FLAG_GUIDSPECIFIC;
3094 }
3095 break;
3096 }
3097
3098 if (bit < 0) {
3099 fdisk_warnx(cxt, _("failed to toggle unsupported bit %lu"), flag);
3100 return -EINVAL;
3101 }
3102
3103 if (!isset(bits, bit))
3104 setbit(bits, bit);
3105 else
3106 clrbit(bits, bit);
3107
3108 e->attrs = attrs;
3109
3110 if (flag == GPT_FLAG_GUIDSPECIFIC)
3111 fdisk_info(cxt, isset(bits, bit) ?
3112 _("The GUID specific bit %d on partition %zu is enabled now.") :
3113 _("The GUID specific bit %d on partition %zu is disabled now."),
3114 bit, i + 1);
3115 else
3116 fdisk_info(cxt, isset(bits, bit) ?
3117 _("The %s flag on partition %zu is enabled now.") :
3118 _("The %s flag on partition %zu is disabled now."),
3119 name, i + 1);
3120
3121 gpt_recompute_crc(gpt->pheader, gpt->ents);
3122 gpt_recompute_crc(gpt->bheader, gpt->ents);
3123 fdisk_label_set_changed(cxt->label, 1);
3124 return 0;
3125 }
3126
3127 static int gpt_entry_cmp_start(const void *a, const void *b)
3128 {
3129 const struct gpt_entry *ae = (const struct gpt_entry *) a,
3130 *be = (const struct gpt_entry *) b;
3131 int au = gpt_entry_is_used(ae),
3132 bu = gpt_entry_is_used(be);
3133
3134 if (!au && !bu)
3135 return 0;
3136 if (!au)
3137 return 1;
3138 if (!bu)
3139 return -1;
3140
3141 return cmp_numbers(gpt_partition_start(ae), gpt_partition_start(be));
3142 }
3143
3144 /* sort partition by start sector */
3145 static int gpt_reorder(struct fdisk_context *cxt)
3146 {
3147 struct fdisk_gpt_label *gpt;
3148 size_t i, nparts, mess;
3149
3150 assert(cxt);
3151 assert(cxt->label);
3152 assert(fdisk_is_label(cxt, GPT));
3153
3154 gpt = self_label(cxt);
3155 nparts = gpt_get_nentries(gpt);
3156
3157 for (i = 0, mess = 0; mess == 0 && i + 1 < nparts; i++)
3158 mess = gpt_entry_cmp_start(
3159 (const void *) gpt_get_entry(gpt, i),
3160 (const void *) gpt_get_entry(gpt, i + 1)) > 0;
3161
3162 if (!mess)
3163 return 1;
3164
3165 qsort(gpt->ents, nparts, sizeof(struct gpt_entry),
3166 gpt_entry_cmp_start);
3167
3168 gpt_recompute_crc(gpt->pheader, gpt->ents);
3169 gpt_recompute_crc(gpt->bheader, gpt->ents);
3170 fdisk_label_set_changed(cxt->label, 1);
3171
3172 return 0;
3173 }
3174
3175 static int gpt_reset_alignment(struct fdisk_context *cxt)
3176 {
3177 struct fdisk_gpt_label *gpt;
3178 struct gpt_header *h;
3179
3180 assert(cxt);
3181 assert(cxt->label);
3182 assert(fdisk_is_label(cxt, GPT));
3183
3184 gpt = self_label(cxt);
3185 h = gpt ? gpt->pheader : NULL;
3186
3187 if (h) {
3188 /* always follow existing table */
3189 cxt->first_lba = le64_to_cpu(h->first_usable_lba);
3190 cxt->last_lba = le64_to_cpu(h->last_usable_lba);
3191 } else {
3192 /* estimate ranges for GPT */
3193 uint64_t first, last;
3194 int rc;
3195
3196 rc = count_first_last_lba(cxt, &first, &last, NULL);
3197 if (rc)
3198 return rc;
3199 if (cxt->first_lba < first)
3200 cxt->first_lba = first;
3201 if (cxt->last_lba > last)
3202 cxt->last_lba = last;
3203 }
3204
3205 return 0;
3206 }
3207 /*
3208 * Deinitialize fdisk-specific variables
3209 */
3210 static void gpt_deinit(struct fdisk_label *lb)
3211 {
3212 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
3213
3214 if (!gpt)
3215 return;
3216
3217 free(gpt->ents);
3218 free(gpt->pheader);
3219 free(gpt->bheader);
3220
3221 gpt->ents = NULL;
3222 gpt->pheader = NULL;
3223 gpt->bheader = NULL;
3224 }
3225
3226 static const struct fdisk_label_operations gpt_operations =
3227 {
3228 .probe = gpt_probe_label,
3229 .write = gpt_write_disklabel,
3230 .verify = gpt_verify_disklabel,
3231 .create = gpt_create_disklabel,
3232 .locate = gpt_locate_disklabel,
3233 .get_item = gpt_get_disklabel_item,
3234 .set_id = gpt_set_disklabel_id,
3235
3236 .get_part = gpt_get_partition,
3237 .set_part = gpt_set_partition,
3238 .add_part = gpt_add_partition,
3239 .del_part = gpt_delete_partition,
3240 .reorder = gpt_reorder,
3241
3242 .part_is_used = gpt_part_is_used,
3243 .part_toggle_flag = gpt_toggle_partition_flag,
3244
3245 .deinit = gpt_deinit,
3246
3247 .reset_alignment = gpt_reset_alignment
3248 };
3249
3250 static const struct fdisk_field gpt_fields[] =
3251 {
3252 /* basic */
3253 { FDISK_FIELD_DEVICE, N_("Device"), 10, 0 },
3254 { FDISK_FIELD_START, N_("Start"), 5, FDISK_FIELDFL_NUMBER },
3255 { FDISK_FIELD_END, N_("End"), 5, FDISK_FIELDFL_NUMBER },
3256 { FDISK_FIELD_SECTORS, N_("Sectors"), 5, FDISK_FIELDFL_NUMBER },
3257 { FDISK_FIELD_SIZE, N_("Size"), 5, FDISK_FIELDFL_NUMBER | FDISK_FIELDFL_EYECANDY },
3258 { FDISK_FIELD_TYPE, N_("Type"), 0.1, FDISK_FIELDFL_EYECANDY },
3259 /* expert */
3260 { FDISK_FIELD_TYPEID, N_("Type-UUID"), 36, FDISK_FIELDFL_DETAIL },
3261 { FDISK_FIELD_UUID, N_("UUID"), 36, FDISK_FIELDFL_DETAIL },
3262 { FDISK_FIELD_NAME, N_("Name"), 0.2, FDISK_FIELDFL_DETAIL },
3263 { FDISK_FIELD_ATTR, N_("Attrs"), 0, FDISK_FIELDFL_DETAIL }
3264 };
3265
3266 /*
3267 * allocates GPT in-memory stuff
3268 */
3269 struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt __attribute__ ((__unused__)))
3270 {
3271 struct fdisk_label *lb;
3272 struct fdisk_gpt_label *gpt;
3273
3274 gpt = calloc(1, sizeof(*gpt));
3275 if (!gpt)
3276 return NULL;
3277
3278 /* initialize generic part of the driver */
3279 lb = (struct fdisk_label *) gpt;
3280 lb->name = "gpt";
3281 lb->id = FDISK_DISKLABEL_GPT;
3282 lb->op = &gpt_operations;
3283
3284 lb->parttypes = gpt_parttypes;
3285 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
3286 lb->parttype_cuts = gpt_parttype_cuts;
3287 lb->nparttype_cuts = ARRAY_SIZE(gpt_parttype_cuts);
3288
3289 lb->fields = gpt_fields;
3290 lb->nfields = ARRAY_SIZE(gpt_fields);
3291
3292 /* return calloc() result to keep static anaylizers happy */
3293 return (struct fdisk_label *) gpt;
3294 }
3295
3296 /**
3297 * fdisk_gpt_disable_relocation
3298 * @lb: label
3299 * @disable: 0 or 1
3300 *
3301 * Disable automatic backup header relocation to the end of the device. The
3302 * header position is recalculated during libfdisk probing stage by
3303 * fdisk_assign_device() and later written by fdisk_write_disklabel(), so you
3304 * need to call it before fdisk_assign_device().
3305 *
3306 * Since: 2.36
3307 */
3308 void fdisk_gpt_disable_relocation(struct fdisk_label *lb, int disable)
3309 {
3310 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
3311
3312 assert(gpt);
3313 gpt->no_relocate = disable ? 1 : 0;
3314 }
3315
3316 /**
3317 * fdisk_gpt_enable_minimize
3318 * @lb: label
3319 * @enable: 0 or 1
3320 *
3321 * Force libfdisk to write backup header to behind last partition. The
3322 * header position is recalculated on fdisk_write_disklabel().
3323 *
3324 * Since: 2.36
3325 */
3326 void fdisk_gpt_enable_minimize(struct fdisk_label *lb, int enable)
3327 {
3328 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
3329
3330 assert(gpt);
3331 gpt->minimize = enable ? 1 : 0;
3332 }
3333
3334 #ifdef TEST_PROGRAM
3335 static int test_getattr(struct fdisk_test *ts __attribute__((unused)),
3336 int argc, char *argv[])
3337 {
3338 if (argc != 3)
3339 return -1;
3340
3341 const char *disk = argv[1];
3342 size_t part = strtoul(argv[2], NULL, 0) - 1;
3343 struct fdisk_context *cxt;
3344 uint64_t atters = 0;
3345
3346 cxt = fdisk_new_context();
3347 fdisk_assign_device(cxt, disk, 1);
3348
3349 if (!fdisk_is_label(cxt, GPT))
3350 return EXIT_FAILURE;
3351
3352 if (fdisk_gpt_get_partition_attrs(cxt, part, &atters))
3353 return EXIT_FAILURE;
3354
3355 printf("%s: 0x%016" PRIx64 "\n", argv[2], atters);
3356
3357 fdisk_unref_context(cxt);
3358 return 0;
3359 }
3360
3361 static int test_setattr(struct fdisk_test *ts __attribute__((unused)),
3362 int argc, char *argv[])
3363 {
3364 if (argc != 4)
3365 return -1;
3366
3367 const char *disk = argv[1];
3368 size_t part = strtoul(argv[2], NULL, 0) - 1;
3369 uint64_t atters = strtoull(argv[3], NULL, 0);
3370 struct fdisk_context *cxt;
3371
3372 cxt = fdisk_new_context();
3373 fdisk_assign_device(cxt, disk, 0);
3374
3375 if (!fdisk_is_label(cxt, GPT))
3376 return EXIT_FAILURE;
3377
3378 if (fdisk_gpt_set_partition_attrs(cxt, part, atters))
3379 return EXIT_FAILURE;
3380
3381 if (fdisk_write_disklabel(cxt))
3382 return EXIT_FAILURE;
3383
3384 fdisk_unref_context(cxt);
3385 return 0;
3386 }
3387
3388 int main(int argc, char *argv[])
3389 {
3390 struct fdisk_test tss[] = {
3391 { "--getattr", test_getattr, "<disk> <partition> print attributes" },
3392 { "--setattr", test_setattr, "<disk> <partition> <value> set attributes" },
3393 { NULL }
3394 };
3395
3396 return fdisk_run_test(tss, argc, argv);
3397 }
3398
3399 #endif