]> git.ipfire.org Git - thirdparty/util-linux.git/blame_incremental - libfdisk/src/gpt.c
taskset: Accept 0 pid for current process
[thirdparty/util-linux.git] / libfdisk / src / gpt.c
... / ...
CommitLineData
1/*
2 * Copyright (C) 2007 Karel Zak <kzak@redhat.com>
3 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
4 *
5 * GUID Partition Table (GPT) support. Based on UEFI Specs 2.3.1
6 * Chapter 5: GUID Partition Table (GPT) Disk Layout (Jun 27th, 2012).
7 * Some ideas and inspiration from GNU parted and gptfdisk.
8 */
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <inttypes.h>
13#include <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 */
57struct 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 */
78enum {
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. */
95struct 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 */
105struct 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
123struct 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 */
137struct 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
155static const struct fdisk_parttype gpt_parttypes[] =
156{
157 #include "pt-gpt-partnames.h"
158};
159
160static 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 */
180struct 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
193static void gpt_deinit(struct fdisk_label *lb);
194
195static 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 */
203static 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! */
212static 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 */
230static 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
237static 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
247static 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
257static 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
270static 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
276static 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
317static 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
330static 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
337static 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
353unknown:
354 return "unknown";
355}
356
357static 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
362static 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
367static 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 */
376static 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 */
382static 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 */
399static 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 */
413static 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
431static 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
449static 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 */
464static 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
469static 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 */
483static 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 */
516static 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;
557failed:
558 DBG(GPT, ul_debug("failed to fix alternative-LBA [rc=%d]", rc));
559 return rc;
560}
561
562static 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
597static 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 */
606static 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 */
624static 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 */
657static 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
680static 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
722static 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
746static 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 */
836static 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 */
894static 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 }
965done:
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
972static 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
995static 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 */
1007static 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
1038fail:
1039 free(ret);
1040 return NULL;
1041}
1042
1043static 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
1049static 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
1057static 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 */
1073static 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 */
1088static 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 */
1113static 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
1122static 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 */
1151done:
1152 return ret;
1153}
1154
1155/* Check if there is a valid header signature */
1156static 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 */
1166static 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;
1222invalid:
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
1231static 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
1278static 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 */
1347static 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 */
1369static 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 */
1393static 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 */
1416static 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 */
1429static 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 */
1457static 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. */
1509static 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. */
1532static 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 */
1566static 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 */
1596static 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
1627done:
1628 if (nsegments)
1629 *nsegments = num;
1630 if (largest_segment)
1631 *largest_segment = largest_seg;
1632
1633 return totfound;
1634}
1635
1636static 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;
1717failed:
1718 DBG(GPT, ul_debug("probe failed"));
1719 gpt_deinit(cxt->label);
1720 return 0;
1721}
1722
1723static 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
1736static int gpt_entry_attrs_to_string(struct gpt_entry *e, char **res)
1737{
1738 unsigned int n, count = 0;
1739 size_t l;
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 = calloc(1, sizeof(GPT_ATTRSTR_NOBLOCK) +
1756 sizeof(GPT_ATTRSTR_REQ) +
1757 sizeof(GPT_ATTRSTR_LEGACY) +
1758 sizeof("GUID:") + (GPT_ATTRBIT_GUID_COUNT * 3));
1759 if (!*res)
1760 return -errno;
1761
1762 p = *res;
1763 if (isset(bits, GPT_ATTRBIT_REQ)) {
1764 memcpy(p, GPT_ATTRSTR_REQ, (l = sizeof(GPT_ATTRSTR_REQ)));
1765 p += l - 1;
1766 }
1767 if (isset(bits, GPT_ATTRBIT_NOBLOCK)) {
1768 if (p != *res)
1769 *p++ = ' ';
1770 memcpy(p, GPT_ATTRSTR_NOBLOCK, (l = sizeof(GPT_ATTRSTR_NOBLOCK)));
1771 p += l - 1;
1772 }
1773 if (isset(bits, GPT_ATTRBIT_LEGACY)) {
1774 if (p != *res)
1775 *p++ = ' ';
1776 memcpy(p, GPT_ATTRSTR_LEGACY, (l = sizeof(GPT_ATTRSTR_LEGACY)));
1777 p += l - 1;
1778 }
1779
1780 for (n = GPT_ATTRBIT_GUID_FIRST;
1781 n < GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT; n++) {
1782
1783 if (!isset(bits, n))
1784 continue;
1785 if (!count) {
1786 if (p != *res)
1787 *p++ = ' ';
1788 p += sprintf(p, "GUID:%u", n);
1789 } else
1790 p += sprintf(p, ",%u", n);
1791 count++;
1792 }
1793
1794 return 0;
1795}
1796
1797static int gpt_entry_attrs_from_string(
1798 struct fdisk_context *cxt,
1799 struct gpt_entry *e,
1800 const char *str)
1801{
1802 const char *p = str;
1803 uint64_t attrs = 0;
1804 char *bits;
1805
1806 assert(e);
1807 assert(p);
1808
1809 DBG(GPT, ul_debug("parsing string attributes '%s'", p));
1810
1811 bits = (char *) &attrs;
1812
1813 while (p && *p) {
1814 int bit = -1;
1815
1816 while (isblank(*p)) p++;
1817 if (!*p)
1818 break;
1819
1820 DBG(GPT, ul_debug(" item '%s'", p));
1821
1822 if (strncmp(p, GPT_ATTRSTR_REQ,
1823 sizeof(GPT_ATTRSTR_REQ) - 1) == 0) {
1824 bit = GPT_ATTRBIT_REQ;
1825 p += sizeof(GPT_ATTRSTR_REQ) - 1;
1826 } else if (strncmp(p, GPT_ATTRSTR_REQ_TYPO,
1827 sizeof(GPT_ATTRSTR_REQ_TYPO) - 1) == 0) {
1828 bit = GPT_ATTRBIT_REQ;
1829 p += sizeof(GPT_ATTRSTR_REQ_TYPO) - 1;
1830 } else if (strncmp(p, GPT_ATTRSTR_LEGACY,
1831 sizeof(GPT_ATTRSTR_LEGACY) - 1) == 0) {
1832 bit = GPT_ATTRBIT_LEGACY;
1833 p += sizeof(GPT_ATTRSTR_LEGACY) - 1;
1834 } else if (strncmp(p, GPT_ATTRSTR_NOBLOCK,
1835 sizeof(GPT_ATTRSTR_NOBLOCK) - 1) == 0) {
1836 bit = GPT_ATTRBIT_NOBLOCK;
1837 p += sizeof(GPT_ATTRSTR_NOBLOCK) - 1;
1838
1839 /* GUID:<bit> as well as <bit> */
1840 } else if (isdigit((unsigned char) *p)
1841 || (strncmp(p, "GUID:", 5) == 0
1842 && isdigit((unsigned char) *(p + 5)))) {
1843 char *end = NULL;
1844
1845 if (*p == 'G')
1846 p += 5;
1847
1848 errno = 0;
1849 bit = strtol(p, &end, 0);
1850 if (errno || !end || end == str
1851 || bit < GPT_ATTRBIT_GUID_FIRST
1852 || bit >= GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT)
1853 bit = -1;
1854 else
1855 p = end;
1856 }
1857
1858 if (bit < 0) {
1859 fdisk_warnx(cxt, _("unsupported GPT attribute bit '%s'"), p);
1860 return -EINVAL;
1861 }
1862
1863 if (*p && *p != ',' && !isblank(*p)) {
1864 fdisk_warnx(cxt, _("failed to parse GPT attribute string '%s'"), str);
1865 return -EINVAL;
1866 }
1867
1868 setbit(bits, bit);
1869
1870 while (isblank(*p)) p++;
1871 if (*p == ',')
1872 p++;
1873 }
1874
1875 e->attrs = attrs;
1876 return 0;
1877}
1878
1879static int gpt_get_partition(struct fdisk_context *cxt, size_t n,
1880 struct fdisk_partition *pa)
1881{
1882 struct fdisk_gpt_label *gpt;
1883 struct gpt_entry *e;
1884 char u_str[UUID_STR_LEN];
1885 int rc = 0;
1886 struct gpt_guid guid;
1887
1888 assert(cxt);
1889 assert(cxt->label);
1890 assert(fdisk_is_label(cxt, GPT));
1891
1892 gpt = self_label(cxt);
1893
1894 if (n >= gpt_get_nentries(gpt))
1895 return -EINVAL;
1896
1897 gpt = self_label(cxt);
1898 e = gpt_get_entry(gpt, n);
1899
1900 pa->used = gpt_entry_is_used(e) || gpt_partition_start(e);
1901 if (!pa->used)
1902 return 0;
1903
1904 pa->start = gpt_partition_start(e);
1905 pa->size = gpt_partition_size(e);
1906 pa->type = gpt_partition_parttype(cxt, e);
1907
1908 guid = e->partition_guid;
1909 if (guid_to_string(&guid, u_str)) {
1910 pa->uuid = strdup(u_str);
1911 if (!pa->uuid) {
1912 rc = -errno;
1913 goto done;
1914 }
1915 } else
1916 pa->uuid = NULL;
1917
1918 rc = gpt_entry_attrs_to_string(e, &pa->attrs);
1919 if (rc)
1920 goto done;
1921
1922 pa->name = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1923 return 0;
1924done:
1925 fdisk_reset_partition(pa);
1926 return rc;
1927}
1928
1929
1930static int gpt_set_partition(struct fdisk_context *cxt, size_t n,
1931 struct fdisk_partition *pa)
1932{
1933 struct fdisk_gpt_label *gpt;
1934 struct gpt_entry *e;
1935 int rc = 0;
1936 uint64_t start, end;
1937
1938 assert(cxt);
1939 assert(cxt->label);
1940 assert(fdisk_is_label(cxt, GPT));
1941
1942 gpt = self_label(cxt);
1943
1944 if (n >= gpt_get_nentries(gpt))
1945 return -EINVAL;
1946
1947 FDISK_INIT_UNDEF(start);
1948 FDISK_INIT_UNDEF(end);
1949
1950 gpt = self_label(cxt);
1951 e = gpt_get_entry(gpt, n);
1952
1953 if (pa->uuid) {
1954 char new_u[UUID_STR_LEN], old_u[UUID_STR_LEN];
1955 struct gpt_guid guid;
1956
1957 guid = e->partition_guid;
1958 guid_to_string(&guid, old_u);
1959 rc = gpt_entry_set_uuid(e, pa->uuid);
1960 if (rc)
1961 return rc;
1962 guid = e->partition_guid;
1963 guid_to_string(&guid, new_u);
1964 fdisk_info(cxt, _("Partition UUID changed from %s to %s."),
1965 old_u, new_u);
1966 }
1967
1968 if (pa->name) {
1969 int len;
1970 char *old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1971 len = gpt_entry_set_name(e, pa->name);
1972 if (len < 0)
1973 fdisk_warn(cxt, _("Failed to translate partition name, name not changed."));
1974 else
1975 fdisk_info(cxt, _("Partition name changed from '%s' to '%.*s'."),
1976 old, len, pa->name);
1977 free(old);
1978 }
1979
1980 if (pa->type && pa->type->typestr) {
1981 struct gpt_guid typeid;
1982
1983 rc = string_to_guid(pa->type->typestr, &typeid);
1984 if (rc)
1985 return rc;
1986 gpt_entry_set_type(e, &typeid);
1987 }
1988 if (pa->attrs) {
1989 rc = gpt_entry_attrs_from_string(cxt, e, pa->attrs);
1990 if (rc)
1991 return rc;
1992 }
1993
1994 if (fdisk_partition_has_start(pa))
1995 start = pa->start;
1996 if (fdisk_partition_has_size(pa) || fdisk_partition_has_start(pa)) {
1997 uint64_t xstart = fdisk_partition_has_start(pa) ? pa->start : gpt_partition_start(e);
1998 uint64_t xsize = fdisk_partition_has_size(pa) ? pa->size : gpt_partition_size(e);
1999 end = xstart + xsize - 1ULL;
2000 }
2001
2002 if (!FDISK_IS_UNDEF(start)) {
2003 if (start < le64_to_cpu(gpt->pheader->first_usable_lba)) {
2004 fdisk_warnx(cxt, _("The start of the partition understeps FirstUsableLBA."));
2005 return -EINVAL;
2006 }
2007 e->lba_start = cpu_to_le64(start);
2008 }
2009 if (!FDISK_IS_UNDEF(end)) {
2010 if (end > le64_to_cpu(gpt->pheader->last_usable_lba)) {
2011 fdisk_warnx(cxt, _("The end of the partition oversteps LastUsableLBA."));
2012 return -EINVAL;
2013 }
2014 e->lba_end = cpu_to_le64(end);
2015 }
2016 gpt_recompute_crc(gpt->pheader, gpt->ents);
2017 gpt_recompute_crc(gpt->bheader, gpt->ents);
2018
2019 fdisk_label_set_changed(cxt->label, 1);
2020 return rc;
2021}
2022
2023static int gpt_read(struct fdisk_context *cxt, off_t offset, void *buf, size_t count)
2024{
2025 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
2026 return -errno;
2027
2028 if (read_all(cxt->dev_fd, buf, count))
2029 return -errno;
2030
2031 DBG(GPT, ul_debug(" read OK [offset=%zu, size=%zu]",
2032 (size_t) offset, count));
2033 return 0;
2034}
2035
2036static int gpt_write(struct fdisk_context *cxt, off_t offset, void *buf, size_t count)
2037{
2038 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
2039 return -errno;
2040
2041 if (write_all(cxt->dev_fd, buf, count))
2042 return -errno;
2043
2044 if (fsync(cxt->dev_fd) != 0)
2045 return -errno;
2046
2047 DBG(GPT, ul_debug(" write OK [offset=%zu, size=%zu]",
2048 (size_t) offset, count));
2049 return 0;
2050}
2051
2052/*
2053 * Write partitions.
2054 * Returns 0 on success, or corresponding error otherwise.
2055 */
2056static int gpt_write_partitions(struct fdisk_context *cxt,
2057 struct gpt_header *header, unsigned char *ents)
2058{
2059 size_t esz = 0;
2060 int rc;
2061
2062 rc = gpt_sizeof_entries(header, &esz);
2063 if (rc)
2064 return rc;
2065
2066 return gpt_write(cxt,
2067 (off_t) le64_to_cpu(header->partition_entry_lba) * cxt->sector_size,
2068 ents, esz);
2069}
2070
2071/*
2072 * Write a GPT header to a specified LBA.
2073 *
2074 * We read all sector, so we have to write all sector back
2075 * to the device -- never ever rely on sizeof(struct gpt_header)!
2076 *
2077 * Returns 0 on success, or corresponding error otherwise.
2078 */
2079static int gpt_write_header(struct fdisk_context *cxt,
2080 struct gpt_header *header, uint64_t lba)
2081{
2082 return gpt_write(cxt, lba * cxt->sector_size, header, cxt->sector_size);
2083}
2084
2085/*
2086 * Write the protective MBR.
2087 * Returns 0 on success, or corresponding error otherwise.
2088 */
2089static int gpt_write_pmbr(struct fdisk_context *cxt)
2090{
2091 struct gpt_legacy_mbr *pmbr;
2092 struct gpt_legacy_mbr *current;
2093 int rc;
2094
2095 assert(cxt);
2096 assert(cxt->firstsector);
2097
2098 DBG(GPT, ul_debug("(over)writing PMBR"));
2099 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
2100
2101 /* zero out the legacy partitions */
2102 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
2103
2104 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
2105 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
2106 pmbr->partition_record[0].start_sector = 2;
2107 pmbr->partition_record[0].end_head = 0xFF;
2108 pmbr->partition_record[0].end_sector = 0xFF;
2109 pmbr->partition_record[0].end_track = 0xFF;
2110 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
2111
2112 /*
2113 * Set size_in_lba to the size of the disk minus one. If the size of the disk
2114 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
2115 */
2116 if (cxt->total_sectors - 1ULL > 0xFFFFFFFFULL)
2117 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
2118 else
2119 pmbr->partition_record[0].size_in_lba =
2120 cpu_to_le32((uint32_t) (cxt->total_sectors - 1ULL));
2121
2122 /* Read the current PMBR and compare it with the new, don't write if
2123 * the same. */
2124 current = malloc(sizeof(*current));
2125 if (!current)
2126 goto do_write;
2127
2128 rc = gpt_read(cxt, GPT_PMBR_LBA * cxt->sector_size,
2129 current, sizeof(*current));
2130 if (!rc)
2131 rc = memcmp(pmbr, current, sizeof(*current));
2132
2133 free(current);
2134
2135 if (!rc) {
2136 DBG(GPT, ul_debug("Same MBR on disk => don't write it"));
2137 return 0;
2138 }
2139
2140 do_write:
2141 /* pMBR covers the first sector (LBA) of the disk */
2142 return gpt_write(cxt, GPT_PMBR_LBA * cxt->sector_size,
2143 pmbr, cxt->sector_size);
2144}
2145
2146/*
2147 * Writes in-memory GPT and pMBR data to disk.
2148 * Returns 0 if successful write, otherwise, a corresponding error.
2149 * Any indication of error will abort the operation.
2150 */
2151static int gpt_write_disklabel(struct fdisk_context *cxt)
2152{
2153 struct fdisk_gpt_label *gpt;
2154 int mbr_type;
2155
2156 assert(cxt);
2157 assert(cxt->label);
2158 assert(fdisk_is_label(cxt, GPT));
2159
2160 DBG(GPT, ul_debug("writing..."));
2161
2162 gpt = self_label(cxt);
2163 mbr_type = valid_pmbr(cxt);
2164
2165 /* check that disk is big enough to handle the backup header */
2166 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
2167 goto err0;
2168
2169 /* check that the backup header is properly placed */
2170 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1ULL)
2171 goto err0;
2172
2173 if (check_overlap_partitions(gpt))
2174 goto err0;
2175
2176 if (gpt->minimize)
2177 gpt_minimize_alternative_lba(cxt, gpt);
2178
2179 /* recompute CRCs for both headers */
2180 gpt_recompute_crc(gpt->pheader, gpt->ents);
2181 gpt_recompute_crc(gpt->bheader, gpt->ents);
2182
2183 /*
2184 * UEFI requires writing in this specific order:
2185 * 1) backup partition tables
2186 * 2) backup GPT header
2187 * 3) primary partition tables
2188 * 4) primary GPT header
2189 * 5) protective MBR
2190 *
2191 * If any write fails, we abort the rest.
2192 */
2193 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
2194 goto err1;
2195 if (gpt_write_header(cxt, gpt->bheader,
2196 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
2197 goto err1;
2198 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
2199 goto err1;
2200 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
2201 goto err1;
2202
2203 if (mbr_type == GPT_MBR_HYBRID)
2204 fdisk_warnx(cxt, _("The device contains hybrid MBR -- writing GPT only."));
2205 else if (gpt_write_pmbr(cxt) != 0)
2206 goto err1;
2207
2208 DBG(GPT, ul_debug("...write success"));
2209 return 0;
2210err0:
2211 DBG(GPT, ul_debug("...write failed: incorrect input"));
2212 errno = EINVAL;
2213 return -EINVAL;
2214err1:
2215 DBG(GPT, ul_debug("...write failed: %m"));
2216 return -errno;
2217}
2218
2219/*
2220 * Verify data integrity and report any found problems for:
2221 * - primary and backup header validations
2222 * - partition validations
2223 */
2224static int gpt_verify_disklabel(struct fdisk_context *cxt)
2225{
2226 int nerror = 0;
2227 unsigned int ptnum;
2228 struct fdisk_gpt_label *gpt;
2229
2230 assert(cxt);
2231 assert(cxt->label);
2232 assert(fdisk_is_label(cxt, GPT));
2233
2234 gpt = self_label(cxt);
2235 if (!gpt)
2236 return -EINVAL;
2237
2238 if (!gpt->bheader) {
2239 nerror++;
2240 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
2241 }
2242
2243 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
2244 nerror++;
2245 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
2246 }
2247 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
2248 nerror++;
2249 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
2250 }
2251
2252 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
2253 nerror++;
2254 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
2255 }
2256
2257 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
2258 nerror++;
2259 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
2260 }
2261 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
2262 nerror++;
2263 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
2264 }
2265
2266 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
2267 nerror++;
2268 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
2269 }
2270 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
2271 nerror++;
2272 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
2273
2274 }
2275 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
2276 nerror++;
2277 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
2278 }
2279
2280 /*
2281 * if the GPT is the primary table, check the alternateLBA
2282 * to see if it is a valid GPT
2283 */
2284 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
2285 le64_to_cpu(gpt->bheader->alternative_lba))) {
2286 nerror++;
2287 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
2288 }
2289
2290 ptnum = check_overlap_partitions(gpt);
2291 if (ptnum) {
2292 nerror++;
2293 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
2294 ptnum, ptnum+1);
2295 }
2296
2297 ptnum = check_too_big_partitions(gpt, cxt->total_sectors);
2298 if (ptnum) {
2299 nerror++;
2300 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
2301 ptnum);
2302 }
2303
2304 ptnum = check_start_after_end_partitions(gpt);
2305 if (ptnum) {
2306 nerror++;
2307 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
2308 ptnum);
2309 }
2310
2311 if (!nerror) { /* yay :-) */
2312 uint32_t nsegments = 0;
2313 uint64_t free_sectors = 0, largest_segment = 0;
2314 char *strsz = NULL;
2315
2316 fdisk_info(cxt, _("No errors detected."));
2317 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
2318 fdisk_info(cxt, _("Using %zu out of %zu partitions."),
2319 partitions_in_use(gpt),
2320 gpt_get_nentries(gpt));
2321
2322 free_sectors = get_free_sectors(cxt, gpt, &nsegments, &largest_segment);
2323 if (largest_segment)
2324 strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER,
2325 largest_segment * cxt->sector_size);
2326
2327 fdisk_info(cxt,
2328 P_("A total of %ju free sectors is available in %u segment.",
2329 "A total of %ju free sectors is available in %u segments "
2330 "(the largest is %s).", nsegments),
2331 free_sectors, nsegments, strsz ? : "0 B");
2332 free(strsz);
2333
2334 } else
2335 fdisk_warnx(cxt,
2336 P_("%d error detected.", "%d errors detected.", nerror),
2337 nerror);
2338
2339 return nerror;
2340}
2341
2342/* Delete a single GPT partition, specified by partnum. */
2343static int gpt_delete_partition(struct fdisk_context *cxt,
2344 size_t partnum)
2345{
2346 struct fdisk_gpt_label *gpt;
2347
2348 assert(cxt);
2349 assert(cxt->label);
2350 assert(fdisk_is_label(cxt, GPT));
2351
2352 gpt = self_label(cxt);
2353
2354 if (partnum >= cxt->label->nparts_max)
2355 return -EINVAL;
2356
2357 if (!gpt_entry_is_used(gpt_get_entry(gpt, partnum)))
2358 return -EINVAL;
2359
2360 /* hasta la vista, baby! */
2361 gpt_zeroize_entry(gpt, partnum);
2362
2363 gpt_recompute_crc(gpt->pheader, gpt->ents);
2364 gpt_recompute_crc(gpt->bheader, gpt->ents);
2365 cxt->label->nparts_cur--;
2366 fdisk_label_set_changed(cxt->label, 1);
2367
2368 return 0;
2369}
2370
2371
2372/* Performs logical checks to add a new partition entry */
2373static int gpt_add_partition(
2374 struct fdisk_context *cxt,
2375 struct fdisk_partition *pa,
2376 size_t *partno)
2377{
2378 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
2379 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
2380 uint64_t dflt_f, dflt_l, max_l; /* largest segment (default) */
2381 struct gpt_guid typeid;
2382 struct fdisk_gpt_label *gpt;
2383 struct gpt_header *pheader;
2384 struct gpt_entry *e;
2385 struct fdisk_ask *ask = NULL;
2386 size_t partnum;
2387 int rc;
2388
2389 assert(cxt);
2390 assert(cxt->label);
2391 assert(fdisk_is_label(cxt, GPT));
2392
2393 gpt = self_label(cxt);
2394
2395 assert(gpt);
2396 assert(gpt->pheader);
2397 assert(gpt->ents);
2398
2399 pheader = gpt->pheader;
2400
2401 rc = fdisk_partition_next_partno(pa, cxt, &partnum);
2402 if (rc) {
2403 DBG(GPT, ul_debug("failed to get next partno"));
2404 return rc;
2405 }
2406
2407 assert(partnum < gpt_get_nentries(gpt));
2408
2409 if (gpt_entry_is_used(gpt_get_entry(gpt, partnum))) {
2410 fdisk_warnx(cxt, _("Partition %zu is already defined. "
2411 "Delete it before re-adding it."), partnum +1);
2412 return -ERANGE;
2413 }
2414 if (gpt_get_nentries(gpt) == partitions_in_use(gpt)) {
2415 fdisk_warnx(cxt, _("All partitions are already in use."));
2416 return -ENOSPC;
2417 }
2418 if (!get_free_sectors(cxt, gpt, NULL, NULL)) {
2419 fdisk_warnx(cxt, _("No free sectors available."));
2420 return -ENOSPC;
2421 }
2422
2423 rc = string_to_guid(pa && pa->type && pa->type->typestr ?
2424 pa->type->typestr:
2425 GPT_DEFAULT_ENTRY_TYPE, &typeid);
2426 if (rc)
2427 return rc;
2428
2429 disk_f = find_first_available(gpt, le64_to_cpu(pheader->first_usable_lba));
2430 e = gpt_get_entry(gpt, 0);
2431
2432 /* if first sector no explicitly defined then ignore small gaps before
2433 * the first partition */
2434 if ((!pa || !fdisk_partition_has_start(pa))
2435 && gpt_entry_is_used(e)
2436 && disk_f < gpt_partition_start(e)) {
2437
2438 do {
2439 uint64_t x;
2440 DBG(GPT, ul_debug("testing first sector %"PRIu64"", disk_f));
2441 disk_f = find_first_available(gpt, disk_f);
2442 if (!disk_f)
2443 break;
2444 x = find_last_free(gpt, disk_f);
2445 if (x - disk_f >= cxt->grain / cxt->sector_size)
2446 break;
2447 DBG(GPT, ul_debug("first sector %"PRIu64" addresses to small space, continue...", disk_f));
2448 disk_f = x + 1ULL;
2449 } while(1);
2450
2451 if (disk_f == 0)
2452 disk_f = find_first_available(gpt, le64_to_cpu(pheader->first_usable_lba));
2453 }
2454
2455 e = NULL;
2456 disk_l = find_last_free_sector(gpt);
2457
2458 /* the default is the largest free space */
2459 dflt_f = find_first_in_largest(gpt);
2460 dflt_l = find_last_free(gpt, dflt_f);
2461
2462 /* don't offer too small free space by default, this is possible to
2463 * bypass by sfdisk script */
2464 if ((!pa || !fdisk_partition_has_start(pa))
2465 && dflt_l - dflt_f + 1 < cxt->grain / cxt->sector_size) {
2466 fdisk_warnx(cxt, _("No enough free sectors available."));
2467 return -ENOSPC;
2468 }
2469
2470 /* align the default in range <dflt_f,dflt_l>*/
2471 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
2472
2473 /* first sector */
2474 if (pa && pa->start_follow_default) {
2475 user_f = dflt_f;
2476
2477 } else if (pa && fdisk_partition_has_start(pa)) {
2478 DBG(GPT, ul_debug("first sector defined: %ju", (uintmax_t)pa->start));
2479 if (pa->start != find_first_available(gpt, pa->start)) {
2480 fdisk_warnx(cxt, _("Sector %ju already used."), (uintmax_t)pa->start);
2481 return -ERANGE;
2482 }
2483 user_f = pa->start;
2484 } else {
2485 /* ask by dialog */
2486 for (;;) {
2487 if (!ask)
2488 ask = fdisk_new_ask();
2489 else
2490 fdisk_reset_ask(ask);
2491 if (!ask)
2492 return -ENOMEM;
2493
2494 /* First sector */
2495 fdisk_ask_set_query(ask, _("First sector"));
2496 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
2497 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
2498 fdisk_ask_number_set_default(ask, dflt_f); /* default */
2499 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
2500
2501 rc = fdisk_do_ask(cxt, ask);
2502 if (rc)
2503 goto done;
2504
2505 user_f = fdisk_ask_number_get_result(ask);
2506 if (user_f != find_first_available(gpt, user_f)) {
2507 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
2508 continue;
2509 }
2510 break;
2511 }
2512 }
2513
2514
2515 /* Last sector */
2516 dflt_l = max_l = find_last_free(gpt, user_f);
2517
2518 /* Make sure the last partition has aligned size by default because
2519 * range specified by LastUsableLBA may be unaligned on disks where
2520 * logical sector != physical (512/4K) because backup header size is
2521 * calculated from logical sectors. */
2522 if (max_l == le64_to_cpu(gpt->pheader->last_usable_lba))
2523 dflt_l = fdisk_align_lba_in_range(cxt, max_l, user_f, max_l) - 1;
2524
2525 if (pa && pa->end_follow_default) {
2526 user_l = dflt_l;
2527
2528 } else if (pa && fdisk_partition_has_size(pa)) {
2529 user_l = user_f + pa->size - 1;
2530 DBG(GPT, ul_debug("size defined: %ju, end: %"PRIu64
2531 "(last possible: %"PRIu64", optimal: %"PRIu64")",
2532 (uintmax_t)pa->size, user_l, max_l, dflt_l));
2533
2534 if (user_l != dflt_l
2535 && !pa->size_explicit
2536 && alignment_required(cxt)
2537 && user_l - user_f > (cxt->grain / fdisk_get_sector_size(cxt))) {
2538
2539 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2540 if (user_l > user_f)
2541 user_l -= 1ULL;
2542 }
2543 } else {
2544 for (;;) {
2545 if (!ask)
2546 ask = fdisk_new_ask();
2547 else
2548 fdisk_reset_ask(ask);
2549 if (!ask)
2550 return -ENOMEM;
2551
2552 fdisk_ask_set_query(ask, _("Last sector, +/-sectors or +/-size{K,M,G,T,P}"));
2553 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
2554 fdisk_ask_number_set_low(ask, user_f); /* minimal */
2555 fdisk_ask_number_set_default(ask, dflt_l); /* default */
2556 fdisk_ask_number_set_high(ask, max_l); /* maximal */
2557 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
2558 fdisk_ask_number_set_unit(ask, cxt->sector_size);
2559 fdisk_ask_number_set_wrap_negative(ask, 1); /* wrap negative around high */
2560
2561 rc = fdisk_do_ask(cxt, ask);
2562 if (rc)
2563 goto done;
2564
2565 user_l = fdisk_ask_number_get_result(ask);
2566 if (fdisk_ask_number_is_relative(ask)) {
2567 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2568 if (user_l > user_f)
2569 user_l -= 1ULL;
2570 }
2571
2572 if (user_l >= user_f && user_l <= disk_l)
2573 break;
2574
2575 fdisk_warnx(cxt, _("Value out of range."));
2576 }
2577 }
2578
2579
2580 if (user_f > user_l || partnum >= cxt->label->nparts_max) {
2581 fdisk_warnx(cxt, _("Could not create partition %zu"), partnum + 1);
2582 rc = -EINVAL;
2583 goto done;
2584 }
2585
2586 /* Be paranoid and check against on-disk setting rather than against libfdisk cxt */
2587 if (user_l > le64_to_cpu(pheader->last_usable_lba)) {
2588 fdisk_warnx(cxt, _("The last usable GPT sector is %ju, but %ju is requested."),
2589 le64_to_cpu(pheader->last_usable_lba), user_l);
2590 rc = -EINVAL;
2591 goto done;
2592 }
2593
2594 if (user_f < le64_to_cpu(pheader->first_usable_lba)) {
2595 fdisk_warnx(cxt, _("The first usable GPT sector is %ju, but %ju is requested."),
2596 le64_to_cpu(pheader->first_usable_lba), user_f);
2597 rc = -EINVAL;
2598 goto done;
2599 }
2600
2601 assert(!FDISK_IS_UNDEF(user_l));
2602 assert(!FDISK_IS_UNDEF(user_f));
2603 assert(partnum < gpt_get_nentries(gpt));
2604
2605 e = gpt_get_entry(gpt, partnum);
2606 e->lba_end = cpu_to_le64(user_l);
2607 e->lba_start = cpu_to_le64(user_f);
2608
2609 gpt_entry_set_type(e, &typeid);
2610
2611 if (pa && pa->uuid) {
2612 /* Sometimes it's necessary to create a copy of the PT and
2613 * reuse already defined UUID
2614 */
2615 rc = gpt_entry_set_uuid(e, pa->uuid);
2616 if (rc)
2617 goto done;
2618 } else {
2619 /* Any time a new partition entry is created a new GUID must be
2620 * generated for that partition, and every partition is guaranteed
2621 * to have a unique GUID.
2622 */
2623 struct gpt_guid guid;
2624
2625 uuid_generate_random((unsigned char *) &guid);
2626 swap_efi_guid(&guid);
2627 e->partition_guid = guid;
2628 }
2629
2630 if (pa && pa->name && *pa->name)
2631 gpt_entry_set_name(e, pa->name);
2632 if (pa && pa->attrs)
2633 gpt_entry_attrs_from_string(cxt, e, pa->attrs);
2634
2635 DBG(GPT, ul_debug("new partition: partno=%zu, start=%"PRIu64", end=%"PRIu64", size=%"PRIu64"",
2636 partnum,
2637 gpt_partition_start(e),
2638 gpt_partition_end(e),
2639 gpt_partition_size(e)));
2640
2641 gpt_recompute_crc(gpt->pheader, gpt->ents);
2642 gpt_recompute_crc(gpt->bheader, gpt->ents);
2643
2644 /* report result */
2645 {
2646 struct fdisk_parttype *t;
2647
2648 cxt->label->nparts_cur++;
2649 fdisk_label_set_changed(cxt->label, 1);
2650
2651 t = gpt_partition_parttype(cxt, e);
2652 fdisk_info_new_partition(cxt, partnum + 1, user_f, user_l, t);
2653 fdisk_unref_parttype(t);
2654 }
2655
2656 rc = 0;
2657 if (partno)
2658 *partno = partnum;
2659done:
2660 fdisk_unref_ask(ask);
2661 return rc;
2662}
2663
2664/*
2665 * Create a new GPT disklabel - destroys any previous data.
2666 */
2667static int gpt_create_disklabel(struct fdisk_context *cxt)
2668{
2669 int rc = 0;
2670 size_t esz = 0;
2671 char str[UUID_STR_LEN];
2672 struct fdisk_gpt_label *gpt;
2673 struct gpt_guid guid;
2674
2675 assert(cxt);
2676 assert(cxt->label);
2677 assert(fdisk_is_label(cxt, GPT));
2678
2679 gpt = self_label(cxt);
2680
2681 /* label private stuff has to be empty, see gpt_deinit() */
2682 assert(gpt->pheader == NULL);
2683 assert(gpt->bheader == NULL);
2684
2685 /*
2686 * When no header, entries or pmbr is set, we're probably
2687 * dealing with a new, empty disk - so always allocate memory
2688 * to deal with the data structures whatever the case is.
2689 */
2690 rc = gpt_mknew_pmbr(cxt);
2691 if (rc < 0)
2692 goto done;
2693
2694 assert(cxt->sector_size >= sizeof(struct gpt_header));
2695
2696 /* primary */
2697 gpt->pheader = calloc(1, cxt->sector_size);
2698 if (!gpt->pheader) {
2699 rc = -ENOMEM;
2700 goto done;
2701 }
2702 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
2703 if (rc < 0)
2704 goto done;
2705
2706 /* backup ("copy" primary) */
2707 gpt->bheader = calloc(1, cxt->sector_size);
2708 if (!gpt->bheader) {
2709 rc = -ENOMEM;
2710 goto done;
2711 }
2712 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
2713 last_lba(cxt), gpt->pheader);
2714 if (rc < 0)
2715 goto done;
2716
2717 rc = gpt_sizeof_entries(gpt->pheader, &esz);
2718 if (rc)
2719 goto done;
2720 gpt->ents = calloc(1, esz);
2721 if (!gpt->ents) {
2722 rc = -ENOMEM;
2723 goto done;
2724 }
2725 gpt_recompute_crc(gpt->pheader, gpt->ents);
2726 gpt_recompute_crc(gpt->bheader, gpt->ents);
2727
2728 cxt->label->nparts_max = gpt_get_nentries(gpt);
2729 cxt->label->nparts_cur = 0;
2730
2731 guid = gpt->pheader->disk_guid;
2732 guid_to_string(&guid, str);
2733 fdisk_label_set_changed(cxt->label, 1);
2734 fdisk_info(cxt, _("Created a new GPT disklabel (GUID: %s)."), str);
2735
2736 if (gpt_get_nentries(gpt) < GPT_NPARTITIONS)
2737 fdisk_info(cxt, _("The maximal number of partitions is %zu (default is %zu)."),
2738 gpt_get_nentries(gpt), GPT_NPARTITIONS);
2739done:
2740 return rc;
2741}
2742
2743static int gpt_set_disklabel_id(struct fdisk_context *cxt, const char *str)
2744{
2745 struct fdisk_gpt_label *gpt;
2746 struct gpt_guid uuid;
2747 char *old, *new;
2748 int rc;
2749
2750 assert(cxt);
2751 assert(cxt->label);
2752 assert(fdisk_is_label(cxt, GPT));
2753
2754 gpt = self_label(cxt);
2755 if (!str) {
2756 char *buf = NULL;
2757
2758 if (fdisk_ask_string(cxt,
2759 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &buf))
2760 return -EINVAL;
2761 rc = string_to_guid(buf, &uuid);
2762 free(buf);
2763 } else
2764 rc = string_to_guid(str, &uuid);
2765
2766 if (rc) {
2767 fdisk_warnx(cxt, _("Failed to parse your UUID."));
2768 return rc;
2769 }
2770
2771 old = gpt_get_header_id(gpt->pheader);
2772
2773 gpt->pheader->disk_guid = uuid;
2774 gpt->bheader->disk_guid = uuid;
2775
2776 gpt_recompute_crc(gpt->pheader, gpt->ents);
2777 gpt_recompute_crc(gpt->bheader, gpt->ents);
2778
2779 new = gpt_get_header_id(gpt->pheader);
2780
2781 fdisk_info(cxt, _("Disk identifier changed from %s to %s."), old, new);
2782
2783 free(old);
2784 free(new);
2785 fdisk_label_set_changed(cxt->label, 1);
2786 return 0;
2787}
2788
2789static int gpt_check_table_overlap(struct fdisk_context *cxt,
2790 uint64_t first_usable,
2791 uint64_t last_usable)
2792{
2793 struct fdisk_gpt_label *gpt = self_label(cxt);
2794 size_t i;
2795 int rc = 0;
2796
2797 /* First check if there's enough room for the table. last_lba may have wrapped */
2798 if (first_usable > cxt->total_sectors || /* far too little space */
2799 last_usable > cxt->total_sectors || /* wrapped */
2800 first_usable > last_usable) { /* too little space */
2801 fdisk_warnx(cxt, _("Not enough space for new partition table!"));
2802 return -ENOSPC;
2803 }
2804
2805 /* check that all partitions fit in the remaining space */
2806 for (i = 0; i < gpt_get_nentries(gpt); i++) {
2807 struct gpt_entry *e = gpt_get_entry(gpt, i);
2808
2809 if (!gpt_entry_is_used(e))
2810 continue;
2811 if (gpt_partition_start(e) < first_usable) {
2812 fdisk_warnx(cxt, _("Partition #%zu out of range (minimal start is %"PRIu64" sectors)"),
2813 i + 1, first_usable);
2814 rc = -EINVAL;
2815 }
2816 if (gpt_partition_end(e) > last_usable) {
2817 fdisk_warnx(cxt, _("Partition #%zu out of range (maximal end is %"PRIu64" sectors)"),
2818 i + 1, last_usable - (uint64_t) 1);
2819 rc = -EINVAL;
2820 }
2821 }
2822 return rc;
2823}
2824
2825/**
2826 * fdisk_gpt_set_npartitions:
2827 * @cxt: context
2828 * @nents: number of wanted entries
2829 *
2830 * Enlarge GPT entries array if possible. The function check if an existing
2831 * partition does not overlap the entries array area. If yes, then it report
2832 * warning and returns -EINVAL.
2833 *
2834 * Returns: 0 on success, < 0 on error.
2835 * Since: 2.29
2836 */
2837int fdisk_gpt_set_npartitions(struct fdisk_context *cxt, uint32_t nents)
2838{
2839 struct fdisk_gpt_label *gpt;
2840 size_t new_size = 0;
2841 uint32_t old_nents;
2842 uint64_t first_usable = 0ULL, last_usable = 0ULL;
2843 int rc;
2844
2845 assert(cxt);
2846 assert(cxt->label);
2847
2848 if (!fdisk_is_label(cxt, GPT))
2849 return -EINVAL;
2850
2851 gpt = self_label(cxt);
2852
2853 old_nents = le32_to_cpu(gpt->pheader->npartition_entries);
2854 if (old_nents == nents)
2855 return 0; /* do nothing, say nothing */
2856
2857 /* calculate the size (bytes) of the entries array */
2858 rc = gpt_calculate_sizeof_entries(gpt->pheader, nents, &new_size);
2859 if (rc) {
2860 uint32_t entry_size = le32_to_cpu(gpt->pheader->sizeof_partition_entry);
2861
2862 if (entry_size == 0)
2863 fdisk_warnx(cxt, _("The partition entry size is zero."));
2864 else
2865 fdisk_warnx(cxt, _("The number of the partition has to be smaller than %zu."),
2866 (size_t) UINT32_MAX / entry_size);
2867 return rc;
2868 }
2869
2870 rc = gpt_calculate_first_lba(gpt->pheader, nents, &first_usable, cxt);
2871 if (rc == 0)
2872 rc = gpt_calculate_last_lba(gpt->pheader, nents, &last_usable, cxt);
2873 if (rc)
2874 return rc;
2875
2876 /* if expanding the table, first check that everything fits,
2877 * then allocate more memory and zero. */
2878 if (nents > old_nents) {
2879 unsigned char *ents;
2880 size_t old_size = 0;
2881
2882 rc = gpt_calculate_sizeof_entries(gpt->pheader, old_nents, &old_size);
2883 if (rc == 0)
2884 rc = gpt_check_table_overlap(cxt, first_usable, last_usable);
2885 if (rc)
2886 return rc;
2887 ents = realloc(gpt->ents, new_size);
2888 if (!ents) {
2889 fdisk_warnx(cxt, _("Cannot allocate memory!"));
2890 return -ENOMEM;
2891 }
2892 memset(ents + old_size, 0, new_size - old_size);
2893 gpt->ents = ents;
2894 }
2895
2896 /* everything's ok, apply the new size */
2897 gpt->pheader->npartition_entries = cpu_to_le32(nents);
2898 gpt->bheader->npartition_entries = cpu_to_le32(nents);
2899
2900 /* usable LBA addresses will have changed */
2901 fdisk_set_first_lba(cxt, first_usable);
2902 fdisk_set_last_lba(cxt, last_usable);
2903 gpt->pheader->first_usable_lba = cpu_to_le64(first_usable);
2904 gpt->bheader->first_usable_lba = cpu_to_le64(first_usable);
2905 gpt->pheader->last_usable_lba = cpu_to_le64(last_usable);
2906 gpt->bheader->last_usable_lba = cpu_to_le64(last_usable);
2907
2908 /* The backup header must be recalculated */
2909 gpt_mknew_header_common(cxt, gpt->bheader, le64_to_cpu(gpt->pheader->alternative_lba));
2910
2911 /* CRCs will have changed */
2912 gpt_recompute_crc(gpt->pheader, gpt->ents);
2913 gpt_recompute_crc(gpt->bheader, gpt->ents);
2914
2915 /* update library info */
2916 cxt->label->nparts_max = gpt_get_nentries(gpt);
2917
2918 fdisk_info(cxt, _("Partition table length changed from %"PRIu32" to %"PRIu32"."),
2919 old_nents, nents);
2920
2921 fdisk_label_set_changed(cxt->label, 1);
2922 return 0;
2923}
2924
2925static int gpt_part_is_used(struct fdisk_context *cxt, size_t i)
2926{
2927 struct fdisk_gpt_label *gpt;
2928 struct gpt_entry *e;
2929
2930 assert(cxt);
2931 assert(cxt->label);
2932 assert(fdisk_is_label(cxt, GPT));
2933
2934 gpt = self_label(cxt);
2935
2936 if (i >= gpt_get_nentries(gpt))
2937 return 0;
2938
2939 e = gpt_get_entry(gpt, i);
2940
2941 return gpt_entry_is_used(e) || gpt_partition_start(e);
2942}
2943
2944/**
2945 * fdisk_gpt_is_hybrid:
2946 * @cxt: context
2947 *
2948 * The regular GPT contains PMBR (dummy protective MBR) where the protective
2949 * MBR does not address any partitions.
2950 *
2951 * Hybrid GPT contains regular MBR where this partition table addresses the
2952 * same partitions as GPT. It's recommended to not use hybrid GPT due to MBR
2953 * limits.
2954 *
2955 * The libfdisk does not provide functionality to sync GPT and MBR, you have to
2956 * directly access and modify (P)MBR (see fdisk_new_nested_context()).
2957 *
2958 * Returns: 1 if partition table detected as hybrid otherwise return 0
2959 */
2960int fdisk_gpt_is_hybrid(struct fdisk_context *cxt)
2961{
2962 assert(cxt);
2963 return valid_pmbr(cxt) == GPT_MBR_HYBRID;
2964}
2965
2966/**
2967 * fdisk_gpt_get_partition_attrs:
2968 * @cxt: context
2969 * @partnum: partition number
2970 * @attrs: GPT partition attributes
2971 *
2972 * Sets @attrs for the given partition
2973 *
2974 * Returns: 0 on success, <0 on error.
2975 */
2976int fdisk_gpt_get_partition_attrs(
2977 struct fdisk_context *cxt,
2978 size_t partnum,
2979 uint64_t *attrs)
2980{
2981 struct fdisk_gpt_label *gpt;
2982
2983 assert(cxt);
2984 assert(cxt->label);
2985
2986 if (!fdisk_is_label(cxt, GPT))
2987 return -EINVAL;
2988
2989 gpt = self_label(cxt);
2990
2991 if (partnum >= gpt_get_nentries(gpt))
2992 return -EINVAL;
2993
2994 *attrs = le64_to_cpu(gpt_get_entry(gpt, partnum)->attrs);
2995 return 0;
2996}
2997
2998/**
2999 * fdisk_gpt_set_partition_attrs:
3000 * @cxt: context
3001 * @partnum: partition number
3002 * @attrs: GPT partition attributes
3003 *
3004 * Sets the GPT partition attributes field to @attrs.
3005 *
3006 * Returns: 0 on success, <0 on error.
3007 */
3008int fdisk_gpt_set_partition_attrs(
3009 struct fdisk_context *cxt,
3010 size_t partnum,
3011 uint64_t attrs)
3012{
3013 struct fdisk_gpt_label *gpt;
3014
3015 assert(cxt);
3016 assert(cxt->label);
3017
3018 if (!fdisk_is_label(cxt, GPT))
3019 return -EINVAL;
3020
3021 DBG(GPT, ul_debug("entry attributes change requested partno=%zu", partnum));
3022 gpt = self_label(cxt);
3023
3024 if (partnum >= gpt_get_nentries(gpt))
3025 return -EINVAL;
3026
3027 gpt_get_entry(gpt, partnum)->attrs = cpu_to_le64(attrs);
3028 fdisk_info(cxt, _("The attributes on partition %zu changed to 0x%016" PRIx64 "."),
3029 partnum + 1, attrs);
3030
3031 gpt_recompute_crc(gpt->pheader, gpt->ents);
3032 gpt_recompute_crc(gpt->bheader, gpt->ents);
3033 fdisk_label_set_changed(cxt->label, 1);
3034 return 0;
3035}
3036
3037static int gpt_toggle_partition_flag(
3038 struct fdisk_context *cxt,
3039 size_t i,
3040 unsigned long flag)
3041{
3042 struct fdisk_gpt_label *gpt;
3043 struct gpt_entry *e;
3044 uint64_t attrs;
3045 uintmax_t tmp;
3046 char *bits;
3047 const char *name = NULL;
3048 int bit = -1, rc;
3049
3050 assert(cxt);
3051 assert(cxt->label);
3052 assert(fdisk_is_label(cxt, GPT));
3053
3054 DBG(GPT, ul_debug("entry attribute change requested partno=%zu", i));
3055 gpt = self_label(cxt);
3056
3057 if (i >= gpt_get_nentries(gpt))
3058 return -EINVAL;
3059
3060 e = gpt_get_entry(gpt, i);
3061 attrs = e->attrs;
3062 bits = (char *) &attrs;
3063
3064 switch (flag) {
3065 case GPT_FLAG_REQUIRED:
3066 bit = GPT_ATTRBIT_REQ;
3067 name = GPT_ATTRSTR_REQ;
3068 break;
3069 case GPT_FLAG_NOBLOCK:
3070 bit = GPT_ATTRBIT_NOBLOCK;
3071 name = GPT_ATTRSTR_NOBLOCK;
3072 break;
3073 case GPT_FLAG_LEGACYBOOT:
3074 bit = GPT_ATTRBIT_LEGACY;
3075 name = GPT_ATTRSTR_LEGACY;
3076 break;
3077 case GPT_FLAG_GUIDSPECIFIC:
3078 rc = fdisk_ask_number(cxt, 48, 48, 63, _("Enter GUID specific bit"), &tmp);
3079 if (rc)
3080 return rc;
3081 bit = tmp;
3082 break;
3083 default:
3084 /* already specified PT_FLAG_GUIDSPECIFIC bit */
3085 if (flag >= 48 && flag <= 63) {
3086 bit = flag;
3087 flag = GPT_FLAG_GUIDSPECIFIC;
3088 }
3089 break;
3090 }
3091
3092 if (bit < 0) {
3093 fdisk_warnx(cxt, _("failed to toggle unsupported bit %lu"), flag);
3094 return -EINVAL;
3095 }
3096
3097 if (!isset(bits, bit))
3098 setbit(bits, bit);
3099 else
3100 clrbit(bits, bit);
3101
3102 e->attrs = attrs;
3103
3104 if (flag == GPT_FLAG_GUIDSPECIFIC)
3105 fdisk_info(cxt, isset(bits, bit) ?
3106 _("The GUID specific bit %d on partition %zu is enabled now.") :
3107 _("The GUID specific bit %d on partition %zu is disabled now."),
3108 bit, i + 1);
3109 else
3110 fdisk_info(cxt, isset(bits, bit) ?
3111 _("The %s flag on partition %zu is enabled now.") :
3112 _("The %s flag on partition %zu is disabled now."),
3113 name, i + 1);
3114
3115 gpt_recompute_crc(gpt->pheader, gpt->ents);
3116 gpt_recompute_crc(gpt->bheader, gpt->ents);
3117 fdisk_label_set_changed(cxt->label, 1);
3118 return 0;
3119}
3120
3121static int gpt_entry_cmp_start(const void *a, const void *b)
3122{
3123 const struct gpt_entry *ae = (const struct gpt_entry *) a,
3124 *be = (const struct gpt_entry *) b;
3125 int au = gpt_entry_is_used(ae),
3126 bu = gpt_entry_is_used(be);
3127
3128 if (!au && !bu)
3129 return 0;
3130 if (!au)
3131 return 1;
3132 if (!bu)
3133 return -1;
3134
3135 return cmp_numbers(gpt_partition_start(ae), gpt_partition_start(be));
3136}
3137
3138/* sort partition by start sector */
3139static int gpt_reorder(struct fdisk_context *cxt)
3140{
3141 struct fdisk_gpt_label *gpt;
3142 size_t i, nparts, mess;
3143
3144 assert(cxt);
3145 assert(cxt->label);
3146 assert(fdisk_is_label(cxt, GPT));
3147
3148 gpt = self_label(cxt);
3149 nparts = gpt_get_nentries(gpt);
3150
3151 for (i = 0, mess = 0; mess == 0 && i + 1 < nparts; i++)
3152 mess = gpt_entry_cmp_start(
3153 (const void *) gpt_get_entry(gpt, i),
3154 (const void *) gpt_get_entry(gpt, i + 1)) > 0;
3155
3156 if (!mess)
3157 return 1;
3158
3159 qsort(gpt->ents, nparts, sizeof(struct gpt_entry),
3160 gpt_entry_cmp_start);
3161
3162 gpt_recompute_crc(gpt->pheader, gpt->ents);
3163 gpt_recompute_crc(gpt->bheader, gpt->ents);
3164 fdisk_label_set_changed(cxt->label, 1);
3165
3166 return 0;
3167}
3168
3169static int gpt_reset_alignment(struct fdisk_context *cxt)
3170{
3171 struct fdisk_gpt_label *gpt;
3172 struct gpt_header *h;
3173
3174 assert(cxt);
3175 assert(cxt->label);
3176 assert(fdisk_is_label(cxt, GPT));
3177
3178 gpt = self_label(cxt);
3179 h = gpt ? gpt->pheader : NULL;
3180
3181 if (h) {
3182 /* always follow existing table */
3183 cxt->first_lba = le64_to_cpu(h->first_usable_lba);
3184 cxt->last_lba = le64_to_cpu(h->last_usable_lba);
3185 } else {
3186 /* estimate ranges for GPT */
3187 uint64_t first, last;
3188 int rc;
3189
3190 rc = count_first_last_lba(cxt, &first, &last, NULL);
3191 if (rc)
3192 return rc;
3193 if (cxt->first_lba < first)
3194 cxt->first_lba = first;
3195 if (cxt->last_lba > last)
3196 cxt->last_lba = last;
3197 }
3198
3199 return 0;
3200}
3201/*
3202 * Deinitialize fdisk-specific variables
3203 */
3204static void gpt_deinit(struct fdisk_label *lb)
3205{
3206 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
3207
3208 if (!gpt)
3209 return;
3210
3211 free(gpt->ents);
3212 free(gpt->pheader);
3213 free(gpt->bheader);
3214
3215 gpt->ents = NULL;
3216 gpt->pheader = NULL;
3217 gpt->bheader = NULL;
3218}
3219
3220static const struct fdisk_label_operations gpt_operations =
3221{
3222 .probe = gpt_probe_label,
3223 .write = gpt_write_disklabel,
3224 .verify = gpt_verify_disklabel,
3225 .create = gpt_create_disklabel,
3226 .locate = gpt_locate_disklabel,
3227 .get_item = gpt_get_disklabel_item,
3228 .set_id = gpt_set_disklabel_id,
3229
3230 .get_part = gpt_get_partition,
3231 .set_part = gpt_set_partition,
3232 .add_part = gpt_add_partition,
3233 .del_part = gpt_delete_partition,
3234 .reorder = gpt_reorder,
3235
3236 .part_is_used = gpt_part_is_used,
3237 .part_toggle_flag = gpt_toggle_partition_flag,
3238
3239 .deinit = gpt_deinit,
3240
3241 .reset_alignment = gpt_reset_alignment
3242};
3243
3244static const struct fdisk_field gpt_fields[] =
3245{
3246 /* basic */
3247 { FDISK_FIELD_DEVICE, N_("Device"), 10, 0 },
3248 { FDISK_FIELD_START, N_("Start"), 5, FDISK_FIELDFL_NUMBER },
3249 { FDISK_FIELD_END, N_("End"), 5, FDISK_FIELDFL_NUMBER },
3250 { FDISK_FIELD_SECTORS, N_("Sectors"), 5, FDISK_FIELDFL_NUMBER },
3251 { FDISK_FIELD_SIZE, N_("Size"), 5, FDISK_FIELDFL_NUMBER | FDISK_FIELDFL_EYECANDY },
3252 { FDISK_FIELD_TYPE, N_("Type"), 0.1, FDISK_FIELDFL_EYECANDY },
3253 /* expert */
3254 { FDISK_FIELD_TYPEID, N_("Type-UUID"), 36, FDISK_FIELDFL_DETAIL },
3255 { FDISK_FIELD_UUID, N_("UUID"), 36, FDISK_FIELDFL_DETAIL },
3256 { FDISK_FIELD_NAME, N_("Name"), 0.2, FDISK_FIELDFL_DETAIL },
3257 { FDISK_FIELD_ATTR, N_("Attrs"), 0, FDISK_FIELDFL_DETAIL }
3258};
3259
3260/*
3261 * allocates GPT in-memory stuff
3262 */
3263struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt __attribute__ ((__unused__)))
3264{
3265 struct fdisk_label *lb;
3266 struct fdisk_gpt_label *gpt;
3267
3268 gpt = calloc(1, sizeof(*gpt));
3269 if (!gpt)
3270 return NULL;
3271
3272 /* initialize generic part of the driver */
3273 lb = (struct fdisk_label *) gpt;
3274 lb->name = "gpt";
3275 lb->id = FDISK_DISKLABEL_GPT;
3276 lb->op = &gpt_operations;
3277
3278 lb->parttypes = gpt_parttypes;
3279 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
3280 lb->parttype_cuts = gpt_parttype_cuts;
3281 lb->nparttype_cuts = ARRAY_SIZE(gpt_parttype_cuts);
3282
3283 lb->fields = gpt_fields;
3284 lb->nfields = ARRAY_SIZE(gpt_fields);
3285
3286 /* return calloc() result to keep static anaylizers happy */
3287 return (struct fdisk_label *) gpt;
3288}
3289
3290/**
3291 * fdisk_gpt_disable_relocation
3292 * @lb: label
3293 * @disable: 0 or 1
3294 *
3295 * Disable automatic backup header relocation to the end of the device. The
3296 * header position is recalculated during libfdisk probing stage by
3297 * fdisk_assign_device() and later written by fdisk_write_disklabel(), so you
3298 * need to call it before fdisk_assign_device().
3299 *
3300 * Since: 2.36
3301 */
3302void fdisk_gpt_disable_relocation(struct fdisk_label *lb, int disable)
3303{
3304 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
3305
3306 assert(gpt);
3307 gpt->no_relocate = disable ? 1 : 0;
3308}
3309
3310/**
3311 * fdisk_gpt_enable_minimize
3312 * @lb: label
3313 * @enable: 0 or 1
3314 *
3315 * Force libfdisk to write backup header to behind last partition. The
3316 * header position is recalculated on fdisk_write_disklabel().
3317 *
3318 * Since: 2.36
3319 */
3320void fdisk_gpt_enable_minimize(struct fdisk_label *lb, int enable)
3321{
3322 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
3323
3324 assert(gpt);
3325 gpt->minimize = enable ? 1 : 0;
3326}
3327
3328#ifdef TEST_PROGRAM
3329static int test_getattr(struct fdisk_test *ts __attribute__((unused)),
3330 int argc, char *argv[])
3331{
3332 if (argc != 3)
3333 return -1;
3334
3335 const char *disk = argv[1];
3336 size_t part = strtoul(argv[2], NULL, 0) - 1;
3337 struct fdisk_context *cxt;
3338 uint64_t atters = 0;
3339
3340 cxt = fdisk_new_context();
3341 fdisk_assign_device(cxt, disk, 1);
3342
3343 if (!fdisk_is_label(cxt, GPT))
3344 return EXIT_FAILURE;
3345
3346 if (fdisk_gpt_get_partition_attrs(cxt, part, &atters))
3347 return EXIT_FAILURE;
3348
3349 printf("%s: 0x%016" PRIx64 "\n", argv[2], atters);
3350
3351 fdisk_unref_context(cxt);
3352 return 0;
3353}
3354
3355static int test_setattr(struct fdisk_test *ts __attribute__((unused)),
3356 int argc, char *argv[])
3357{
3358 if (argc != 4)
3359 return -1;
3360
3361 const char *disk = argv[1];
3362 size_t part = strtoul(argv[2], NULL, 0) - 1;
3363 uint64_t atters = strtoull(argv[3], NULL, 0);
3364 struct fdisk_context *cxt;
3365
3366 cxt = fdisk_new_context();
3367 fdisk_assign_device(cxt, disk, 0);
3368
3369 if (!fdisk_is_label(cxt, GPT))
3370 return EXIT_FAILURE;
3371
3372 if (fdisk_gpt_set_partition_attrs(cxt, part, atters))
3373 return EXIT_FAILURE;
3374
3375 if (fdisk_write_disklabel(cxt))
3376 return EXIT_FAILURE;
3377
3378 fdisk_unref_context(cxt);
3379 return 0;
3380}
3381
3382int main(int argc, char *argv[])
3383{
3384 struct fdisk_test tss[] = {
3385 { "--getattr", test_getattr, "<disk> <partition> print attributes" },
3386 { "--setattr", test_setattr, "<disk> <partition> <value> set attributes" },
3387 { NULL }
3388 };
3389
3390 return fdisk_run_test(tss, argc, argv);
3391}
3392
3393#endif