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