]> git.ipfire.org Git - thirdparty/util-linux.git/blame - libfdisk/src/gpt.c
taskset: Accept 0 pid for current process
[thirdparty/util-linux.git] / libfdisk / src / gpt.c
CommitLineData
5dbff4c0 1/*
766d5156
DB
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.
5dbff4c0 8 */
5dbff4c0
KZ
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <inttypes.h>
fbae1442 13#include <stdint.h>
5dbff4c0 14#include <sys/stat.h>
5dbff4c0
KZ
15#include <sys/utsname.h>
16#include <sys/types.h>
17#include <fcntl.h>
18#include <unistd.h>
19#include <errno.h>
766d5156
DB
20#include <ctype.h>
21#include <uuid.h>
5dbff4c0 22
62d50bbe
KZ
23#include "fdiskP.h"
24
766d5156 25#include "crc32.h"
810f986b 26#include "blkdev.h"
9eca9d0d 27#include "bitops.h"
766d5156 28#include "strutils.h"
19613111 29#include "all-io.h"
3457d90e 30#include "pt-mbr.h"
487b57f5 31#include "encode.h"
766d5156 32
0077e7cd
KZ
33/**
34 * SECTION: gpt
705854f3
KZ
35 * @title: UEFI GPT
36 * @short_description: specific functionality
0077e7cd
KZ
37 */
38
766d5156
DB
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
e9bf0935 43#define GPT_HEADER_MINSZ 92 /* bytes */
766d5156
DB
44
45#define GPT_PMBR_LBA 0
46#define GPT_MBR_PROTECTIVE 1
47#define GPT_MBR_HYBRID 2
48
0a7cdf80 49#define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001ULL
766d5156
DB
50
51#define EFI_PMBR_OSTYPE 0xEE
52#define MSDOS_MBR_SIGNATURE 0xAA55
e39966c6 53#define GPT_PART_NAME_LEN (72 / sizeof(uint16_t))
fbae1442 54#define GPT_NPARTITIONS ((size_t) FDISK_GPT_NPARTITIONS_DEFAULT)
766d5156
DB
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 */
c0d14b09 73#define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
766d5156
DB
74
75/*
76 * Attribute bits
77 */
01086b80
KZ
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};
c83f772e 88
d1b7bfe5
SR
89#define GPT_ATTRSTR_REQ "RequiredPartition"
90#define GPT_ATTRSTR_REQ_TYPO "RequiredPartiton"
01086b80
KZ
91#define GPT_ATTRSTR_NOBLOCK "NoBlockIOProtocol"
92#define GPT_ATTRSTR_LEGACY "LegacyBIOSBootable"
c83f772e 93
766d5156
DB
94/* The GPT Partition entry array contains an array of GPT entries. */
95struct gpt_entry {
d45fa25d
KZ
96 struct gpt_guid type; /* purpose and type of the partition */
97 struct gpt_guid partition_guid;
766d5156
DB
98 uint64_t lba_start;
99 uint64_t lba_end;
01086b80 100 uint64_t attrs;
d45fa25d 101 uint16_t name[GPT_PART_NAME_LEN];
766d5156
DB
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 */
9ed38607 111 uint64_t my_lba; /* LBA of block that contains this struct (LBA 1) */
766d5156
DB
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 */
3f731001 115 struct gpt_guid disk_guid; /* unique disk identifier */
9ed38607 116 uint64_t partition_entry_lba; /* LBA of start of partition entries array */
766d5156
DB
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 */
9ed38607 120 uint8_t reserved2[512 - 92]; /* must all be 0 */
766d5156
DB
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
3ca03d59 155static const struct fdisk_parttype gpt_parttypes[] =
766d5156 156{
96c2b09f 157 #include "pt-gpt-partnames.h"
766d5156
DB
158};
159
f94e753b
KZ
160static const struct fdisk_shortcut gpt_parttype_cuts[] =
161{
2d07a4de
TW
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 */
f94e753b
KZ
169};
170
694a407d
KZ
171#define alignment_required(_x) ((_x)->grain != (_x)->sector_size)
172
d71ef5a4 173/* gpt_entry macros */
874aa9c3
KZ
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
d71ef5a4
KZ
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 */
b28df75e
KZ
186
187 unsigned char *ents; /* entries (partitions) */
387ac277
KZ
188
189 unsigned int no_relocate :1, /* do not fix backup location */
190 minimize :1;
d71ef5a4
KZ
191};
192
193static void gpt_deinit(struct fdisk_label *lb);
194
9ffeb235 195static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
d71ef5a4 196{
d71ef5a4
KZ
197 return (struct fdisk_gpt_label *) cxt->label;
198}
199
874aa9c3
KZ
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
c0d14b09 211/* prints UUID in the real byte order! */
88141067 212static void gpt_debug_uuid(const char *mesg, struct gpt_guid *guid)
c0d14b09
KZ
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}
c0d14b09 225
766d5156
DB
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);
5dbff4c0
KZ
235}
236
c0d14b09 237static int string_to_guid(const char *in, struct gpt_guid *guid)
766d5156 238{
4044d244 239 if (uuid_parse(in, (unsigned char *) guid)) { /* BE */
36cd4b3c 240 DBG(GPT, ul_debug("failed to parse GUID: %s", in));
4044d244
KZ
241 return -EINVAL;
242 }
c0d14b09 243 swap_efi_guid(guid); /* LE */
766d5156
DB
244 return 0;
245}
246
7f539277 247static char *guid_to_string(const struct gpt_guid *guid, char *out)
766d5156 248{
c0d14b09
KZ
249 struct gpt_guid u = *guid; /* LE */
250
251 swap_efi_guid(&u); /* BE */
252 uuid_unparse_upper((unsigned char *) &u, out);
253
46667ba4 254 return out;
766d5156
DB
255}
256
7f539277
KZ
257static struct fdisk_parttype *gpt_partition_parttype(
258 struct fdisk_context *cxt,
259 const struct gpt_entry *e)
260{
261 struct fdisk_parttype *t;
b443c177 262 char str[UUID_STR_LEN];
92e486f8 263 struct gpt_guid guid = e->type;
7f539277 264
92e486f8 265 guid_to_string(&guid, str);
a745611d 266 t = fdisk_label_get_parttype_from_string(cxt->label, str);
7f539277
KZ
267 return t ? : fdisk_new_unknown_parttype(0, str);
268}
269
b0a484a8
KZ
270static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
271{
272 e->type = *uuid;
36cd4b3c 273 DBG(GPT, gpt_debug_uuid("new type", uuid));
b0a484a8
KZ
274}
275
5be3df4a 276static int gpt_entry_set_name(struct gpt_entry *e, char *str)
b0a484a8 277{
5be3df4a
VD
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 }
b0a484a8
KZ
309 }
310
311 for (i = 0; i < GPT_PART_NAME_LEN; i++)
5be3df4a
VD
312 e->name[i] = cpu_to_le16(name[i]);
313
c1165241 314 return (int)((char *) in - str);
b0a484a8
KZ
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}
7f539277 329
02a376f2
KZ
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
7f539277 336
766d5156
DB
337static const char *gpt_get_header_revstr(struct gpt_header *header)
338{
339 if (!header)
340 goto unknown;
341
43a2b094 342 switch (le32_to_cpu(header->revision)) {
766d5156
DB
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
b28df75e
KZ
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
b683c081
KZ
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
aa1c7a76 381/* calculate size of entries array in bytes for specified number of entries */
b1bc5ae3
KZ
382static inline int gpt_calculate_sizeof_entries(
383 struct gpt_header *hdr,
384 uint32_t nents, size_t *sz)
9e320545 385{
b1bc5ae3
KZ
386 uint32_t esz = hdr ? le32_to_cpu(hdr->sizeof_partition_entry) :
387 sizeof(struct gpt_entry);
9e320545
KZ
388
389 if (nents == 0 || esz == 0 || SIZE_MAX/esz < nents) {
311e33af 390 DBG(GPT, ul_debug("entries array size check failed"));
9e320545
KZ
391 return -ERANGE;
392 }
393
2815af9e 394 *sz = (size_t) nents * esz;
9e320545
KZ
395 return 0;
396}
397
aa1c7a76 398/* calculate size of entries array in sectors for specified number of entries */
b1bc5ae3
KZ
399static inline int gpt_calculate_sectorsof_entries(
400 struct gpt_header *hdr,
401 uint32_t nents, uint64_t *sz,
402 struct fdisk_context *cxt)
9e320545 403{
d1187380 404 size_t esz = 0;
b1bc5ae3
KZ
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{
d1187380 419 uint64_t esects = 0;
b1bc5ae3
KZ
420 int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
421
ffac9652
KZ
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;
b1bc5ae3
KZ
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{
d1187380 437 uint64_t esects = 0;
b1bc5ae3
KZ
438 int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
439
ffac9652
KZ
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;
b1bc5ae3
KZ
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{
d1187380 455 uint64_t esects = 0;
b1bc5ae3
KZ
456 int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
457
458 if (rc == 0)
459 *sz = esects + 2ULL;
460 return rc;
9e320545
KZ
461}
462
b1bc5ae3
KZ
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}
766d5156 468
5989556a
KZ
469static char *gpt_get_header_id(struct gpt_header *header)
470{
b443c177 471 char str[UUID_STR_LEN];
92e486f8 472 struct gpt_guid guid = header->disk_guid;
5989556a 473
92e486f8 474 guid_to_string(&guid, str);
5989556a
KZ
475
476 return strdup(str);
477}
478
3f731001
DB
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;
7c2cfb18 486 int rc;
3f731001
DB
487
488 if (!cxt || !cxt->firstsector)
489 return -ENOSYS;
490
3457d90e
KZ
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);
7c2cfb18
KZ
495 if (rc)
496 return rc;
3f731001
DB
497
498 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
8ffa3b65 499 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
3f731001
DB
500
501 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
502 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
8ffa3b65
KZ
503 pmbr->partition_record[0].start_sector = 2;
504 pmbr->partition_record[0].end_head = 0xFF;
3f731001
DB
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 =
0a7cdf80 509 cpu_to_le32((uint32_t) min( cxt->total_sectors - 1ULL, 0xFFFFFFFFULL) );
3f731001
DB
510
511 return 0;
512}
513
b1bc5ae3 514
9a8a3b88 515/* Move backup header to the end of the device */
d1187380 516static int gpt_fix_alternative_lba(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
9a8a3b88
KZ
517{
518 struct gpt_header *p, *b;
387ac277 519 uint64_t x = 0, orig;
b1bc5ae3 520 size_t nents;
d1187380 521 int rc;
9a8a3b88
KZ
522
523 if (!cxt)
d1187380 524 return -EINVAL;
9a8a3b88
KZ
525
526 p = gpt->pheader; /* primary */
527 b = gpt->bheader; /* backup */
528
b1bc5ae3 529 nents = le32_to_cpu(p->npartition_entries);
387ac277 530 orig = le64_to_cpu(p->alternative_lba);
9a8a3b88
KZ
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 */
d1187380
KZ
540 rc = gpt_calculate_alternative_entries_lba(p, nents, &x, cxt);
541 if (rc)
542 goto failed;
543
b1bc5ae3 544 b->partition_entry_lba = cpu_to_le64(x);
9a8a3b88
KZ
545
546 /* update last usable LBA */
d1187380
KZ
547 rc = gpt_calculate_last_lba(p, nents, &x, cxt);
548 if (rc)
549 goto failed;
550
b1bc5ae3
KZ
551 p->last_usable_lba = cpu_to_le64(x);
552 b->last_usable_lba = cpu_to_le64(x);
9a8a3b88 553
387ac277
KZ
554 DBG(GPT, ul_debug("Alternative-LBA updated from %"PRIu64" to %"PRIu64,
555 orig, le64_to_cpu(p->alternative_lba)));
d1187380
KZ
556 return 0;
557failed:
558 DBG(GPT, ul_debug("failed to fix alternative-LBA [rc=%d]", rc));
559 return rc;
387ac277
KZ
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 */
d1187380 606static int gpt_minimize_alternative_lba(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
387ac277
KZ
607{
608 uint64_t total = gpt_calculate_minimal_size(cxt, gpt);
609 uint64_t orig = cxt->total_sectors;
d1187380 610 int rc;
387ac277
KZ
611
612 /* Let's temporary change size of the device to recalculate backup header */
613 cxt->total_sectors = total;
d1187380
KZ
614 rc = gpt_fix_alternative_lba(cxt, gpt);
615 if (rc)
616 return rc;
617
387ac277
KZ
618 cxt->total_sectors = orig;
619 fdisk_label_set_changed(cxt->label, 1);
d1187380 620 return 0;
9a8a3b88
KZ
621}
622
3f731001
DB
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
b1bc5ae3
KZ
632 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) {
633 /* primary */
0a7cdf80
KZ
634 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1ULL);
635 header->partition_entry_lba = cpu_to_le64(2ULL);
b1bc5ae3
KZ
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);
3f731001
DB
642
643 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
b1bc5ae3 644 header->partition_entry_lba = cpu_to_le64(x);
3f731001
DB
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
45ddb828
KZ
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
4bb82a45
KZ
688 assert(cxt->sector_size >= sizeof(struct gpt_header));
689
690 res = calloc(1, cxt->sector_size);
45ddb828
KZ
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)
0a7cdf80 711 res->partition_entry_lba = cpu_to_le64(2ULL);
45ddb828 712 else {
5eaeb585 713 uint64_t esz = (uint64_t) le32_to_cpu(src->npartition_entries) * sizeof(struct gpt_entry);
45ddb828
KZ
714 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
715
0a7cdf80 716 res->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1ULL - esects);
45ddb828
KZ
717 }
718
719 return res;
720}
721
b7c67e64
KZ
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
c6b3e988 738 rc = ul_parse_size(str, (uintmax_t *) num, &pwr);
b7c67e64
KZ
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,
b11e1b7e
KZ
747 uint64_t *first, uint64_t *last,
748 uint32_t *maxents)
1240f549 749{
b7c67e64 750 int rc = 0;
d1187380 751 uint64_t flba = 0, llba = 0;
fb64d932 752 uint64_t nents = GPT_NPARTITIONS;
b7c67e64 753
1240f549 754 assert(cxt);
b7c67e64
KZ
755 assert(first);
756 assert(last);
757
758 *first = *last = 0;
1240f549 759
fb64d932
SDR
760 /* Get the table length from the script, if given */
761 if (cxt->script) {
762 rc = get_script_u64(cxt, &nents, "table-length");
9f17b992
KZ
763 if (rc == 1)
764 nents = GPT_NPARTITIONS; /* undefined by script */
765 else if (rc < 0)
fb64d932
SDR
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 }
b11e1b7e
KZ
784 }
785
d1187380
KZ
786 if (rc)
787 return rc;
b11e1b7e
KZ
788 if (maxents)
789 *maxents = nents;
1240f549 790
b7c67e64
KZ
791 /* script default */
792 if (cxt->script) {
793 rc = get_script_u64(cxt, first, "first-lba");
794 if (rc < 0)
795 return rc;
796
36cd4b3c 797 DBG(GPT, ul_debug("FirstLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
fdbd7bb9 798 *first, flba, (uintmax_t)cxt->first_lba));
b7c67e64
KZ
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
36cd4b3c 809 DBG(GPT, ul_debug("LastLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
fdbd7bb9 810 *last, llba, (uintmax_t)cxt->last_lba));
b7c67e64
KZ
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;
1240f549
KZ
826}
827
3f731001
DB
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{
1240f549 839 uint64_t first, last;
b11e1b7e 840 uint32_t nents = 0;
b7c67e64 841 int has_id = 0, rc;
3f731001
DB
842
843 if (!cxt || !header)
844 return -ENOSYS;
845
3f731001
DB
846 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
847 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
4bb82a45
KZ
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
9e930041 851 * to accept it, so use the header without the zeroed area.
4bb82a45
KZ
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));
3f731001 856
b11e1b7e
KZ
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);
b7c67e64
KZ
860 if (rc)
861 return rc;
862
b11e1b7e
KZ
863 header->npartition_entries = cpu_to_le32(nents);
864 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
865
b4184690
KZ
866 header->first_usable_lba = cpu_to_le64(first);
867 header->last_usable_lba = cpu_to_le64(last);
3f731001
DB
868
869 gpt_mknew_header_common(cxt, header, lba);
3f731001 870
4b43f7c9
KZ
871 if (cxt->script) {
872 const char *id = fdisk_script_get_header(cxt->script, "label-id");
92e486f8
RM
873 struct gpt_guid guid = header->disk_guid;
874 if (id && string_to_guid(id, &guid) == 0)
4b43f7c9 875 has_id = 1;
92e486f8 876 header->disk_guid = guid;
4b43f7c9
KZ
877 }
878
879 if (!has_id) {
92e486f8
RM
880 struct gpt_guid guid;
881
dd405ea7 882 uuid_generate_random((unsigned char *) &guid);
92e486f8 883 swap_efi_guid(&guid);
dd405ea7 884 header->disk_guid = guid;
4b43f7c9 885 }
3f731001
DB
886 return 0;
887}
888
766d5156
DB
889/*
890 * Checks if there is a valid protective MBR partition table.
891 * Returns 0 if it is invalid or failure. Otherwise, return
9e930041 892 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depending on the detection.
766d5156
DB
893 */
894static int valid_pmbr(struct fdisk_context *cxt)
895{
879fadf1 896 int i, part = 0, ret = 0; /* invalid by default */
766d5156
DB
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
f67c524e 904 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
766d5156
DB
905 goto done;
906
766d5156 907 /* seems like a valid MBR was found, check DOS primary partitions */
f67c524e 908 for (i = 0; i < 4; i++) {
766d5156
DB
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 */
879fadf1 915 part = i;
766d5156 916 ret = GPT_MBR_PROTECTIVE;
c6bf5c09 917 break;
766d5156 918 }
f67c524e 919 }
ac920fed 920
766d5156
DB
921 if (ret != GPT_MBR_PROTECTIVE)
922 goto done;
c6bf5c09 923
c6bf5c09 924
f67c524e 925 for (i = 0 ; i < 4; i++) {
766d5156 926 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
1d844703 927 (pmbr->partition_record[i].os_type != 0x00)) {
766d5156 928 ret = GPT_MBR_HYBRID;
1d844703
KZ
929 goto done;
930 }
f67c524e 931 }
766d5156 932
1d844703
KZ
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
766d5156
DB
938 /*
939 * Protective MBRs take up the lesser of the whole disk
940 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
1fd10841
DB
941 * Some partitioning programs, nonetheless, choose to set
942 * the size to the maximum 32-bit limitation, disregarding
943 * the disk size.
766d5156
DB
944 *
945 * Hybrid MBRs do not necessarily comply with this.
59db52ad
KZ
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.
766d5156 949 */
f67c524e 950 if (ret == GPT_MBR_PROTECTIVE) {
0a7cdf80
KZ
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) {
9a8a3b88 953
0a7cdf80 954 fdisk_warnx(cxt, _("GPT PMBR size mismatch (%"PRIu64" != %"PRIu64") "
9a8a3b88 955 "will be corrected by write."),
fbae1442 956 sz_lba, cxt->total_sectors - (uint64_t) 1);
9a8a3b88 957
2bb3aa36 958 /* Note that gpt_write_pmbr() overwrites PMBR, but we want to keep it valid already
9a8a3b88
KZ
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) );
1572fb3e 962 fdisk_label_set_changed(cxt->label, 1);
59db52ad 963 }
f67c524e 964 }
766d5156 965done:
36cd4b3c 966 DBG(GPT, ul_debug("PMBR type: %s",
1d844703
KZ
967 ret == GPT_MBR_PROTECTIVE ? "protective" :
968 ret == GPT_MBR_HYBRID ? "hybrid" : "???" ));
766d5156
DB
969 return ret;
970}
971
972static uint64_t last_lba(struct fdisk_context *cxt)
5dbff4c0 973{
5dbff4c0 974 struct stat s;
cbebd20d 975 uint64_t sectors = 0;
5dbff4c0 976
766d5156
DB
977 memset(&s, 0, sizeof(s));
978 if (fstat(cxt->dev_fd, &s) == -1) {
83df5feb 979 fdisk_warn(cxt, _("gpt: stat() failed"));
5dbff4c0
KZ
980 return 0;
981 }
766d5156 982
5dbff4c0 983 if (S_ISBLK(s.st_mode))
0a7cdf80 984 sectors = cxt->total_sectors - 1ULL;
cbebd20d
KZ
985 else if (S_ISREG(s.st_mode))
986 sectors = ((uint64_t) s.st_size /
987 (uint64_t) cxt->sector_size) - 1ULL;
988 else
83df5feb 989 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
cbebd20d 990
36cd4b3c 991 DBG(GPT, ul_debug("last LBA: %"PRIu64"", sectors));
cbebd20d 992 return sectors;
5dbff4c0
KZ
993}
994
766d5156
DB
995static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
996 void *buffer, const size_t bytes)
5dbff4c0 997{
766d5156 998 off_t offset = lba * cxt->sector_size;
5dbff4c0 999
bbe8e6a9
KZ
1000 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
1001 return -1;
b9710f1f 1002 return (size_t)read(cxt->dev_fd, buffer, bytes) != bytes;
5dbff4c0
KZ
1003}
1004
766d5156
DB
1005
1006/* Returns the GPT entry array */
b28df75e 1007static unsigned char *gpt_read_entries(struct fdisk_context *cxt,
d71ef5a4 1008 struct gpt_header *header)
5dbff4c0 1009{
b9144a43 1010 size_t sz = 0;
9e320545
KZ
1011 ssize_t ssz;
1012
b28df75e 1013 unsigned char *ret = NULL;
d71ef5a4
KZ
1014 off_t offset;
1015
1016 assert(cxt);
1017 assert(header);
1018
b1bc5ae3 1019 if (gpt_sizeof_entries(header, &sz))
f71b96bf 1020 return NULL;
f71b96bf 1021
46667ba4 1022 ret = calloc(1, sz);
d71ef5a4
KZ
1023 if (!ret)
1024 return NULL;
9e320545 1025
5eaeb585 1026 offset = (off_t) le64_to_cpu(header->partition_entry_lba) *
766d5156
DB
1027 cxt->sector_size;
1028
1029 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
d71ef5a4 1030 goto fail;
9e320545
KZ
1031
1032 ssz = read(cxt->dev_fd, ret, sz);
1033 if (ssz < 0 || (size_t) ssz != sz)
d71ef5a4 1034 goto fail;
766d5156
DB
1035
1036 return ret;
d71ef5a4
KZ
1037
1038fail:
1039 free(ret);
1040 return NULL;
766d5156
DB
1041}
1042
7020de0b
KZ
1043static inline uint32_t count_crc32(const unsigned char *buf, size_t len,
1044 size_t ex_off, size_t ex_len)
766d5156 1045{
977dd748 1046 return (ul_crc32_exclude_offset(~0L, buf, len, ex_off, ex_len, 0) ^ ~0L);
766d5156
DB
1047}
1048
7020de0b
KZ
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
b28df75e 1057static inline uint32_t gpt_entryarr_count_crc32(struct gpt_header *header, unsigned char *ents)
7020de0b
KZ
1058{
1059 size_t arysz = 0;
1060
b1bc5ae3 1061 if (gpt_sizeof_entries(header, &arysz))
9e320545 1062 return 0;
7020de0b 1063
b28df75e 1064 return count_crc32(ents, arysz, 0, 0);
7020de0b
KZ
1065}
1066
1067
766d5156
DB
1068/*
1069 * Recompute header and partition array 32bit CRC checksums.
1070 * This function does not fail - if there's corruption, then it
9e930041 1071 * will be reported when checksumming it again (ie: probing or verify).
766d5156 1072 */
b28df75e 1073static void gpt_recompute_crc(struct gpt_header *header, unsigned char *ents)
766d5156 1074{
766d5156
DB
1075 if (!header)
1076 return;
1077
7020de0b
KZ
1078 header->partition_entry_array_crc32 =
1079 cpu_to_le32( gpt_entryarr_count_crc32(header, ents) );
766d5156 1080
7020de0b 1081 header->crc32 = cpu_to_le32( gpt_header_count_crc32(header) );
766d5156
DB
1082}
1083
1084/*
1085 * Compute the 32bit CRC checksum of the partition table header.
1086 * Returns 1 if it is valid, otherwise 0.
1087 */
b28df75e 1088static int gpt_check_header_crc(struct gpt_header *header, unsigned char *ents)
766d5156 1089{
7020de0b
KZ
1090 uint32_t orgcrc = le32_to_cpu(header->crc32),
1091 crc = gpt_header_count_crc32(header);
766d5156 1092
7020de0b 1093 if (crc == orgcrc)
d71ef5a4
KZ
1094 return 1;
1095
766d5156 1096 /*
7020de0b
KZ
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.
766d5156 1100 */
d71ef5a4 1101 if (ents) {
766d5156 1102 gpt_recompute_crc(header, ents);
7020de0b 1103 return gpt_header_count_crc32(header) == orgcrc;
d71ef5a4
KZ
1104 }
1105
1106 return 0;
766d5156
DB
1107}
1108
1109/*
1110 * It initializes the partition entry array.
1111 * Returns 1 if the checksum is valid, otherwise 0.
1112 */
b28df75e 1113static int gpt_check_entryarr_crc(struct gpt_header *header, unsigned char *ents)
766d5156 1114{
d71ef5a4 1115 if (!header || !ents)
7020de0b 1116 return 0;
766d5156 1117
7020de0b
KZ
1118 return gpt_entryarr_count_crc32(header, ents) ==
1119 le32_to_cpu(header->partition_entry_array_crc32);
766d5156
DB
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) {
36cd4b3c 1132 DBG(GPT, ul_debug("error: header last LBA is before first LBA"));
766d5156 1133 goto done;
5dbff4c0 1134 }
766d5156
DB
1135
1136 /* check if first and last usable LBAs with the disk's last LBA */
1137 if (fu > lastlba || lu > lastlba) {
75cd5e2f
KZ
1138 DBG(GPT, ul_debug("error: header LBAs are after the disk's last LBA (%ju..%ju)",
1139 (uintmax_t) fu, (uintmax_t) lu));
766d5156
DB
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) {
36cd4b3c 1146 DBG(GPT, ul_debug("error: header outside of usable range"));
766d5156
DB
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 */
d71ef5a4
KZ
1166static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
1167 uint64_t lba,
b28df75e 1168 unsigned char **_ents)
766d5156
DB
1169{
1170 struct gpt_header *header = NULL;
b28df75e 1171 unsigned char *ents = NULL;
e9bf0935 1172 uint32_t hsz;
766d5156
DB
1173
1174 if (!cxt)
1175 return NULL;
1176
4bb82a45
KZ
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);
46667ba4
KZ
1182 if (!header)
1183 return NULL;
766d5156 1184
d71ef5a4 1185 /* read and verify header */
4bb82a45 1186 if (read_lba(cxt, lba, header, cxt->sector_size) != 0)
766d5156
DB
1187 goto invalid;
1188
1189 if (!gpt_check_signature(header))
1190 goto invalid;
1191
9c6f3de6
KZ
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
d71ef5a4
KZ
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))
766d5156
DB
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
d71ef5a4
KZ
1215 if (_ents)
1216 *_ents = ents;
1217 else
1218 free(ents);
1219
36cd4b3c 1220 DBG(GPT, ul_debug("found valid header on LBA %"PRIu64"", lba));
766d5156
DB
1221 return header;
1222invalid:
1223 free(header);
d71ef5a4 1224 free(ents);
45ddb828 1225
36cd4b3c 1226 DBG(GPT, ul_debug("read header on LBA %"PRIu64" failed", lba));
766d5156
DB
1227 return NULL;
1228}
1229
775001ad
KZ
1230
1231static int gpt_locate_disklabel(struct fdisk_context *cxt, int n,
9bbcf43f 1232 const char **name, uint64_t *offset, size_t *size)
775001ad
KZ
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");
9bbcf43f 1250 *offset = (uint64_t) GPT_PRIMARY_PARTITION_TABLE_LBA * cxt->sector_size;
775001ad
KZ
1251 *size = sizeof(struct gpt_header);
1252 break;
1253 case 2:
1254 *name = _("GPT Entries");
1255 gpt = self_label(cxt);
5eaeb585
KZ
1256 *offset = (uint64_t) le64_to_cpu(gpt->pheader->partition_entry_lba) *
1257 cxt->sector_size;
b1bc5ae3 1258 return gpt_sizeof_entries(gpt->pheader, size);
93737ad3
KZ
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;
775001ad
KZ
1271 default:
1272 return 1; /* no more chunks */
1273 }
1274
1275 return 0;
1276}
1277
5989556a
KZ
1278static int gpt_get_disklabel_item(struct fdisk_context *cxt, struct fdisk_labelitem *item)
1279{
1280 struct gpt_header *h;
1281 int rc = 0;
b9d930d6 1282 uint64_t x = 0;
5989556a
KZ
1283
1284 assert(cxt);
1285 assert(cxt->label);
1286 assert(fdisk_is_label(cxt, GPT));
1287
1288 h = self_label(cxt)->pheader;
775001ad 1289
5989556a
KZ
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:
3afbdb58 1299 item->name = _("First usable LBA");
5989556a
KZ
1300 item->type = 'j';
1301 item->data.num64 = le64_to_cpu(h->first_usable_lba);
1302 break;
1303 case GPT_LABELITEM_LASTLBA:
3afbdb58 1304 item->name = _("Last usable LBA");
5989556a
KZ
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. */
b9d930d6 1316 item->name = _("Partition entries starting LBA");
5989556a
KZ
1317 item->type = 'j';
1318 item->data.num64 = le64_to_cpu(h->partition_entry_lba);
1319 break;
b9d930d6
KZ
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;
5989556a
KZ
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)
9e930041 1335 rc = 1; /* unsupported generic item */
5989556a
KZ
1336 else
1337 rc = 2; /* out of range */
1338 break;
1339 }
1340
1341 return rc;
1342}
775001ad 1343
766d5156
DB
1344/*
1345 * Returns the number of partitions that are in use.
1346 */
b683c081 1347static size_t partitions_in_use(struct fdisk_gpt_label *gpt)
766d5156 1348{
b683c081 1349 size_t i, used = 0;
766d5156 1350
b28df75e
KZ
1351 assert(gpt);
1352 assert(gpt->pheader);
1353 assert(gpt->ents);
1354
b683c081 1355 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e 1356 struct gpt_entry *e = gpt_get_entry(gpt, i);
766d5156 1357
02a376f2 1358 if (gpt_entry_is_used(e))
766d5156 1359 used++;
b28df75e 1360 }
766d5156
DB
1361 return used;
1362}
1363
766d5156
DB
1364
1365/*
1366 * Check if a partition is too big for the disk (sectors).
1367 * Returns the faulting partition number, otherwise 0.
1368 */
b28df75e 1369static uint32_t check_too_big_partitions(struct fdisk_gpt_label *gpt, uint64_t sectors)
766d5156 1370{
b683c081 1371 size_t i;
766d5156 1372
b28df75e
KZ
1373 assert(gpt);
1374 assert(gpt->pheader);
1375 assert(gpt->ents);
1376
b683c081 1377 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e
KZ
1378 struct gpt_entry *e = gpt_get_entry(gpt, i);
1379
02a376f2 1380 if (!gpt_entry_is_used(e))
766d5156 1381 continue;
b28df75e 1382 if (gpt_partition_end(e) >= sectors)
766d5156 1383 return i + 1;
5dbff4c0 1384 }
766d5156
DB
1385
1386 return 0;
5dbff4c0
KZ
1387}
1388
766d5156
DB
1389/*
1390 * Check if a partition ends before it begins
1391 * Returns the faulting partition number, otherwise 0.
5dbff4c0 1392 */
b28df75e 1393static uint32_t check_start_after_end_partitions(struct fdisk_gpt_label *gpt)
5dbff4c0 1394{
b683c081 1395 size_t i;
5dbff4c0 1396
b28df75e
KZ
1397 assert(gpt);
1398 assert(gpt->pheader);
1399 assert(gpt->ents);
1400
b683c081 1401 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e
KZ
1402 struct gpt_entry *e = gpt_get_entry(gpt, i);
1403
02a376f2 1404 if (!gpt_entry_is_used(e))
766d5156 1405 continue;
b28df75e 1406 if (gpt_partition_start(e) > gpt_partition_end(e))
766d5156 1407 return i + 1;
5dbff4c0 1408 }
766d5156
DB
1409
1410 return 0;
5dbff4c0
KZ
1411}
1412
766d5156 1413/*
09af3db4 1414 * Check if partition e1 overlaps with partition e2.
766d5156 1415 */
874aa9c3 1416static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
5dbff4c0 1417{
874aa9c3
KZ
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));
766d5156
DB
1424}
1425
1426/*
09af3db4 1427 * Find any partitions that overlap.
766d5156 1428 */
b28df75e 1429static uint32_t check_overlap_partitions(struct fdisk_gpt_label *gpt)
766d5156 1430{
b683c081 1431 size_t i, j;
766d5156 1432
b28df75e
KZ
1433 assert(gpt);
1434 assert(gpt->pheader);
1435 assert(gpt->ents);
1436
b683c081 1437 for (i = 0; i < gpt_get_nentries(gpt); i++)
766d5156 1438 for (j = 0; j < i; j++) {
b28df75e
KZ
1439 struct gpt_entry *ei = gpt_get_entry(gpt, i);
1440 struct gpt_entry *ej = gpt_get_entry(gpt, j);
1441
02a376f2 1442 if (!gpt_entry_is_used(ei) || !gpt_entry_is_used(ej))
766d5156 1443 continue;
b28df75e 1444 if (partition_overlap(ei, ej)) {
36cd4b3c 1445 DBG(GPT, ul_debug("partitions overlap detected [%zu vs. %zu]", i, j));
766d5156 1446 return i + 1;
c15aec86 1447 }
766d5156
DB
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 */
b28df75e 1457static uint64_t find_first_available(struct fdisk_gpt_label *gpt, uint64_t start)
766d5156 1458{
b683c081 1459 int first_moved = 0;
766d5156 1460 uint64_t first;
602ebe7d
KZ
1461 uint64_t fu, lu;
1462
b28df75e
KZ
1463 assert(gpt);
1464 assert(gpt->pheader);
1465 assert(gpt->ents);
766d5156 1466
b28df75e
KZ
1467 fu = le64_to_cpu(gpt->pheader->first_usable_lba);
1468 lu = le64_to_cpu(gpt->pheader->last_usable_lba);
602ebe7d 1469
766d5156
DB
1470 /*
1471 * Begin from the specified starting point or from the first usable
1472 * LBA, whichever is greater...
1473 */
602ebe7d 1474 first = start < fu ? fu : start;
766d5156
DB
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 {
b683c081
KZ
1484 size_t i;
1485
766d5156 1486 first_moved = 0;
b683c081 1487 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e
KZ
1488 struct gpt_entry *e = gpt_get_entry(gpt, i);
1489
02a376f2 1490 if (!gpt_entry_is_used(e))
766d5156 1491 continue;
b28df75e 1492 if (first < gpt_partition_start(e))
766d5156 1493 continue;
b28df75e
KZ
1494 if (first <= gpt_partition_end(e)) {
1495 first = gpt_partition_end(e) + 1;
766d5156
DB
1496 first_moved = 1;
1497 }
1498 }
1499 } while (first_moved == 1);
1500
602ebe7d 1501 if (first > lu)
766d5156
DB
1502 first = 0;
1503
1504 return first;
5dbff4c0
KZ
1505}
1506
766d5156
DB
1507
1508/* Returns last available sector in the free space pointed to by start. From gdisk. */
b28df75e 1509static uint64_t find_last_free(struct fdisk_gpt_label *gpt, uint64_t start)
5dbff4c0 1510{
b683c081 1511 size_t i;
766d5156
DB
1512 uint64_t nearest_start;
1513
b28df75e
KZ
1514 assert(gpt);
1515 assert(gpt->pheader);
1516 assert(gpt->ents);
766d5156 1517
b28df75e 1518 nearest_start = le64_to_cpu(gpt->pheader->last_usable_lba);
602ebe7d 1519
b683c081 1520 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e
KZ
1521 struct gpt_entry *e = gpt_get_entry(gpt, i);
1522 uint64_t ps = gpt_partition_start(e);
602ebe7d
KZ
1523
1524 if (nearest_start > ps && ps > start)
0a7cdf80 1525 nearest_start = ps - 1ULL;
5dbff4c0 1526 }
766d5156
DB
1527
1528 return nearest_start;
5dbff4c0 1529}
766d5156
DB
1530
1531/* Returns the last free sector on the disk. From gdisk. */
b28df75e 1532static uint64_t find_last_free_sector(struct fdisk_gpt_label *gpt)
766d5156 1533{
b683c081 1534 int last_moved;
766d5156
DB
1535 uint64_t last = 0;
1536
b28df75e
KZ
1537 assert(gpt);
1538 assert(gpt->pheader);
1539 assert(gpt->ents);
766d5156
DB
1540
1541 /* start by assuming the last usable LBA is available */
b28df75e 1542 last = le64_to_cpu(gpt->pheader->last_usable_lba);
766d5156 1543 do {
b683c081
KZ
1544 size_t i;
1545
766d5156 1546 last_moved = 0;
b683c081 1547 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e
KZ
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;
766d5156
DB
1553 last_moved = 1;
1554 }
1555 }
1556 } while (last_moved == 1);
b28df75e 1557
766d5156
DB
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 */
b28df75e 1566static uint64_t find_first_in_largest(struct fdisk_gpt_label *gpt)
766d5156
DB
1567{
1568 uint64_t start = 0, first_sect, last_sect;
1569 uint64_t segment_size, selected_size = 0, selected_segment = 0;
1570
b28df75e
KZ
1571 assert(gpt);
1572 assert(gpt->pheader);
1573 assert(gpt->ents);
766d5156
DB
1574
1575 do {
b28df75e 1576 first_sect = find_first_available(gpt, start);
766d5156 1577 if (first_sect != 0) {
b28df75e 1578 last_sect = find_last_free(gpt, first_sect);
0a7cdf80 1579 segment_size = last_sect - first_sect + 1ULL;
766d5156
DB
1580
1581 if (segment_size > selected_size) {
1582 selected_size = segment_size;
1583 selected_segment = first_sect;
1584 }
0a7cdf80 1585 start = last_sect + 1ULL;
766d5156
DB
1586 }
1587 } while (first_sect != 0);
1588
766d5156
DB
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 */
b28df75e
KZ
1596static uint64_t get_free_sectors(struct fdisk_context *cxt,
1597 struct fdisk_gpt_label *gpt,
1598 uint32_t *nsegments,
766d5156
DB
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
b28df75e
KZ
1609 assert(gpt);
1610 assert(gpt->pheader);
1611 assert(gpt->ents);
1612
766d5156 1613 do {
b28df75e 1614 first_sect = find_first_available(gpt, start);
766d5156 1615 if (first_sect) {
b28df75e 1616 last_sect = find_last_free(gpt, first_sect);
766d5156
DB
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++;
0a7cdf80 1623 start = last_sect + 1ULL;
766d5156
DB
1624 }
1625 } while (first_sect);
1626
1627done:
512a430f
KZ
1628 if (nsegments)
1629 *nsegments = num;
1630 if (largest_segment)
1631 *largest_segment = largest_seg;
766d5156
DB
1632
1633 return totfound;
1634}
1635
9ffeb235 1636static int gpt_probe_label(struct fdisk_context *cxt)
766d5156
DB
1637{
1638 int mbr_type;
9ffeb235 1639 struct fdisk_gpt_label *gpt;
766d5156 1640
9ffeb235
KZ
1641 assert(cxt);
1642 assert(cxt->label);
aa36c2cf 1643 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1644
1645 gpt = self_label(cxt);
766d5156 1646
d2d9efa1
KZ
1647 /* TODO: it would be nice to support scenario when GPT headers are OK,
1648 * but PMBR is corrupt */
766d5156
DB
1649 mbr_type = valid_pmbr(cxt);
1650 if (!mbr_type)
1651 goto failed;
1652
d71ef5a4
KZ
1653 /* primary header */
1654 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1655 &gpt->ents);
45ddb828
KZ
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);
766d5156 1665
d2d9efa1 1666 if (!gpt->pheader && !gpt->bheader)
766d5156
DB
1667 goto failed;
1668
d2d9efa1
KZ
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."));
45ddb828
KZ
1673 gpt->bheader = gpt_copy_header(cxt, gpt->pheader);
1674 if (!gpt->bheader)
d2d9efa1 1675 goto failed;
d2d9efa1 1676 gpt_recompute_crc(gpt->bheader, gpt->ents);
9a8a3b88 1677 fdisk_label_set_changed(cxt->label, 1);
d2d9efa1
KZ
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."));
45ddb828
KZ
1683 gpt->pheader = gpt_copy_header(cxt, gpt->bheader);
1684 if (!gpt->pheader)
d2d9efa1 1685 goto failed;
d2d9efa1 1686 gpt_recompute_crc(gpt->pheader, gpt->ents);
9a8a3b88
KZ
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. */
387ac277
KZ
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)) {
9a8a3b88 1695
387ac277
KZ
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
d1187380
KZ
1703 if (gpt_fix_alternative_lba(cxt, gpt) != 0)
1704 fdisk_warnx(cxt, _("Failed to recalculate backup GPT table location"));
387ac277
KZ
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 }
d2d9efa1 1709 }
d71ef5a4 1710
387ac277
KZ
1711 if (gpt->minimize && gpt_possible_minimize(cxt, gpt))
1712 fdisk_label_set_changed(cxt->label, 1);
1713
b683c081 1714 cxt->label->nparts_max = gpt_get_nentries(gpt);
b28df75e 1715 cxt->label->nparts_cur = partitions_in_use(gpt);
766d5156
DB
1716 return 1;
1717failed:
36cd4b3c 1718 DBG(GPT, ul_debug("probe failed"));
9ffeb235 1719 gpt_deinit(cxt->label);
766d5156
DB
1720 return 0;
1721}
1722
766d5156
DB
1723static char *encode_to_utf8(unsigned char *src, size_t count)
1724{
487b57f5
KZ
1725 unsigned char *dest;
1726 size_t len = (count * 3 / 2) + 1;
3f731001 1727
487b57f5 1728 dest = calloc(1, len);
d06f321d
KZ
1729 if (!dest)
1730 return NULL;
766d5156 1731
ce8985cc 1732 ul_encode_to_utf8(UL_ENCODE_UTF16LE, dest, len, src, count);
487b57f5 1733 return (char *) dest;
766d5156
DB
1734}
1735
01086b80 1736static int gpt_entry_attrs_to_string(struct gpt_entry *e, char **res)
c83f772e 1737{
01086b80
KZ
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;
159652d9 1747 attrs = e->attrs;
01086b80
KZ
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));
c83f772e 1759 if (!*res)
01086b80
KZ
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)) {
d8ed9e03 1768 if (p != *res)
01086b80
KZ
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)) {
d8ed9e03 1774 if (p != *res)
01086b80
KZ
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++) {
c83f772e 1782
01086b80 1783 if (!isset(bits, n))
c83f772e 1784 continue;
01086b80 1785 if (!count) {
d8ed9e03 1786 if (p != *res)
01086b80
KZ
1787 *p++ = ' ';
1788 p += sprintf(p, "GUID:%u", n);
1789 } else
1790 p += sprintf(p, ",%u", n);
c83f772e 1791 count++;
c83f772e
KZ
1792 }
1793
01086b80 1794 return 0;
c83f772e
KZ
1795}
1796
c77ba531
KZ
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
36cd4b3c 1809 DBG(GPT, ul_debug("parsing string attributes '%s'", p));
c77ba531
KZ
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
36cd4b3c 1820 DBG(GPT, ul_debug(" item '%s'", p));
c77ba531 1821
17d0902c 1822 if (strncmp(p, GPT_ATTRSTR_REQ,
c77ba531
KZ
1823 sizeof(GPT_ATTRSTR_REQ) - 1) == 0) {
1824 bit = GPT_ATTRBIT_REQ;
1825 p += sizeof(GPT_ATTRSTR_REQ) - 1;
d1b7bfe5
SR
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;
c77ba531
KZ
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;
17d0902c
KZ
1838
1839 /* GUID:<bit> as well as <bit> */
bae57b5a 1840 } else if (isdigit((unsigned char) *p)
17d0902c 1841 || (strncmp(p, "GUID:", 5) == 0
bae57b5a 1842 && isdigit((unsigned char) *(p + 5)))) {
c77ba531
KZ
1843 char *end = NULL;
1844
17d0902c
KZ
1845 if (*p == 'G')
1846 p += 5;
1847
c77ba531
KZ
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) {
54fefa07 1859 fdisk_warnx(cxt, _("unsupported GPT attribute bit '%s'"), p);
c77ba531
KZ
1860 return -EINVAL;
1861 }
1862
17d0902c
KZ
1863 if (*p && *p != ',' && !isblank(*p)) {
1864 fdisk_warnx(cxt, _("failed to parse GPT attribute string '%s'"), str);
1865 return -EINVAL;
1866 }
1867
c77ba531
KZ
1868 setbit(bits, bit);
1869
1870 while (isblank(*p)) p++;
1871 if (*p == ',')
1872 p++;
1873 }
1874
159652d9 1875 e->attrs = attrs;
c77ba531
KZ
1876 return 0;
1877}
1878
8c0a7f91
KZ
1879static int gpt_get_partition(struct fdisk_context *cxt, size_t n,
1880 struct fdisk_partition *pa)
766d5156 1881{
9ffeb235 1882 struct fdisk_gpt_label *gpt;
6941952e 1883 struct gpt_entry *e;
b443c177 1884 char u_str[UUID_STR_LEN];
01086b80 1885 int rc = 0;
92e486f8 1886 struct gpt_guid guid;
9ffeb235
KZ
1887
1888 assert(cxt);
1889 assert(cxt->label);
aa36c2cf 1890 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1891
1892 gpt = self_label(cxt);
766d5156 1893
b683c081 1894 if (n >= gpt_get_nentries(gpt))
6941952e 1895 return -EINVAL;
3c5fb475 1896
6941952e 1897 gpt = self_label(cxt);
b28df75e 1898 e = gpt_get_entry(gpt, n);
b1920e0b 1899
02a376f2 1900 pa->used = gpt_entry_is_used(e) || gpt_partition_start(e);
8c0a7f91
KZ
1901 if (!pa->used)
1902 return 0;
766d5156 1903
8c0a7f91 1904 pa->start = gpt_partition_start(e);
77d6a70a 1905 pa->size = gpt_partition_size(e);
7f539277 1906 pa->type = gpt_partition_parttype(cxt, e);
766d5156 1907
92e486f8
RM
1908 guid = e->partition_guid;
1909 if (guid_to_string(&guid, u_str)) {
8c0a7f91 1910 pa->uuid = strdup(u_str);
01086b80
KZ
1911 if (!pa->uuid) {
1912 rc = -errno;
1913 goto done;
1914 }
8c0a7f91
KZ
1915 } else
1916 pa->uuid = NULL;
1917
01086b80
KZ
1918 rc = gpt_entry_attrs_to_string(e, &pa->attrs);
1919 if (rc)
1920 goto done;
b1920e0b 1921
8c0a7f91 1922 pa->name = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
8c0a7f91 1923 return 0;
01086b80 1924done:
8c0a7f91 1925 fdisk_reset_partition(pa);
01086b80 1926 return rc;
6941952e 1927}
766d5156 1928
9348ef25 1929
b0a484a8
KZ
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;
9146a008 1936 uint64_t start, end;
b0a484a8
KZ
1937
1938 assert(cxt);
1939 assert(cxt->label);
1940 assert(fdisk_is_label(cxt, GPT));
1941
1942 gpt = self_label(cxt);
1943
b683c081 1944 if (n >= gpt_get_nentries(gpt))
b0a484a8
KZ
1945 return -EINVAL;
1946
9146a008
KZ
1947 FDISK_INIT_UNDEF(start);
1948 FDISK_INIT_UNDEF(end);
1949
b0a484a8 1950 gpt = self_label(cxt);
b28df75e 1951 e = gpt_get_entry(gpt, n);
b0a484a8
KZ
1952
1953 if (pa->uuid) {
b443c177 1954 char new_u[UUID_STR_LEN], old_u[UUID_STR_LEN];
92e486f8 1955 struct gpt_guid guid;
6936c081 1956
92e486f8
RM
1957 guid = e->partition_guid;
1958 guid_to_string(&guid, old_u);
b0a484a8
KZ
1959 rc = gpt_entry_set_uuid(e, pa->uuid);
1960 if (rc)
1961 return rc;
92e486f8
RM
1962 guid = e->partition_guid;
1963 guid_to_string(&guid, new_u);
0477369a 1964 fdisk_info(cxt, _("Partition UUID changed from %s to %s."),
6936c081 1965 old_u, new_u);
b0a484a8
KZ
1966 }
1967
6936c081 1968 if (pa->name) {
c1165241 1969 int len;
6936c081 1970 char *old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
c1165241
VD
1971 len = gpt_entry_set_name(e, pa->name);
1972 if (len < 0)
760942e2 1973 fdisk_warn(cxt, _("Failed to translate partition name, name not changed."));
c1165241
VD
1974 else
1975 fdisk_info(cxt, _("Partition name changed from '%s' to '%.*s'."),
1976 old, len, pa->name);
6936c081
KZ
1977 free(old);
1978 }
1979
b0a484a8
KZ
1980 if (pa->type && pa->type->typestr) {
1981 struct gpt_guid typeid;
1982
a48c0985
KZ
1983 rc = string_to_guid(pa->type->typestr, &typeid);
1984 if (rc)
1985 return rc;
b0a484a8
KZ
1986 gpt_entry_set_type(e, &typeid);
1987 }
c77ba531
KZ
1988 if (pa->attrs) {
1989 rc = gpt_entry_attrs_from_string(cxt, e, pa->attrs);
1990 if (rc)
1991 return rc;
1992 }
b0a484a8 1993
ecf40cda 1994 if (fdisk_partition_has_start(pa))
9146a008 1995 start = pa->start;
76785052
KZ
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 }
9146a008 2001
c949fa98
KZ
2002 if (!FDISK_IS_UNDEF(start)) {
2003 if (start < le64_to_cpu(gpt->pheader->first_usable_lba)) {
614ddddf 2004 fdisk_warnx(cxt, _("The start of the partition understeps FirstUsableLBA."));
c949fa98
KZ
2005 return -EINVAL;
2006 }
9146a008 2007 e->lba_start = cpu_to_le64(start);
c949fa98
KZ
2008 }
2009 if (!FDISK_IS_UNDEF(end)) {
2010 if (end > le64_to_cpu(gpt->pheader->last_usable_lba)) {
614ddddf 2011 fdisk_warnx(cxt, _("The end of the partition oversteps LastUsableLBA."));
c949fa98
KZ
2012 return -EINVAL;
2013 }
9146a008 2014 e->lba_end = cpu_to_le64(end);
c949fa98 2015 }
b0a484a8
KZ
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
17b4496a
PR
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
afb27a8e
KZ
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;
b0a484a8 2040
afb27a8e
KZ
2041 if (write_all(cxt->dev_fd, buf, count))
2042 return -errno;
2043
c2ec04d3
KZ
2044 if (fsync(cxt->dev_fd) != 0)
2045 return -errno;
afb27a8e 2046
36cd4b3c 2047 DBG(GPT, ul_debug(" write OK [offset=%zu, size=%zu]",
afb27a8e
KZ
2048 (size_t) offset, count));
2049 return 0;
2050}
766d5156
DB
2051
2052/*
2053 * Write partitions.
2054 * Returns 0 on success, or corresponding error otherwise.
2055 */
2056static int gpt_write_partitions(struct fdisk_context *cxt,
b28df75e 2057 struct gpt_header *header, unsigned char *ents)
766d5156 2058{
afb27a8e 2059 size_t esz = 0;
9e320545
KZ
2060 int rc;
2061
afb27a8e 2062 rc = gpt_sizeof_entries(header, &esz);
9e320545
KZ
2063 if (rc)
2064 return rc;
766d5156 2065
afb27a8e
KZ
2066 return gpt_write(cxt,
2067 (off_t) le64_to_cpu(header->partition_entry_lba) * cxt->sector_size,
2068 ents, esz);
766d5156
DB
2069}
2070
2071/*
4bb82a45
KZ
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 *
766d5156
DB
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{
afb27a8e 2082 return gpt_write(cxt, lba * cxt->sector_size, header, cxt->sector_size);
766d5156
DB
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{
1b504263 2091 struct gpt_legacy_mbr *pmbr;
17b4496a
PR
2092 struct gpt_legacy_mbr *current;
2093 int rc;
766d5156 2094
9ffeb235
KZ
2095 assert(cxt);
2096 assert(cxt->firstsector);
766d5156 2097
36cd4b3c 2098 DBG(GPT, ul_debug("(over)writing PMBR"));
766d5156
DB
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;
8ffa3b65
KZ
2106 pmbr->partition_record[0].start_sector = 2;
2107 pmbr->partition_record[0].end_head = 0xFF;
766d5156
DB
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 */
0a7cdf80 2116 if (cxt->total_sectors - 1ULL > 0xFFFFFFFFULL)
766d5156
DB
2117 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
2118 else
2119 pmbr->partition_record[0].size_in_lba =
0a7cdf80 2120 cpu_to_le32((uint32_t) (cxt->total_sectors - 1ULL));
766d5156 2121
654a443a
KZ
2122 /* Read the current PMBR and compare it with the new, don't write if
2123 * the same. */
17b4496a
PR
2124 current = malloc(sizeof(*current));
2125 if (!current)
2126 goto do_write;
2127
2128 rc = gpt_read(cxt, GPT_PMBR_LBA * cxt->sector_size,
7e07aa75 2129 current, sizeof(*current));
17b4496a
PR
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:
19613111 2141 /* pMBR covers the first sector (LBA) of the disk */
afb27a8e
KZ
2142 return gpt_write(cxt, GPT_PMBR_LBA * cxt->sector_size,
2143 pmbr, cxt->sector_size);
766d5156
DB
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 */
9ffeb235 2151static int gpt_write_disklabel(struct fdisk_context *cxt)
766d5156 2152{
9ffeb235 2153 struct fdisk_gpt_label *gpt;
433d05ff 2154 int mbr_type;
d71ef5a4 2155
9ffeb235
KZ
2156 assert(cxt);
2157 assert(cxt->label);
aa36c2cf 2158 assert(fdisk_is_label(cxt, GPT));
9ffeb235 2159
aa1c7a76 2160 DBG(GPT, ul_debug("writing..."));
36cd4b3c 2161
9ffeb235 2162 gpt = self_label(cxt);
433d05ff 2163 mbr_type = valid_pmbr(cxt);
766d5156
DB
2164
2165 /* check that disk is big enough to handle the backup header */
c15aec86 2166 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
766d5156
DB
2167 goto err0;
2168
2169 /* check that the backup header is properly placed */
0a7cdf80 2170 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1ULL)
766d5156
DB
2171 goto err0;
2172
b28df75e 2173 if (check_overlap_partitions(gpt))
766d5156
DB
2174 goto err0;
2175
387ac277
KZ
2176 if (gpt->minimize)
2177 gpt_minimize_alternative_lba(cxt, gpt);
2178
766d5156 2179 /* recompute CRCs for both headers */
d71ef5a4
KZ
2180 gpt_recompute_crc(gpt->pheader, gpt->ents);
2181 gpt_recompute_crc(gpt->bheader, gpt->ents);
766d5156
DB
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 */
d71ef5a4 2193 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
766d5156 2194 goto err1;
c15aec86
KZ
2195 if (gpt_write_header(cxt, gpt->bheader,
2196 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
766d5156 2197 goto err1;
d71ef5a4 2198 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
766d5156 2199 goto err1;
d71ef5a4 2200 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
766d5156 2201 goto err1;
433d05ff
KZ
2202
2203 if (mbr_type == GPT_MBR_HYBRID)
1d844703 2204 fdisk_warnx(cxt, _("The device contains hybrid MBR -- writing GPT only."));
433d05ff 2205 else if (gpt_write_pmbr(cxt) != 0)
766d5156
DB
2206 goto err1;
2207
36cd4b3c 2208 DBG(GPT, ul_debug("...write success"));
766d5156
DB
2209 return 0;
2210err0:
36cd4b3c 2211 DBG(GPT, ul_debug("...write failed: incorrect input"));
c15aec86 2212 errno = EINVAL;
766d5156
DB
2213 return -EINVAL;
2214err1:
36cd4b3c 2215 DBG(GPT, ul_debug("...write failed: %m"));
766d5156
DB
2216 return -errno;
2217}
2218
2219/*
2220 * Verify data integrity and report any found problems for:
2221 * - primary and backup header validations
9e930041 2222 * - partition validations
766d5156 2223 */
9ffeb235 2224static int gpt_verify_disklabel(struct fdisk_context *cxt)
766d5156 2225{
83df5feb
KZ
2226 int nerror = 0;
2227 unsigned int ptnum;
9ffeb235
KZ
2228 struct fdisk_gpt_label *gpt;
2229
2230 assert(cxt);
2231 assert(cxt->label);
aa36c2cf 2232 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
2233
2234 gpt = self_label(cxt);
e820595b
KZ
2235 if (!gpt)
2236 return -EINVAL;
766d5156 2237
e820595b 2238 if (!gpt->bheader) {
766d5156 2239 nerror++;
83df5feb 2240 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
766d5156
DB
2241 }
2242
d71ef5a4 2243 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
766d5156 2244 nerror++;
83df5feb 2245 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
766d5156 2246 }
d71ef5a4 2247 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
766d5156 2248 nerror++;
83df5feb 2249 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
766d5156
DB
2250 }
2251
d71ef5a4 2252 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
766d5156 2253 nerror++;
83df5feb 2254 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
766d5156
DB
2255 }
2256
d71ef5a4 2257 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
766d5156 2258 nerror++;
83df5feb 2259 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
766d5156 2260 }
d71ef5a4 2261 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
766d5156 2262 nerror++;
83df5feb 2263 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
766d5156
DB
2264 }
2265
d71ef5a4 2266 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
766d5156 2267 nerror++;
83df5feb 2268 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
766d5156 2269 }
d71ef5a4 2270 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
766d5156 2271 nerror++;
83df5feb 2272 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
766d5156
DB
2273
2274 }
c15aec86 2275 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
766d5156 2276 nerror++;
a1e276ae 2277 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
766d5156
DB
2278 }
2279
2280 /*
2281 * if the GPT is the primary table, check the alternateLBA
2282 * to see if it is a valid GPT
2283 */
c15aec86
KZ
2284 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
2285 le64_to_cpu(gpt->bheader->alternative_lba))) {
766d5156 2286 nerror++;
83df5feb 2287 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
766d5156
DB
2288 }
2289
b28df75e 2290 ptnum = check_overlap_partitions(gpt);
766d5156
DB
2291 if (ptnum) {
2292 nerror++;
83df5feb
KZ
2293 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
2294 ptnum, ptnum+1);
766d5156
DB
2295 }
2296
b28df75e 2297 ptnum = check_too_big_partitions(gpt, cxt->total_sectors);
766d5156
DB
2298 if (ptnum) {
2299 nerror++;
83df5feb
KZ
2300 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
2301 ptnum);
766d5156
DB
2302 }
2303
b28df75e 2304 ptnum = check_start_after_end_partitions(gpt);
766d5156
DB
2305 if (ptnum) {
2306 nerror++;
83df5feb
KZ
2307 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
2308 ptnum);
766d5156
DB
2309 }
2310
2311 if (!nerror) { /* yay :-) */
2312 uint32_t nsegments = 0;
2313 uint64_t free_sectors = 0, largest_segment = 0;
6d0ed4cb 2314 char *strsz = NULL;
766d5156 2315
ac1a559a 2316 fdisk_info(cxt, _("No errors detected."));
83df5feb 2317 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
b683c081 2318 fdisk_info(cxt, _("Using %zu out of %zu partitions."),
b28df75e 2319 partitions_in_use(gpt),
b683c081 2320 gpt_get_nentries(gpt));
766d5156 2321
b28df75e 2322 free_sectors = get_free_sectors(cxt, gpt, &nsegments, &largest_segment);
6d0ed4cb
KZ
2323 if (largest_segment)
2324 strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER,
2325 largest_segment * cxt->sector_size);
2326
4ae11fe8 2327 fdisk_info(cxt,
829f4206
KZ
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 "
6d0ed4cb 2330 "(the largest is %s).", nsegments),
a64e9911 2331 free_sectors, nsegments, strsz ? : "0 B");
6d0ed4cb
KZ
2332 free(strsz);
2333
766d5156 2334 } else
a1e276ae 2335 fdisk_warnx(cxt,
8e7f944d 2336 P_("%d error detected.", "%d errors detected.", nerror),
a1e276ae 2337 nerror);
766d5156 2338
c7fce443 2339 return nerror;
766d5156
DB
2340}
2341
2342/* Delete a single GPT partition, specified by partnum. */
8a95621d 2343static int gpt_delete_partition(struct fdisk_context *cxt,
9ffeb235 2344 size_t partnum)
766d5156 2345{
9ffeb235 2346 struct fdisk_gpt_label *gpt;
d71ef5a4 2347
9ffeb235
KZ
2348 assert(cxt);
2349 assert(cxt->label);
aa36c2cf 2350 assert(fdisk_is_label(cxt, GPT));
d71ef5a4 2351
9ffeb235
KZ
2352 gpt = self_label(cxt);
2353
b28df75e 2354 if (partnum >= cxt->label->nparts_max)
1f5eb51b 2355 return -EINVAL;
766d5156 2356
02a376f2 2357 if (!gpt_entry_is_used(gpt_get_entry(gpt, partnum)))
1f5eb51b 2358 return -EINVAL;
b28df75e
KZ
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);
1f5eb51b
DB
2367
2368 return 0;
766d5156
DB
2369}
2370
080633e4 2371
766d5156 2372/* Performs logical checks to add a new partition entry */
8a95621d
KZ
2373static int gpt_add_partition(
2374 struct fdisk_context *cxt,
c3bc7483
KZ
2375 struct fdisk_partition *pa,
2376 size_t *partno)
766d5156 2377{
512a430f
KZ
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*/
921c7da5 2380 uint64_t dflt_f, dflt_l, max_l; /* largest segment (default) */
c0d14b09 2381 struct gpt_guid typeid;
9ffeb235 2382 struct fdisk_gpt_label *gpt;
d71ef5a4 2383 struct gpt_header *pheader;
b28df75e 2384 struct gpt_entry *e;
4114da08 2385 struct fdisk_ask *ask = NULL;
77d6a70a 2386 size_t partnum;
4114da08 2387 int rc;
766d5156 2388
9ffeb235
KZ
2389 assert(cxt);
2390 assert(cxt->label);
aa36c2cf 2391 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
2392
2393 gpt = self_label(cxt);
b28df75e
KZ
2394
2395 assert(gpt);
2396 assert(gpt->pheader);
2397 assert(gpt->ents);
2398
d71ef5a4 2399 pheader = gpt->pheader;
d71ef5a4 2400
6c89f750 2401 rc = fdisk_partition_next_partno(pa, cxt, &partnum);
1240f549 2402 if (rc) {
36cd4b3c 2403 DBG(GPT, ul_debug("failed to get next partno"));
77d6a70a 2404 return rc;
1240f549 2405 }
b28df75e 2406
b683c081 2407 assert(partnum < gpt_get_nentries(gpt));
b28df75e 2408
02a376f2 2409 if (gpt_entry_is_used(gpt_get_entry(gpt, partnum))) {
829f4206 2410 fdisk_warnx(cxt, _("Partition %zu is already defined. "
83217641 2411 "Delete it before re-adding it."), partnum +1);
77d6a70a 2412 return -ERANGE;
766d5156 2413 }
b683c081 2414 if (gpt_get_nentries(gpt) == partitions_in_use(gpt)) {
83df5feb 2415 fdisk_warnx(cxt, _("All partitions are already in use."));
77d6a70a 2416 return -ENOSPC;
766d5156 2417 }
b28df75e 2418 if (!get_free_sectors(cxt, gpt, NULL, NULL)) {
83df5feb 2419 fdisk_warnx(cxt, _("No free sectors available."));
8254c3a5 2420 return -ENOSPC;
766d5156
DB
2421 }
2422
4044d244 2423 rc = string_to_guid(pa && pa->type && pa->type->typestr ?
77d6a70a
KZ
2424 pa->type->typestr:
2425 GPT_DEFAULT_ENTRY_TYPE, &typeid);
4044d244
KZ
2426 if (rc)
2427 return rc;
77d6a70a 2428
b28df75e
KZ
2429 disk_f = find_first_available(gpt, le64_to_cpu(pheader->first_usable_lba));
2430 e = gpt_get_entry(gpt, 0);
4a4616b2
KZ
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))
02a376f2 2435 && gpt_entry_is_used(e)
b28df75e 2436 && disk_f < gpt_partition_start(e)) {
4a4616b2
KZ
2437
2438 do {
2439 uint64_t x;
36cd4b3c 2440 DBG(GPT, ul_debug("testing first sector %"PRIu64"", disk_f));
b28df75e 2441 disk_f = find_first_available(gpt, disk_f);
4a4616b2
KZ
2442 if (!disk_f)
2443 break;
b28df75e 2444 x = find_last_free(gpt, disk_f);
4a4616b2
KZ
2445 if (x - disk_f >= cxt->grain / cxt->sector_size)
2446 break;
36cd4b3c 2447 DBG(GPT, ul_debug("first sector %"PRIu64" addresses to small space, continue...", disk_f));
0a7cdf80 2448 disk_f = x + 1ULL;
4a4616b2
KZ
2449 } while(1);
2450
2451 if (disk_f == 0)
b28df75e 2452 disk_f = find_first_available(gpt, le64_to_cpu(pheader->first_usable_lba));
4a4616b2
KZ
2453 }
2454
b28df75e
KZ
2455 e = NULL;
2456 disk_l = find_last_free_sector(gpt);
512a430f
KZ
2457
2458 /* the default is the largest free space */
b28df75e
KZ
2459 dflt_f = find_first_in_largest(gpt);
2460 dflt_l = find_last_free(gpt, dflt_f);
512a430f 2461
a64e9911
KZ
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
512a430f 2470 /* align the default in range <dflt_f,dflt_l>*/
9475cc78 2471 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
766d5156 2472
77d6a70a 2473 /* first sector */
ecf40cda
KZ
2474 if (pa && pa->start_follow_default) {
2475 user_f = dflt_f;
2476
2477 } else if (pa && fdisk_partition_has_start(pa)) {
36cd4b3c 2478 DBG(GPT, ul_debug("first sector defined: %ju", (uintmax_t)pa->start));
b28df75e 2479 if (pa->start != find_first_available(gpt, pa->start)) {
fdbd7bb9 2480 fdisk_warnx(cxt, _("Sector %ju already used."), (uintmax_t)pa->start);
77d6a70a 2481 return -ERANGE;
e3443e8f 2482 }
77d6a70a 2483 user_f = pa->start;
77d6a70a
KZ
2484 } else {
2485 /* ask by dialog */
2486 for (;;) {
2487 if (!ask)
2488 ask = fdisk_new_ask();
2489 else
2490 fdisk_reset_ask(ask);
5cebb2ab
VD
2491 if (!ask)
2492 return -ENOMEM;
77d6a70a
KZ
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);
b28df75e 2506 if (user_f != find_first_available(gpt, user_f)) {
77d6a70a
KZ
2507 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
2508 continue;
2509 }
512a430f 2510 break;
77d6a70a
KZ
2511 }
2512 }
2513
1240f549 2514
77d6a70a 2515 /* Last sector */
921c7da5
KZ
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;
77d6a70a 2524
ecf40cda
KZ
2525 if (pa && pa->end_follow_default) {
2526 user_l = dflt_l;
2527
2528 } else if (pa && fdisk_partition_has_size(pa)) {
ee50336c 2529 user_l = user_f + pa->size - 1;
921c7da5
KZ
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));
694a407d
KZ
2533
2534 if (user_l != dflt_l
2535 && !pa->size_explicit
2536 && alignment_required(cxt)
d527d2dd 2537 && user_l - user_f > (cxt->grain / fdisk_get_sector_size(cxt))) {
694a407d 2538
68fe4b28
KZ
2539 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2540 if (user_l > user_f)
0a7cdf80 2541 user_l -= 1ULL;
68fe4b28 2542 }
77d6a70a
KZ
2543 } else {
2544 for (;;) {
2545 if (!ask)
2546 ask = fdisk_new_ask();
2547 else
2548 fdisk_reset_ask(ask);
7c43fd23
KZ
2549 if (!ask)
2550 return -ENOMEM;
77d6a70a 2551
757cefbb 2552 fdisk_ask_set_query(ask, _("Last sector, +/-sectors or +/-size{K,M,G,T,P}"));
77d6a70a
KZ
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 */
921c7da5 2556 fdisk_ask_number_set_high(ask, max_l); /* maximal */
77d6a70a
KZ
2557 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
2558 fdisk_ask_number_set_unit(ask, cxt->sector_size);
757cefbb 2559 fdisk_ask_number_set_wrap_negative(ask, 1); /* wrap negative around high */
77d6a70a
KZ
2560
2561 rc = fdisk_do_ask(cxt, ask);
2562 if (rc)
2563 goto done;
2564
2565 user_l = fdisk_ask_number_get_result(ask);
1240f549 2566 if (fdisk_ask_number_is_relative(ask)) {
765004f3
KZ
2567 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l);
2568 if (user_l > user_f)
0a7cdf80 2569 user_l -= 1ULL;
0c344037 2570 }
18b266ce 2571
765004f3 2572 if (user_l >= user_f && user_l <= disk_l)
77d6a70a 2573 break;
8c73e509
KZ
2574
2575 fdisk_warnx(cxt, _("Value out of range."));
77d6a70a 2576 }
766d5156
DB
2577 }
2578
8d95e7e0
KZ
2579
2580 if (user_f > user_l || partnum >= cxt->label->nparts_max) {
27aadd8b 2581 fdisk_warnx(cxt, _("Could not create partition %zu"), partnum + 1);
8d95e7e0 2582 rc = -EINVAL;
1240f549 2583 goto done;
8d95e7e0
KZ
2584 }
2585
3fd1f771 2586 /* Be paranoid and check against on-disk setting rather than against libfdisk cxt */
9d9a1b87
KZ
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
ecf40cda
KZ
2601 assert(!FDISK_IS_UNDEF(user_l));
2602 assert(!FDISK_IS_UNDEF(user_f));
b683c081 2603 assert(partnum < gpt_get_nentries(gpt));
ecf40cda 2604
b28df75e 2605 e = gpt_get_entry(gpt, partnum);
8d95e7e0
KZ
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;
1240f549 2618 } else {
8d95e7e0
KZ
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 */
92e486f8
RM
2623 struct gpt_guid guid;
2624
dd405ea7 2625 uuid_generate_random((unsigned char *) &guid);
92e486f8 2626 swap_efi_guid(&guid);
dd405ea7 2627 e->partition_guid = guid;
8d95e7e0
KZ
2628 }
2629
2630 if (pa && pa->name && *pa->name)
2631 gpt_entry_set_name(e, pa->name);
c77ba531
KZ
2632 if (pa && pa->attrs)
2633 gpt_entry_attrs_from_string(cxt, e, pa->attrs);
8d95e7e0 2634
36cd4b3c 2635 DBG(GPT, ul_debug("new partition: partno=%zu, start=%"PRIu64", end=%"PRIu64", size=%"PRIu64"",
ee50336c
KZ
2636 partnum,
2637 gpt_partition_start(e),
2638 gpt_partition_end(e),
2639 gpt_partition_size(e)));
2640
b28df75e
KZ
2641 gpt_recompute_crc(gpt->pheader, gpt->ents);
2642 gpt_recompute_crc(gpt->bheader, gpt->ents);
8d95e7e0
KZ
2643
2644 /* report result */
2645 {
a01b5b70
KZ
2646 struct fdisk_parttype *t;
2647
9ffeb235
KZ
2648 cxt->label->nparts_cur++;
2649 fdisk_label_set_changed(cxt->label, 1);
a01b5b70 2650
b28df75e 2651 t = gpt_partition_parttype(cxt, e);
a01b5b70 2652 fdisk_info_new_partition(cxt, partnum + 1, user_f, user_l, t);
dfc6db2a 2653 fdisk_unref_parttype(t);
9fcd49d5 2654 }
8254c3a5 2655
4114da08 2656 rc = 0;
c3bc7483
KZ
2657 if (partno)
2658 *partno = partnum;
4114da08 2659done:
a3d83488 2660 fdisk_unref_ask(ask);
4114da08 2661 return rc;
766d5156
DB
2662}
2663
3f731001
DB
2664/*
2665 * Create a new GPT disklabel - destroys any previous data.
2666 */
9ffeb235 2667static int gpt_create_disklabel(struct fdisk_context *cxt)
3f731001
DB
2668{
2669 int rc = 0;
5eaeb585 2670 size_t esz = 0;
b443c177 2671 char str[UUID_STR_LEN];
9ffeb235 2672 struct fdisk_gpt_label *gpt;
92e486f8 2673 struct gpt_guid guid;
9ffeb235
KZ
2674
2675 assert(cxt);
2676 assert(cxt->label);
aa36c2cf 2677 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
2678
2679 gpt = self_label(cxt);
3f731001 2680
d71ef5a4 2681 /* label private stuff has to be empty, see gpt_deinit() */
d71ef5a4
KZ
2682 assert(gpt->pheader == NULL);
2683 assert(gpt->bheader == NULL);
4e0e8253 2684
3f731001 2685 /*
3f731001
DB
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 */
3f731001
DB
2690 rc = gpt_mknew_pmbr(cxt);
2691 if (rc < 0)
2692 goto done;
2693
4bb82a45
KZ
2694 assert(cxt->sector_size >= sizeof(struct gpt_header));
2695
d71ef5a4 2696 /* primary */
4bb82a45 2697 gpt->pheader = calloc(1, cxt->sector_size);
46667ba4
KZ
2698 if (!gpt->pheader) {
2699 rc = -ENOMEM;
2700 goto done;
2701 }
d71ef5a4 2702 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
3f731001
DB
2703 if (rc < 0)
2704 goto done;
2705
d71ef5a4 2706 /* backup ("copy" primary) */
4bb82a45 2707 gpt->bheader = calloc(1, cxt->sector_size);
46667ba4
KZ
2708 if (!gpt->bheader) {
2709 rc = -ENOMEM;
2710 goto done;
2711 }
d71ef5a4
KZ
2712 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
2713 last_lba(cxt), gpt->pheader);
3f731001
DB
2714 if (rc < 0)
2715 goto done;
2716
b1bc5ae3 2717 rc = gpt_sizeof_entries(gpt->pheader, &esz);
9e320545
KZ
2718 if (rc)
2719 goto done;
46667ba4
KZ
2720 gpt->ents = calloc(1, esz);
2721 if (!gpt->ents) {
2722 rc = -ENOMEM;
2723 goto done;
2724 }
d71ef5a4
KZ
2725 gpt_recompute_crc(gpt->pheader, gpt->ents);
2726 gpt_recompute_crc(gpt->bheader, gpt->ents);
3f731001 2727
b683c081 2728 cxt->label->nparts_max = gpt_get_nentries(gpt);
9ffeb235 2729 cxt->label->nparts_cur = 0;
9fcd49d5 2730
92e486f8
RM
2731 guid = gpt->pheader->disk_guid;
2732 guid_to_string(&guid, str);
9ffeb235 2733 fdisk_label_set_changed(cxt->label, 1);
0477369a 2734 fdisk_info(cxt, _("Created a new GPT disklabel (GUID: %s)."), str);
b11e1b7e
KZ
2735
2736 if (gpt_get_nentries(gpt) < GPT_NPARTITIONS)
fbae1442 2737 fdisk_info(cxt, _("The maximal number of partitions is %zu (default is %zu)."),
b11e1b7e 2738 gpt_get_nentries(gpt), GPT_NPARTITIONS);
3f731001
DB
2739done:
2740 return rc;
2741}
2742
e5f31446 2743static int gpt_set_disklabel_id(struct fdisk_context *cxt, const char *str)
35b1f0a4
KZ
2744{
2745 struct fdisk_gpt_label *gpt;
2746 struct gpt_guid uuid;
e5f31446 2747 char *old, *new;
35b1f0a4
KZ
2748 int rc;
2749
2750 assert(cxt);
2751 assert(cxt->label);
aa36c2cf 2752 assert(fdisk_is_label(cxt, GPT));
35b1f0a4
KZ
2753
2754 gpt = self_label(cxt);
e5f31446 2755 if (!str) {
3c3b7648
KZ
2756 char *buf = NULL;
2757
e5f31446 2758 if (fdisk_ask_string(cxt,
3c3b7648 2759 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &buf))
e5f31446 2760 return -EINVAL;
3c3b7648
KZ
2761 rc = string_to_guid(buf, &uuid);
2762 free(buf);
e5f31446
KZ
2763 } else
2764 rc = string_to_guid(str, &uuid);
35b1f0a4
KZ
2765
2766 if (rc) {
2767 fdisk_warnx(cxt, _("Failed to parse your UUID."));
2768 return rc;
2769 }
2770
5989556a 2771 old = gpt_get_header_id(gpt->pheader);
35b1f0a4
KZ
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
5989556a 2779 new = gpt_get_header_id(gpt->pheader);
35b1f0a4 2780
0477369a 2781 fdisk_info(cxt, _("Disk identifier changed from %s to %s."), old, new);
35b1f0a4
KZ
2782
2783 free(old);
2784 free(new);
2785 fdisk_label_set_changed(cxt->label, 1);
2786 return 0;
2787}
2788
a18e726c
SP
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);
b683c081 2794 size_t i;
a18e726c
SP
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 */
b683c081 2806 for (i = 0; i < gpt_get_nentries(gpt); i++) {
b28df75e
KZ
2807 struct gpt_entry *e = gpt_get_entry(gpt, i);
2808
02a376f2 2809 if (!gpt_entry_is_used(e))
a18e726c 2810 continue;
b28df75e 2811 if (gpt_partition_start(e) < first_usable) {
b683c081 2812 fdisk_warnx(cxt, _("Partition #%zu out of range (minimal start is %"PRIu64" sectors)"),
a18e726c
SP
2813 i + 1, first_usable);
2814 rc = -EINVAL;
2815 }
b28df75e 2816 if (gpt_partition_end(e) > last_usable) {
b683c081 2817 fdisk_warnx(cxt, _("Partition #%zu out of range (maximal end is %"PRIu64" sectors)"),
fbae1442 2818 i + 1, last_usable - (uint64_t) 1);
a18e726c
SP
2819 rc = -EINVAL;
2820 }
2821 }
2822 return rc;
2823}
2824
f88eeb25
KZ
2825/**
2826 * fdisk_gpt_set_npartitions:
2827 * @cxt: context
b1bc5ae3 2828 * @nents: number of wanted entries
f88eeb25 2829 *
5225bdad 2830 * Enlarge GPT entries array if possible. The function check if an existing
f88eeb25
KZ
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.
81b176c4 2835 * Since: 2.29
f88eeb25 2836 */
b1bc5ae3 2837int fdisk_gpt_set_npartitions(struct fdisk_context *cxt, uint32_t nents)
a18e726c
SP
2838{
2839 struct fdisk_gpt_label *gpt;
d1187380 2840 size_t new_size = 0;
b1bc5ae3 2841 uint32_t old_nents;
d1187380 2842 uint64_t first_usable = 0ULL, last_usable = 0ULL;
a18e726c
SP
2843 int rc;
2844
2845 assert(cxt);
2846 assert(cxt->label);
21f1206a
KZ
2847
2848 if (!fdisk_is_label(cxt, GPT))
2849 return -EINVAL;
a18e726c
SP
2850
2851 gpt = self_label(cxt);
2852
b1bc5ae3
KZ
2853 old_nents = le32_to_cpu(gpt->pheader->npartition_entries);
2854 if (old_nents == nents)
a67054f9 2855 return 0; /* do nothing, say nothing */
a18e726c
SP
2856
2857 /* calculate the size (bytes) of the entries array */
b1bc5ae3 2858 rc = gpt_calculate_sizeof_entries(gpt->pheader, nents, &new_size);
9e320545 2859 if (rc) {
845fd622
KZ
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."),
fbae1442 2866 (size_t) UINT32_MAX / entry_size);
9e320545 2867 return rc;
f71b96bf
KZ
2868 }
2869
d1187380
KZ
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;
a18e726c
SP
2875
2876 /* if expanding the table, first check that everything fits,
2877 * then allocate more memory and zero. */
b1bc5ae3 2878 if (nents > old_nents) {
b28df75e 2879 unsigned char *ents;
d1187380 2880 size_t old_size = 0;
b28df75e 2881
b1bc5ae3 2882 rc = gpt_calculate_sizeof_entries(gpt->pheader, old_nents, &old_size);
d1187380 2883 if (rc == 0)
b1bc5ae3 2884 rc = gpt_check_table_overlap(cxt, first_usable, last_usable);
a18e726c
SP
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 }
52f35f1e 2892 memset(ents + old_size, 0, new_size - old_size);
a18e726c
SP
2893 gpt->ents = ents;
2894 }
2895
2896 /* everything's ok, apply the new size */
b1bc5ae3
KZ
2897 gpt->pheader->npartition_entries = cpu_to_le32(nents);
2898 gpt->bheader->npartition_entries = cpu_to_le32(nents);
a18e726c
SP
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
a18e726c
SP
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
bbb574a2
KZ
2915 /* update library info */
2916 cxt->label->nparts_max = gpt_get_nentries(gpt);
2917
fbae1442 2918 fdisk_info(cxt, _("Partition table length changed from %"PRIu32" to %"PRIu32"."),
b1bc5ae3 2919 old_nents, nents);
a18e726c
SP
2920
2921 fdisk_label_set_changed(cxt->label, 1);
2922 return 0;
2923}
2924
8c0a7f91 2925static int gpt_part_is_used(struct fdisk_context *cxt, size_t i)
47b8e7c0 2926{
9ffeb235 2927 struct fdisk_gpt_label *gpt;
47b8e7c0
KZ
2928 struct gpt_entry *e;
2929
9ffeb235
KZ
2930 assert(cxt);
2931 assert(cxt->label);
aa36c2cf 2932 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
2933
2934 gpt = self_label(cxt);
2935
b683c081 2936 if (i >= gpt_get_nentries(gpt))
8c0a7f91 2937 return 0;
b28df75e
KZ
2938
2939 e = gpt_get_entry(gpt, i);
47b8e7c0 2940
02a376f2 2941 return gpt_entry_is_used(e) || gpt_partition_start(e);
47b8e7c0
KZ
2942}
2943
0077e7cd
KZ
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 */
433d05ff
KZ
2960int fdisk_gpt_is_hybrid(struct fdisk_context *cxt)
2961{
2962 assert(cxt);
2963 return valid_pmbr(cxt) == GPT_MBR_HYBRID;
2964}
2965
4a4a0927
MM
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);
21f1206a
KZ
2985
2986 if (!fdisk_is_label(cxt, GPT))
2987 return -EINVAL;
4a4a0927
MM
2988
2989 gpt = self_label(cxt);
2990
b683c081 2991 if (partnum >= gpt_get_nentries(gpt))
4a4a0927
MM
2992 return -EINVAL;
2993
b28df75e 2994 *attrs = le64_to_cpu(gpt_get_entry(gpt, partnum)->attrs);
4a4a0927
MM
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);
21f1206a
KZ
3017
3018 if (!fdisk_is_label(cxt, GPT))
3019 return -EINVAL;
4a4a0927 3020
36cd4b3c 3021 DBG(GPT, ul_debug("entry attributes change requested partno=%zu", partnum));
4a4a0927
MM
3022 gpt = self_label(cxt);
3023
b683c081 3024 if (partnum >= gpt_get_nentries(gpt))
4a4a0927
MM
3025 return -EINVAL;
3026
b28df75e 3027 gpt_get_entry(gpt, partnum)->attrs = cpu_to_le64(attrs);
4a4a0927
MM
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
c83f772e
KZ
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;
b28df75e 3043 struct gpt_entry *e;
262c94c2
RM
3044 uint64_t attrs;
3045 uintmax_t tmp;
01086b80
KZ
3046 char *bits;
3047 const char *name = NULL;
3048 int bit = -1, rc;
c83f772e
KZ
3049
3050 assert(cxt);
3051 assert(cxt->label);
aa36c2cf 3052 assert(fdisk_is_label(cxt, GPT));
c83f772e 3053
36cd4b3c 3054 DBG(GPT, ul_debug("entry attribute change requested partno=%zu", i));
c83f772e
KZ
3055 gpt = self_label(cxt);
3056
b683c081 3057 if (i >= gpt_get_nentries(gpt))
c83f772e
KZ
3058 return -EINVAL;
3059
b28df75e
KZ
3060 e = gpt_get_entry(gpt, i);
3061 attrs = e->attrs;
01086b80 3062 bits = (char *) &attrs;
c83f772e
KZ
3063
3064 switch (flag) {
3065 case GPT_FLAG_REQUIRED:
01086b80
KZ
3066 bit = GPT_ATTRBIT_REQ;
3067 name = GPT_ATTRSTR_REQ;
c83f772e
KZ
3068 break;
3069 case GPT_FLAG_NOBLOCK:
01086b80
KZ
3070 bit = GPT_ATTRBIT_NOBLOCK;
3071 name = GPT_ATTRSTR_NOBLOCK;
c83f772e
KZ
3072 break;
3073 case GPT_FLAG_LEGACYBOOT:
01086b80
KZ
3074 bit = GPT_ATTRBIT_LEGACY;
3075 name = GPT_ATTRSTR_LEGACY;
c83f772e
KZ
3076 break;
3077 case GPT_FLAG_GUIDSPECIFIC:
01086b80 3078 rc = fdisk_ask_number(cxt, 48, 48, 63, _("Enter GUID specific bit"), &tmp);
c83f772e
KZ
3079 if (rc)
3080 return rc;
01086b80
KZ
3081 bit = tmp;
3082 break;
773aae5c
KZ
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;
01086b80 3090 }
c83f772e 3091
773aae5c
KZ
3092 if (bit < 0) {
3093 fdisk_warnx(cxt, _("failed to toggle unsupported bit %lu"), flag);
01086b80 3094 return -EINVAL;
773aae5c 3095 }
01086b80
KZ
3096
3097 if (!isset(bits, bit))
3098 setbit(bits, bit);
3099 else
3100 clrbit(bits, bit);
3101
b28df75e 3102 e->attrs = attrs;
01086b80
KZ
3103
3104 if (flag == GPT_FLAG_GUIDSPECIFIC)
0477369a 3105 fdisk_info(cxt, isset(bits, bit) ?
01086b80
KZ
3106 _("The GUID specific bit %d on partition %zu is enabled now.") :
3107 _("The GUID specific bit %d on partition %zu is disabled now."),
c83f772e 3108 bit, i + 1);
01086b80 3109 else
0477369a 3110 fdisk_info(cxt, isset(bits, bit) ?
01086b80
KZ
3111 _("The %s flag on partition %zu is enabled now.") :
3112 _("The %s flag on partition %zu is disabled now."),
3113 name, i + 1);
c83f772e
KZ
3114
3115 gpt_recompute_crc(gpt->pheader, gpt->ents);
3116 gpt_recompute_crc(gpt->bheader, gpt->ents);
01086b80 3117 fdisk_label_set_changed(cxt->label, 1);
c83f772e
KZ
3118 return 0;
3119}
1054699c 3120
9348ef25
KZ
3121static int gpt_entry_cmp_start(const void *a, const void *b)
3122{
ec4b88b8
KZ
3123 const struct gpt_entry *ae = (const struct gpt_entry *) a,
3124 *be = (const struct gpt_entry *) b;
02a376f2
KZ
3125 int au = gpt_entry_is_used(ae),
3126 bu = gpt_entry_is_used(be);
9348ef25 3127
02a376f2 3128 if (!au && !bu)
9348ef25 3129 return 0;
02a376f2 3130 if (!au)
9348ef25 3131 return 1;
02a376f2 3132 if (!bu)
9348ef25
KZ
3133 return -1;
3134
19ff8ff7 3135 return cmp_numbers(gpt_partition_start(ae), gpt_partition_start(be));
9348ef25
KZ
3136}
3137
3138/* sort partition by start sector */
3139static int gpt_reorder(struct fdisk_context *cxt)
3140{
3141 struct fdisk_gpt_label *gpt;
dd49c7d6 3142 size_t i, nparts, mess;
9348ef25
KZ
3143
3144 assert(cxt);
3145 assert(cxt->label);
aa36c2cf 3146 assert(fdisk_is_label(cxt, GPT));
9348ef25
KZ
3147
3148 gpt = self_label(cxt);
b683c081 3149 nparts = gpt_get_nentries(gpt);
9348ef25 3150
dd49c7d6
KZ
3151 for (i = 0, mess = 0; mess == 0 && i + 1 < nparts; i++)
3152 mess = gpt_entry_cmp_start(
b28df75e
KZ
3153 (const void *) gpt_get_entry(gpt, i),
3154 (const void *) gpt_get_entry(gpt, i + 1)) > 0;
dd49c7d6 3155
b948bbf9 3156 if (!mess)
dd49c7d6 3157 return 1;
dd49c7d6 3158
9348ef25
KZ
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
9348ef25
KZ
3166 return 0;
3167}
3168
1240f549
KZ
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);
aa36c2cf 3176 assert(fdisk_is_label(cxt, GPT));
1240f549
KZ
3177
3178 gpt = self_label(cxt);
3179 h = gpt ? gpt->pheader : NULL;
3180
3181 if (h) {
3182 /* always follow existing table */
43a2b094
KZ
3183 cxt->first_lba = le64_to_cpu(h->first_usable_lba);
3184 cxt->last_lba = le64_to_cpu(h->last_usable_lba);
1240f549
KZ
3185 } else {
3186 /* estimate ranges for GPT */
3187 uint64_t first, last;
c9674e73 3188 int rc;
1240f549 3189
c9674e73
KZ
3190 rc = count_first_last_lba(cxt, &first, &last, NULL);
3191 if (rc)
3192 return rc;
1240f549
KZ
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}
4e0e8253
KZ
3201/*
3202 * Deinitialize fdisk-specific variables
3203 */
d71ef5a4 3204static void gpt_deinit(struct fdisk_label *lb)
4e0e8253 3205{
d71ef5a4
KZ
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;
4e0e8253
KZ
3218}
3219
0c5d095e 3220static const struct fdisk_label_operations gpt_operations =
766d5156 3221{
0c5d095e
KZ
3222 .probe = gpt_probe_label,
3223 .write = gpt_write_disklabel,
3224 .verify = gpt_verify_disklabel,
3225 .create = gpt_create_disklabel,
775001ad 3226 .locate = gpt_locate_disklabel,
5989556a 3227 .get_item = gpt_get_disklabel_item,
35b1f0a4 3228 .set_id = gpt_set_disklabel_id,
21fe3dde 3229
8c0a7f91 3230 .get_part = gpt_get_partition,
b0a484a8 3231 .set_part = gpt_set_partition,
77d6a70a 3232 .add_part = gpt_add_partition,
e11c6684 3233 .del_part = gpt_delete_partition,
5989556a 3234 .reorder = gpt_reorder,
8c0a7f91
KZ
3235
3236 .part_is_used = gpt_part_is_used,
c83f772e 3237 .part_toggle_flag = gpt_toggle_partition_flag,
4e0e8253 3238
1240f549
KZ
3239 .deinit = gpt_deinit,
3240
3241 .reset_alignment = gpt_reset_alignment
766d5156 3242};
0c5d095e 3243
bd85d11f 3244static const struct fdisk_field gpt_fields[] =
6941952e
KZ
3245{
3246 /* basic */
bd85d11f
KZ
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 },
bd85d11f
KZ
3251 { FDISK_FIELD_SIZE, N_("Size"), 5, FDISK_FIELDFL_NUMBER | FDISK_FIELDFL_EYECANDY },
3252 { FDISK_FIELD_TYPE, N_("Type"), 0.1, FDISK_FIELDFL_EYECANDY },
6941952e 3253 /* expert */
bd85d11f
KZ
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 }
6941952e
KZ
3258};
3259
0c5d095e
KZ
3260/*
3261 * allocates GPT in-memory stuff
3262 */
01aec449 3263struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt __attribute__ ((__unused__)))
0c5d095e
KZ
3264{
3265 struct fdisk_label *lb;
3266 struct fdisk_gpt_label *gpt;
3267
0c5d095e
KZ
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";
53b422ab 3275 lb->id = FDISK_DISKLABEL_GPT;
0c5d095e 3276 lb->op = &gpt_operations;
f94e753b 3277
0c5d095e
KZ
3278 lb->parttypes = gpt_parttypes;
3279 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
f94e753b
KZ
3280 lb->parttype_cuts = gpt_parttype_cuts;
3281 lb->nparttype_cuts = ARRAY_SIZE(gpt_parttype_cuts);
0c5d095e 3282
bd85d11f
KZ
3283 lb->fields = gpt_fields;
3284 lb->nfields = ARRAY_SIZE(gpt_fields);
6941952e 3285
fe7ef272
KZ
3286 /* return calloc() result to keep static anaylizers happy */
3287 return (struct fdisk_label *) gpt;
0c5d095e 3288}
4a4a0927 3289
387ac277
KZ
3290/**
3291 * fdisk_gpt_disable_relocation
b7c015d1 3292 * @lb: label
387ac277
KZ
3293 * @disable: 0 or 1
3294 *
3295 * Disable automatic backup header relocation to the end of the device. The
aa1c7a76 3296 * header position is recalculated during libfdisk probing stage by
387ac277
KZ
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
b7c015d1
KZ
3312 * @lb: label
3313 * @enable: 0 or 1
387ac277
KZ
3314 *
3315 * Force libfdisk to write backup header to behind last partition. The
aa1c7a76 3316 * header position is recalculated on fdisk_write_disklabel().
387ac277
KZ
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
4a4a0927 3328#ifdef TEST_PROGRAM
2a472ae8
TW
3329static int test_getattr(struct fdisk_test *ts __attribute__((unused)),
3330 int argc, char *argv[])
4a4a0927 3331{
2a472ae8
TW
3332 if (argc != 3)
3333 return -1;
3334
4a4a0927
MM
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
2a472ae8
TW
3355static int test_setattr(struct fdisk_test *ts __attribute__((unused)),
3356 int argc, char *argv[])
4a4a0927 3357{
2a472ae8
TW
3358 if (argc != 4)
3359 return -1;
3360
4a4a0927
MM
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