]> git.ipfire.org Git - thirdparty/util-linux.git/blame - libfdisk/src/gpt.c
libfdisk: extend fdisk_info() functionality
[thirdparty/util-linux.git] / libfdisk / src / gpt.c
CommitLineData
5dbff4c0 1/*
766d5156
DB
2 * Copyright (C) 2007 Karel Zak <kzak@redhat.com>
3 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
4 *
5 * GUID Partition Table (GPT) support. Based on UEFI Specs 2.3.1
6 * Chapter 5: GUID Partition Table (GPT) Disk Layout (Jun 27th, 2012).
7 * Some ideas and inspiration from GNU parted and gptfdisk.
5dbff4c0 8 */
5dbff4c0
KZ
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <inttypes.h>
13#include <sys/stat.h>
5dbff4c0
KZ
14#include <sys/utsname.h>
15#include <sys/types.h>
16#include <fcntl.h>
17#include <unistd.h>
18#include <errno.h>
766d5156
DB
19#include <ctype.h>
20#include <uuid.h>
5dbff4c0 21
62d50bbe
KZ
22#include "fdiskP.h"
23
766d5156 24#include "nls.h"
766d5156 25#include "crc32.h"
810f986b 26#include "blkdev.h"
9eca9d0d 27#include "bitops.h"
766d5156 28#include "strutils.h"
19613111 29#include "all-io.h"
766d5156
DB
30
31#define GPT_HEADER_SIGNATURE 0x5452415020494645LL /* EFI PART */
32#define GPT_HEADER_REVISION_V1_02 0x00010200
33#define GPT_HEADER_REVISION_V1_00 0x00010000
34#define GPT_HEADER_REVISION_V0_99 0x00009900
e9bf0935 35#define GPT_HEADER_MINSZ 92 /* bytes */
766d5156
DB
36
37#define GPT_PMBR_LBA 0
38#define GPT_MBR_PROTECTIVE 1
39#define GPT_MBR_HYBRID 2
40
41#define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001
42
43#define EFI_PMBR_OSTYPE 0xEE
44#define MSDOS_MBR_SIGNATURE 0xAA55
3f731001
DB
45#define GPT_PART_NAME_LEN 72 / sizeof(uint16_t)
46#define GPT_NPARTITIONS 128
766d5156
DB
47
48/* Globally unique identifier */
49struct gpt_guid {
50 uint32_t time_low;
51 uint16_t time_mid;
52 uint16_t time_hi_and_version;
53 uint8_t clock_seq_hi;
54 uint8_t clock_seq_low;
55 uint8_t node[6];
56};
57
58
59/* only checking that the GUID is 0 is enough to verify an empty partition. */
60#define GPT_UNUSED_ENTRY_GUID \
61 ((struct gpt_guid) { 0x00000000, 0x0000, 0x0000, 0x00, 0x00, \
62 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }})
63
64/* Linux native partition type */
c0d14b09 65#define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
766d5156
DB
66
67/*
68 * Attribute bits
69 */
70struct gpt_attr {
71 uint64_t required_to_function:1;
72 uint64_t no_blockio_protocol:1;
73 uint64_t legacy_bios_bootable:1;
74 uint64_t reserved:45;
75 uint64_t guid_secific:16;
76} __attribute__ ((packed));
77
78/* The GPT Partition entry array contains an array of GPT entries. */
79struct gpt_entry {
d45fa25d
KZ
80 struct gpt_guid type; /* purpose and type of the partition */
81 struct gpt_guid partition_guid;
766d5156
DB
82 uint64_t lba_start;
83 uint64_t lba_end;
84 struct gpt_attr attr;
d45fa25d 85 uint16_t name[GPT_PART_NAME_LEN];
766d5156
DB
86} __attribute__ ((packed));
87
88/* GPT header */
89struct gpt_header {
90 uint64_t signature; /* header identification */
91 uint32_t revision; /* header version */
92 uint32_t size; /* in bytes */
93 uint32_t crc32; /* header CRC checksum */
94 uint32_t reserved1; /* must be 0 */
95 uint64_t my_lba; /* LBA that contains this struct (LBA 1) */
96 uint64_t alternative_lba; /* backup GPT header */
97 uint64_t first_usable_lba; /* first usable logical block for partitions */
98 uint64_t last_usable_lba; /* last usable logical block for partitions */
3f731001 99 struct gpt_guid disk_guid; /* unique disk identifier */
766d5156
DB
100 uint64_t partition_entry_lba; /* stat LBA of the partition entry array */
101 uint32_t npartition_entries; /* total partition entries - normally 128 */
102 uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
103 uint32_t partition_entry_array_crc32; /* partition CRC checksum */
104 uint8_t reserved2[512 - 92]; /* must be 0 */
105} __attribute__ ((packed));
106
107struct gpt_record {
108 uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
109 uint8_t start_head; /* unused by EFI, pt start in CHS */
110 uint8_t start_sector; /* unused by EFI, pt start in CHS */
111 uint8_t start_track;
112 uint8_t os_type; /* EFI and legacy non-EFI OS types */
113 uint8_t end_head; /* unused by EFI, pt end in CHS */
114 uint8_t end_sector; /* unused by EFI, pt end in CHS */
115 uint8_t end_track; /* unused by EFI, pt end in CHS */
116 uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
117 uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
118} __attribute__ ((packed));
119
120/* Protected MBR and legacy MBR share same structure */
121struct gpt_legacy_mbr {
122 uint8_t boot_code[440];
123 uint32_t unique_mbr_signature;
124 uint16_t unknown;
125 struct gpt_record partition_record[4];
126 uint16_t signature;
127} __attribute__ ((packed));
128
129/*
130 * Here be dragons!
131 * See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
132 */
133#define DEF_GUID(_u, _n) \
134 { \
135 .typestr = (_u), \
136 .name = (_n), \
137 }
138
139static struct fdisk_parttype gpt_parttypes[] =
140{
141 /* Generic OS */
142 DEF_GUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", N_("EFI System")),
143
144 DEF_GUID("024DEE41-33E7-11D3-9D69-0008C781F39F", N_("MBR partition scheme")),
145 /* Hah!IdontneedEFI */
146 DEF_GUID("21686148-6449-6E6F-744E-656564454649", N_("BIOS boot partition")),
147
148 /* Windows */
149 DEF_GUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE", N_("Microsoft reserved")),
150 DEF_GUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", N_("Microsoft basic data")),
151 DEF_GUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3", N_("Microsoft LDM metadata")),
152 DEF_GUID("AF9B60A0-1431-4F62-BC68-3311714A69AD", N_("Microsoft LDM data")),
ef75bc88 153 DEF_GUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC", N_("Windows recovery evironment")),
766d5156
DB
154 DEF_GUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174", N_("IBM General Parallel Fs")),
155
156 /* HP-UX */
157 DEF_GUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000", N_("HP-UX data partition")),
158 DEF_GUID("E2A1E728-32E3-11D6-A682-7B03A0000000", N_("HP-UX service partition")),
159
160 /* Linux */
161 DEF_GUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4", N_("Linux filesystem")),
162 DEF_GUID("A19D880F-05FC-4D3B-A006-743F0F84911E", N_("Linux RAID")),
163 DEF_GUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", N_("Linux swap")),
164 DEF_GUID("E6D6D379-F507-44C2-A23C-238F2A3DF928", N_("Linux LVM")),
165 DEF_GUID("8DA63339-0007-60C0-C436-083AC8230908", N_("Linux reserved")),
166
e9bf0935 167 /* FreeBSD */
766d5156
DB
168 DEF_GUID("516E7CB4-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD data")),
169 DEF_GUID("83BD6B9D-7F41-11DC-BE0B-001560B84F0F", N_("FreeBSD boot")),
170 DEF_GUID("516E7CB5-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD swap")),
171 DEF_GUID("516E7CB6-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD UFS")),
172 DEF_GUID("516E7CBA-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD ZFS")),
173 DEF_GUID("516E7CB8-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD Vinum")),
174
175 /* Apple OSX */
176 DEF_GUID("48465300-0000-11AA-AA11-00306543ECAC", N_("Apple HFS/HFS+")),
177 DEF_GUID("55465300-0000-11AA-AA11-00306543ECAC", N_("Apple UFS")),
178 DEF_GUID("52414944-0000-11AA-AA11-00306543ECAC", N_("Apple RAID")),
179 DEF_GUID("52414944-5F4F-11AA-AA11-00306543ECAC", N_("Apple RAID offline")),
180 DEF_GUID("426F6F74-0000-11AA-AA11-00306543ECAC", N_("Apple boot")),
181 DEF_GUID("4C616265-6C00-11AA-AA11-00306543ECAC", N_("Apple label")),
182 DEF_GUID("5265636F-7665-11AA-AA11-00306543ECAC", N_("Apple TV recovery")),
183 DEF_GUID("53746F72-6167-11AA-AA11-00306543ECAC", N_("Apple Core storage")),
184
185 /* Solaris */
186 DEF_GUID("6A82CB45-1DD2-11B2-99A6-080020736631", N_("Solaris boot")),
187 DEF_GUID("6A85CF4D-1DD2-11B2-99A6-080020736631", N_("Solaris root")),
188 /* same as Apple ZFS */
189 DEF_GUID("6A898CC3-1DD2-11B2-99A6-080020736631", N_("Solaris /usr & Apple ZFS")),
190 DEF_GUID("6A87C46F-1DD2-11B2-99A6-080020736631", N_("Solaris swap")),
191 DEF_GUID("6A8B642B-1DD2-11B2-99A6-080020736631", N_("Solaris backup")),
192 DEF_GUID("6A8EF2E9-1DD2-11B2-99A6-080020736631", N_("Solaris /var")),
193 DEF_GUID("6A90BA39-1DD2-11B2-99A6-080020736631", N_("Solaris /home")),
194 DEF_GUID("6A9283A5-1DD2-11B2-99A6-080020736631", N_("Solaris alternate sector")),
195 DEF_GUID("6A945A3B-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 1")),
196 DEF_GUID("6A9630D1-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 2")),
197 DEF_GUID("6A980767-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 3")),
198 DEF_GUID("6A96237F-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 4")),
199 DEF_GUID("6A8D2AC7-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 5")),
200
201 /* NetBSD */
202 DEF_GUID("49F48D32-B10E-11DC-B99B-0019D1879648", N_("NetBSD swap")),
203 DEF_GUID("49F48D5A-B10E-11DC-B99B-0019D1879648", N_("NetBSD FFS")),
204 DEF_GUID("49F48D82-B10E-11DC-B99B-0019D1879648", N_("NetBSD LFS")),
205 DEF_GUID("2DB519C4-B10E-11DC-B99B-0019D1879648", N_("NetBSD concatenated")),
206 DEF_GUID("2DB519EC-B10E-11DC-B99B-0019D1879648", N_("NetBSD encrypted")),
207 DEF_GUID("49F48DAA-B10E-11DC-B99B-0019D1879648", N_("NetBSD RAID")),
208
209 /* ChromeOS */
210 DEF_GUID("FE3A2A5D-4F32-41A7-B725-ACCC3285A309", N_("ChromeOS kernel")),
211 DEF_GUID("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC", N_("ChromeOS root fs")),
212 DEF_GUID("2E0A753D-9E48-43B0-8337-B15192CB1B5E", N_("ChromeOS reserved")),
213
214 /* MidnightBSD */
215 DEF_GUID("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD data")),
216 DEF_GUID("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD boot")),
217 DEF_GUID("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD swap")),
218 DEF_GUID("0394Ef8B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD UFS")),
219 DEF_GUID("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD ZFS")),
220 DEF_GUID("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD Vinum")),
221};
222
d71ef5a4 223/* gpt_entry macros */
874aa9c3
KZ
224#define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
225#define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
226
d71ef5a4
KZ
227/*
228 * in-memory fdisk GPT stuff
229 */
230struct fdisk_gpt_label {
231 struct fdisk_label head; /* generic part */
232
233 /* gpt specific part */
234 struct gpt_header *pheader; /* primary header */
235 struct gpt_header *bheader; /* backup header */
236 struct gpt_entry *ents; /* entries (partitions) */
237};
238
239static void gpt_deinit(struct fdisk_label *lb);
240
9ffeb235 241static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
d71ef5a4 242{
d71ef5a4
KZ
243 return (struct fdisk_gpt_label *) cxt->label;
244}
245
874aa9c3
KZ
246/*
247 * Returns the partition length, or 0 if end is before beginning.
248 */
249static uint64_t gpt_partition_size(const struct gpt_entry *e)
250{
251 uint64_t start = gpt_partition_start(e);
252 uint64_t end = gpt_partition_end(e);
253
254 return start > end ? 0 : end - start + 1ULL;
255}
256
c0d14b09
KZ
257#ifdef CONFIG_LIBFDISK_DEBUG
258/* prints UUID in the real byte order! */
259static void dbgprint_uuid(const char *mesg, struct gpt_guid *guid)
260{
261 const unsigned char *uuid = (unsigned char *) guid;
262
263 fprintf(stderr, "%s: "
264 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
265 mesg,
266 uuid[0], uuid[1], uuid[2], uuid[3],
267 uuid[4], uuid[5],
268 uuid[6], uuid[7],
269 uuid[8], uuid[9],
270 uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
271}
272#endif
273
766d5156
DB
274/*
275 * UUID is traditionally 16 byte big-endian array, except Intel EFI
276 * specification where the UUID is a structure of little-endian fields.
277 */
278static void swap_efi_guid(struct gpt_guid *uid)
279{
280 uid->time_low = swab32(uid->time_low);
281 uid->time_mid = swab16(uid->time_mid);
282 uid->time_hi_and_version = swab16(uid->time_hi_and_version);
5dbff4c0
KZ
283}
284
c0d14b09 285static int string_to_guid(const char *in, struct gpt_guid *guid)
766d5156 286{
c0d14b09 287 if (uuid_parse(in, (unsigned char *) guid)) /* BE */
766d5156 288 return -1;
c0d14b09 289 swap_efi_guid(guid); /* LE */
766d5156
DB
290 return 0;
291}
292
c0d14b09 293static char *guid_to_string(struct gpt_guid *guid, char *out)
766d5156 294{
c0d14b09
KZ
295 struct gpt_guid u = *guid; /* LE */
296
297 swap_efi_guid(&u); /* BE */
298 uuid_unparse_upper((unsigned char *) &u, out);
299
46667ba4 300 return out;
766d5156
DB
301}
302
303static const char *gpt_get_header_revstr(struct gpt_header *header)
304{
305 if (!header)
306 goto unknown;
307
308 switch (header->revision) {
309 case GPT_HEADER_REVISION_V1_02:
310 return "1.2";
311 case GPT_HEADER_REVISION_V1_00:
312 return "1.0";
313 case GPT_HEADER_REVISION_V0_99:
314 return "0.99";
315 default:
316 goto unknown;
317 }
318
319unknown:
320 return "unknown";
321}
322
874aa9c3 323static inline int partition_unused(const struct gpt_entry *e)
766d5156 324{
d45fa25d 325 return !memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
766d5156
DB
326 sizeof(struct gpt_guid));
327}
328
3f731001
DB
329/*
330 * Builds a clean new valid protective MBR - will wipe out any existing data.
331 * Returns 0 on success, otherwise < 0 on error.
332 */
333static int gpt_mknew_pmbr(struct fdisk_context *cxt)
334{
335 struct gpt_legacy_mbr *pmbr = NULL;
336
337 if (!cxt || !cxt->firstsector)
338 return -ENOSYS;
339
340 fdisk_zeroize_firstsector(cxt);
341
342 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
343
344 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
345 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
346 pmbr->partition_record[0].start_sector = 1;
347 pmbr->partition_record[0].end_head = 0xFE;
348 pmbr->partition_record[0].end_sector = 0xFF;
349 pmbr->partition_record[0].end_track = 0xFF;
350 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
351 pmbr->partition_record[0].size_in_lba =
352 cpu_to_le32(min((uint32_t) cxt->total_sectors - 1, 0xFFFFFFFF));
353
354 return 0;
355}
356
357/* some universal differences between the headers */
358static void gpt_mknew_header_common(struct fdisk_context *cxt,
359 struct gpt_header *header, uint64_t lba)
360{
361 if (!cxt || !header)
362 return;
363
364 header->my_lba = cpu_to_le64(lba);
365
366 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) { /* primary */
367 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1);
368 header->partition_entry_lba = cpu_to_le64(2);
369 } else { /* backup */
370 uint64_t esz = le32_to_cpu(header->npartition_entries) * sizeof(struct gpt_entry);
371 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
372
373 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
374 header->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1 - esects);
375 }
376}
377
378/*
379 * Builds a new GPT header (at sector lba) from a backup header2.
380 * If building a primary header, then backup is the secondary, and vice versa.
381 *
382 * Always pass a new (zeroized) header to build upon as we don't
383 * explicitly zero-set some values such as CRCs and reserved.
384 *
385 * Returns 0 on success, otherwise < 0 on error.
386 */
387static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
388 struct gpt_header *header,
389 uint64_t lba,
390 struct gpt_header *header2)
391{
392 if (!cxt || !header || !header2)
393 return -ENOSYS;
394
395 header->signature = header2->signature;
396 header->revision = header2->revision;
397 header->size = header2->size;
398 header->npartition_entries = header2->npartition_entries;
399 header->sizeof_partition_entry = header2->sizeof_partition_entry;
400 header->first_usable_lba = header2->first_usable_lba;
401 header->last_usable_lba = header2->last_usable_lba;
402
403 memcpy(&header->disk_guid,
404 &header2->disk_guid, sizeof(header2->disk_guid));
405 gpt_mknew_header_common(cxt, header, lba);
406
407 return 0;
408}
409
410/*
411 * Builds a clean new GPT header (currently under revision 1.0).
412 *
413 * Always pass a new (zeroized) header to build upon as we don't
414 * explicitly zero-set some values such as CRCs and reserved.
415 *
416 * Returns 0 on success, otherwise < 0 on error.
417 */
418static int gpt_mknew_header(struct fdisk_context *cxt,
419 struct gpt_header *header, uint64_t lba)
420{
b4184690 421 uint64_t esz = 0, first, last;
3f731001
DB
422
423 if (!cxt || !header)
424 return -ENOSYS;
425
426 esz = sizeof(struct gpt_entry) * GPT_NPARTITIONS / cxt->sector_size;
427
428 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
429 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
430 header->size = cpu_to_le32(sizeof(struct gpt_header));
431
432 /*
433 * 128 partitions is the default. It can go behond this, however,
434 * we're creating a de facto header here, so no funny business.
435 */
436 header->npartition_entries = cpu_to_le32(GPT_NPARTITIONS);
437 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
b4184690
KZ
438
439 last = cxt->total_sectors - 2 - esz;
440 first = esz + 2;
441
442 if (first < cxt->first_lba && cxt->first_lba < last)
443 /* Align according to topology */
444 first = cxt->first_lba;
445
446 header->first_usable_lba = cpu_to_le64(first);
447 header->last_usable_lba = cpu_to_le64(last);
3f731001
DB
448
449 gpt_mknew_header_common(cxt, header, lba);
450 uuid_generate_random((unsigned char *) &header->disk_guid);
451 swap_efi_guid(&header->disk_guid);
452
453 return 0;
454}
455
766d5156
DB
456/*
457 * Checks if there is a valid protective MBR partition table.
458 * Returns 0 if it is invalid or failure. Otherwise, return
459 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depeding on the detection.
460 */
461static int valid_pmbr(struct fdisk_context *cxt)
462{
879fadf1 463 int i, part = 0, ret = 0; /* invalid by default */
766d5156
DB
464 struct gpt_legacy_mbr *pmbr = NULL;
465
466 if (!cxt->firstsector)
467 goto done;
468
469 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
470
f67c524e 471 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
766d5156
DB
472 goto done;
473
474 /* LBA of the GPT partition header */
475 if (pmbr->partition_record[0].starting_lba !=
476 cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
477 goto done;
478
479 /* seems like a valid MBR was found, check DOS primary partitions */
f67c524e 480 for (i = 0; i < 4; i++) {
766d5156
DB
481 if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
482 /*
483 * Ok, we at least know that there's a protective MBR,
484 * now check if there are other partition types for
485 * hybrid MBR.
486 */
879fadf1 487 part = i;
766d5156
DB
488 ret = GPT_MBR_PROTECTIVE;
489 goto check_hybrid;
490 }
f67c524e 491 }
766d5156
DB
492check_hybrid:
493 if (ret != GPT_MBR_PROTECTIVE)
494 goto done;
f67c524e 495 for (i = 0 ; i < 4; i++) {
766d5156
DB
496 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
497 (pmbr->partition_record[i].os_type != 0x00))
498 ret = GPT_MBR_HYBRID;
f67c524e 499 }
766d5156
DB
500
501 /*
502 * Protective MBRs take up the lesser of the whole disk
503 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
504 *
505 * Hybrid MBRs do not necessarily comply with this.
506 */
f67c524e 507 if (ret == GPT_MBR_PROTECTIVE) {
879fadf1 508 if (le32_to_cpu(pmbr->partition_record[part].size_in_lba) !=
f67c524e 509 min((uint32_t) cxt->total_sectors - 1, 0xFFFFFFFF))
766d5156 510 ret = 0;
f67c524e 511 }
766d5156
DB
512done:
513 return ret;
514}
515
516static uint64_t last_lba(struct fdisk_context *cxt)
5dbff4c0 517{
5dbff4c0
KZ
518 struct stat s;
519
766d5156
DB
520 memset(&s, 0, sizeof(s));
521 if (fstat(cxt->dev_fd, &s) == -1) {
83df5feb 522 fdisk_warn(cxt, _("gpt: stat() failed"));
5dbff4c0
KZ
523 return 0;
524 }
766d5156 525
5dbff4c0 526 if (S_ISBLK(s.st_mode))
766d5156
DB
527 return cxt->total_sectors - 1;
528 else if (S_ISREG(s.st_mode)) {
529 uint64_t sectors = s.st_size >> cxt->sector_size;
530 return (sectors / cxt->sector_size) - 1ULL;
83df5feb
KZ
531 } else
532 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
766d5156 533 return 0;
5dbff4c0
KZ
534}
535
766d5156
DB
536static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
537 void *buffer, const size_t bytes)
5dbff4c0 538{
766d5156 539 off_t offset = lba * cxt->sector_size;
5dbff4c0 540
bbe8e6a9
KZ
541 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
542 return -1;
543 return read(cxt->dev_fd, buffer, bytes) != bytes;
5dbff4c0
KZ
544}
545
766d5156
DB
546
547/* Returns the GPT entry array */
be5f8061 548static struct gpt_entry *gpt_read_entries(struct fdisk_context *cxt,
d71ef5a4 549 struct gpt_header *header)
5dbff4c0 550{
d71ef5a4
KZ
551 ssize_t sz;
552 struct gpt_entry *ret = NULL;
553 off_t offset;
554
555 assert(cxt);
556 assert(header);
557
558 sz = le32_to_cpu(header->npartition_entries) *
559 le32_to_cpu(header->sizeof_partition_entry);
560
46667ba4 561 ret = calloc(1, sz);
d71ef5a4
KZ
562 if (!ret)
563 return NULL;
564 offset = le64_to_cpu(header->partition_entry_lba) *
766d5156
DB
565 cxt->sector_size;
566
567 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
d71ef5a4 568 goto fail;
766d5156 569 if (sz != read(cxt->dev_fd, ret, sz))
d71ef5a4 570 goto fail;
766d5156
DB
571
572 return ret;
d71ef5a4
KZ
573
574fail:
575 free(ret);
576 return NULL;
766d5156
DB
577}
578
579static inline uint32_t count_crc32(const unsigned char *buf, size_t len)
580{
581 return (crc32(~0L, buf, len) ^ ~0L);
582}
583
584/*
585 * Recompute header and partition array 32bit CRC checksums.
586 * This function does not fail - if there's corruption, then it
587 * will be reported when checksuming it again (ie: probing or verify).
588 */
d71ef5a4 589static void gpt_recompute_crc(struct gpt_header *header, struct gpt_entry *ents)
766d5156
DB
590{
591 uint32_t crc = 0;
592 size_t entry_sz = 0;
593
594 if (!header)
595 return;
596
597 /* header CRC */
598 header->crc32 = 0;
599 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
600 header->crc32 = cpu_to_le32(crc);
601
602 /* partition entry array CRC */
603 header->partition_entry_array_crc32 = 0;
604 entry_sz = le32_to_cpu(header->npartition_entries) *
605 le32_to_cpu(header->sizeof_partition_entry);
606
d71ef5a4 607 crc = count_crc32((unsigned char *) ents, entry_sz);
766d5156
DB
608 header->partition_entry_array_crc32 = cpu_to_le32(crc);
609}
610
611/*
612 * Compute the 32bit CRC checksum of the partition table header.
613 * Returns 1 if it is valid, otherwise 0.
614 */
d71ef5a4 615static int gpt_check_header_crc(struct gpt_header *header, struct gpt_entry *ents)
766d5156
DB
616{
617 uint32_t crc, orgcrc = le32_to_cpu(header->crc32);
618
619 header->crc32 = 0;
620 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
621 header->crc32 = cpu_to_le32(orgcrc);
622
d71ef5a4
KZ
623 if (crc == le32_to_cpu(header->crc32))
624 return 1;
625
766d5156
DB
626 /*
627 * If we have checksum mismatch it may be due to stale data,
628 * like a partition being added or deleted. Recompute the CRC again
629 * and make sure this is not the case.
630 */
d71ef5a4 631 if (ents) {
766d5156
DB
632 gpt_recompute_crc(header, ents);
633 orgcrc = le32_to_cpu(header->crc32);
634 header->crc32 = 0;
635 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
636 header->crc32 = cpu_to_le32(orgcrc);
637
638 return crc == le32_to_cpu(header->crc32);
d71ef5a4
KZ
639 }
640
641 return 0;
766d5156
DB
642}
643
644/*
645 * It initializes the partition entry array.
646 * Returns 1 if the checksum is valid, otherwise 0.
647 */
d71ef5a4
KZ
648static int gpt_check_entryarr_crc(struct gpt_header *header,
649 struct gpt_entry *ents)
766d5156
DB
650{
651 int ret = 0;
652 ssize_t entry_sz;
653 uint32_t crc;
654
d71ef5a4 655 if (!header || !ents)
766d5156
DB
656 goto done;
657
658 entry_sz = le32_to_cpu(header->npartition_entries) *
659 le32_to_cpu(header->sizeof_partition_entry);
660
661 if (!entry_sz)
662 goto done;
663
766d5156
DB
664 crc = count_crc32((unsigned char *) ents, entry_sz);
665 ret = (crc == le32_to_cpu(header->partition_entry_array_crc32));
666done:
667 return ret;
668}
669
670static int gpt_check_lba_sanity(struct fdisk_context *cxt, struct gpt_header *header)
671{
672 int ret = 0;
673 uint64_t lu, fu, lastlba = last_lba(cxt);
674
675 fu = le64_to_cpu(header->first_usable_lba);
676 lu = le64_to_cpu(header->last_usable_lba);
677
678 /* check if first and last usable LBA make sense */
679 if (lu < fu) {
680 DBG(LABEL, dbgprint("error: header last LBA is before first LBA"));
681 goto done;
5dbff4c0 682 }
766d5156
DB
683
684 /* check if first and last usable LBAs with the disk's last LBA */
685 if (fu > lastlba || lu > lastlba) {
686 DBG(LABEL, dbgprint("error: header LBAs are after the disk's last LBA"));
687 goto done;
688 }
689
690 /* the header has to be outside usable range */
691 if (fu < GPT_PRIMARY_PARTITION_TABLE_LBA &&
692 GPT_PRIMARY_PARTITION_TABLE_LBA < lu) {
693 DBG(LABEL, dbgprint("error: header outside of usable range"));
694 goto done;
695 }
696
697 ret = 1; /* sane */
698done:
699 return ret;
700}
701
702/* Check if there is a valid header signature */
703static int gpt_check_signature(struct gpt_header *header)
704{
705 return header->signature == cpu_to_le64(GPT_HEADER_SIGNATURE);
706}
707
708/*
709 * Return the specified GPT Header, or NULL upon failure/invalid.
710 * Note that all tests must pass to ensure a valid header,
711 * we do not rely on only testing the signature for a valid probe.
712 */
d71ef5a4
KZ
713static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
714 uint64_t lba,
715 struct gpt_entry **_ents)
766d5156
DB
716{
717 struct gpt_header *header = NULL;
d71ef5a4 718 struct gpt_entry *ents = NULL;
e9bf0935 719 uint32_t hsz;
766d5156
DB
720
721 if (!cxt)
722 return NULL;
723
46667ba4
KZ
724 header = calloc(1, sizeof(*header));
725 if (!header)
726 return NULL;
766d5156 727
d71ef5a4 728 /* read and verify header */
bbe8e6a9 729 if (read_lba(cxt, lba, header, sizeof(struct gpt_header)) != 0)
766d5156
DB
730 goto invalid;
731
732 if (!gpt_check_signature(header))
733 goto invalid;
734
d71ef5a4
KZ
735 if (!gpt_check_header_crc(header, NULL))
736 goto invalid;
737
738 /* read and verify entries */
739 ents = gpt_read_entries(cxt, header);
740 if (!ents)
741 goto invalid;
742
743 if (!gpt_check_entryarr_crc(header, ents))
766d5156
DB
744 goto invalid;
745
746 if (!gpt_check_lba_sanity(cxt, header))
747 goto invalid;
748
749 /* valid header must be at MyLBA */
750 if (le64_to_cpu(header->my_lba) != lba)
751 goto invalid;
752
e9bf0935
DB
753 /* make sure header size is between 92 and sector size bytes */
754 hsz = le32_to_cpu(header->size);
755 if (hsz < GPT_HEADER_MINSZ || hsz > cxt->sector_size)
756 goto invalid;
757
d71ef5a4
KZ
758 if (_ents)
759 *_ents = ents;
760 else
761 free(ents);
762
766d5156
DB
763 return header;
764invalid:
765 free(header);
d71ef5a4 766 free(ents);
766d5156
DB
767 return NULL;
768}
769
766d5156
DB
770/*
771 * Returns the number of partitions that are in use.
772 */
130820a8 773static unsigned partitions_in_use(struct gpt_header *header, struct gpt_entry *e)
766d5156
DB
774{
775 uint32_t i, used = 0;
776
777 if (!header || ! e)
778 return 0;
779
780 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
874aa9c3 781 if (!partition_unused(&e[i]))
766d5156
DB
782 used++;
783 return used;
784}
785
766d5156
DB
786
787/*
788 * Check if a partition is too big for the disk (sectors).
789 * Returns the faulting partition number, otherwise 0.
790 */
83df5feb 791static uint32_t partition_check_too_big(struct gpt_header *header,
766d5156
DB
792 struct gpt_entry *e, uint64_t sectors)
793{
794 uint32_t i;
795
796 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3 797 if (partition_unused(&e[i]))
766d5156 798 continue;
874aa9c3 799 if (gpt_partition_end(&e[i]) >= sectors)
766d5156 800 return i + 1;
5dbff4c0 801 }
766d5156
DB
802
803 return 0;
5dbff4c0
KZ
804}
805
766d5156
DB
806/*
807 * Check if a partition ends before it begins
808 * Returns the faulting partition number, otherwise 0.
5dbff4c0 809 */
83df5feb 810static uint32_t partition_start_after_end(struct gpt_header *header, struct gpt_entry *e)
5dbff4c0 811{
766d5156 812 uint32_t i;
5dbff4c0 813
766d5156 814 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3 815 if (partition_unused(&e[i]))
766d5156 816 continue;
874aa9c3 817 if (gpt_partition_start(&e[i]) > gpt_partition_end(&e[i]))
766d5156 818 return i + 1;
5dbff4c0 819 }
766d5156
DB
820
821 return 0;
5dbff4c0
KZ
822}
823
766d5156
DB
824/*
825 * Check if partition e1 overlaps with partition e2
826 */
874aa9c3 827static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
5dbff4c0 828{
874aa9c3
KZ
829 uint64_t start1 = gpt_partition_start(e1);
830 uint64_t end1 = gpt_partition_end(e1);
831 uint64_t start2 = gpt_partition_start(e2);
832 uint64_t end2 = gpt_partition_end(e2);
833
834 return (start1 && start2 && (start1 <= end2) != (end1 < start2));
766d5156
DB
835}
836
837/*
838 * Find any paritions that overlap.
839 */
83df5feb 840static uint32_t partition_check_overlaps(struct gpt_header *header, struct gpt_entry *e)
766d5156
DB
841{
842 uint32_t i, j;
843
844 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
845 for (j = 0; j < i; j++) {
874aa9c3
KZ
846 if (partition_unused(&e[i]) ||
847 partition_unused(&e[j]))
766d5156 848 continue;
c15aec86
KZ
849 if (partition_overlap(&e[i], &e[j])) {
850 DBG(LABEL, dbgprint("GPT partitions overlap detected [%u vs. %u]", i, j));
766d5156 851 return i + 1;
c15aec86 852 }
766d5156
DB
853 }
854
855 return 0;
856}
857
858/*
859 * Find the first available block after the starting point; returns 0 if
860 * there are no available blocks left, or error. From gdisk.
861 */
862static uint64_t find_first_available(struct gpt_header *header,
863 struct gpt_entry *e, uint64_t start)
864{
865 uint64_t first;
866 uint32_t i, first_moved = 0;
867
602ebe7d
KZ
868 uint64_t fu, lu;
869
766d5156 870 if (!header || !e)
5dbff4c0 871 return 0;
766d5156 872
602ebe7d
KZ
873 fu = le64_to_cpu(header->first_usable_lba);
874 lu = le64_to_cpu(header->last_usable_lba);
875
766d5156
DB
876 /*
877 * Begin from the specified starting point or from the first usable
878 * LBA, whichever is greater...
879 */
602ebe7d 880 first = start < fu ? fu : start;
766d5156
DB
881
882 /*
883 * Now search through all partitions; if first is within an
884 * existing partition, move it to the next sector after that
885 * partition and repeat. If first was moved, set firstMoved
886 * flag; repeat until firstMoved is not set, so as to catch
887 * cases where partitions are out of sequential order....
888 */
889 do {
890 first_moved = 0;
891 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3 892 if (partition_unused(&e[i]))
766d5156 893 continue;
874aa9c3 894 if (first < gpt_partition_start(&e[i]))
766d5156 895 continue;
874aa9c3
KZ
896 if (first <= gpt_partition_end(&e[i])) {
897 first = gpt_partition_end(&e[i]) + 1;
766d5156
DB
898 first_moved = 1;
899 }
900 }
901 } while (first_moved == 1);
902
602ebe7d 903 if (first > lu)
766d5156
DB
904 first = 0;
905
906 return first;
5dbff4c0
KZ
907}
908
766d5156
DB
909
910/* Returns last available sector in the free space pointed to by start. From gdisk. */
911static uint64_t find_last_free(struct gpt_header *header,
912 struct gpt_entry *e, uint64_t start)
5dbff4c0 913{
766d5156
DB
914 uint32_t i;
915 uint64_t nearest_start;
916
917 if (!header || !e)
918 return 0;
919
602ebe7d
KZ
920 nearest_start = le64_to_cpu(header->last_usable_lba);
921
766d5156 922 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
602ebe7d
KZ
923 uint64_t ps = gpt_partition_start(&e[i]);
924
925 if (nearest_start > ps && ps > start)
926 nearest_start = ps - 1;
5dbff4c0 927 }
766d5156
DB
928
929 return nearest_start;
5dbff4c0 930}
766d5156
DB
931
932/* Returns the last free sector on the disk. From gdisk. */
933static uint64_t find_last_free_sector(struct gpt_header *header,
934 struct gpt_entry *e)
935{
936 uint32_t i, last_moved;
937 uint64_t last = 0;
938
939 if (!header || !e)
940 goto done;
941
942 /* start by assuming the last usable LBA is available */
602ebe7d 943 last = le64_to_cpu(header->last_usable_lba);
766d5156
DB
944 do {
945 last_moved = 0;
946 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3
KZ
947 if ((last >= gpt_partition_start(&e[i])) &&
948 (last <= gpt_partition_end(&e[i]))) {
949 last = gpt_partition_start(&e[i]) - 1;
766d5156
DB
950 last_moved = 1;
951 }
952 }
953 } while (last_moved == 1);
954done:
955 return last;
956}
957
958/*
959 * Finds the first available sector in the largest block of unallocated
960 * space on the disk. Returns 0 if there are no available blocks left.
961 * From gdisk.
962 */
963static uint64_t find_first_in_largest(struct gpt_header *header, struct gpt_entry *e)
964{
965 uint64_t start = 0, first_sect, last_sect;
966 uint64_t segment_size, selected_size = 0, selected_segment = 0;
967
968 if (!header || !e)
969 goto done;
970
971 do {
972 first_sect = find_first_available(header, e, start);
973 if (first_sect != 0) {
974 last_sect = find_last_free(header, e, first_sect);
975 segment_size = last_sect - first_sect + 1;
976
977 if (segment_size > selected_size) {
978 selected_size = segment_size;
979 selected_segment = first_sect;
980 }
981 start = last_sect + 1;
982 }
983 } while (first_sect != 0);
984
985done:
986 return selected_segment;
987}
988
989/*
990 * Find the total number of free sectors, the number of segments in which
991 * they reside, and the size of the largest of those segments. From gdisk.
992 */
993static uint64_t get_free_sectors(struct fdisk_context *cxt, struct gpt_header *header,
994 struct gpt_entry *e, uint32_t *nsegments,
995 uint64_t *largest_segment)
996{
997 uint32_t num = 0;
998 uint64_t first_sect, last_sect;
999 uint64_t largest_seg = 0, segment_sz;
1000 uint64_t totfound = 0, start = 0; /* starting point for each search */
1001
1002 if (!cxt->total_sectors)
1003 goto done;
1004
1005 do {
1006 first_sect = find_first_available(header, e, start);
1007 if (first_sect) {
1008 last_sect = find_last_free(header, e, first_sect);
1009 segment_sz = last_sect - first_sect + 1;
1010
1011 if (segment_sz > largest_seg)
1012 largest_seg = segment_sz;
1013 totfound += segment_sz;
1014 num++;
1015 start = last_sect + 1;
1016 }
1017 } while (first_sect);
1018
1019done:
512a430f
KZ
1020 if (nsegments)
1021 *nsegments = num;
1022 if (largest_segment)
1023 *largest_segment = largest_seg;
766d5156
DB
1024
1025 return totfound;
1026}
1027
9ffeb235 1028static int gpt_probe_label(struct fdisk_context *cxt)
766d5156
DB
1029{
1030 int mbr_type;
9ffeb235 1031 struct fdisk_gpt_label *gpt;
766d5156 1032
9ffeb235
KZ
1033 assert(cxt);
1034 assert(cxt->label);
1035 assert(fdisk_is_disklabel(cxt, GPT));
1036
1037 gpt = self_label(cxt);
766d5156
DB
1038
1039 mbr_type = valid_pmbr(cxt);
1040 if (!mbr_type)
1041 goto failed;
1042
1043 DBG(LABEL, dbgprint("found a %s MBR", mbr_type == GPT_MBR_PROTECTIVE ?
1044 "protective" : "hybrid"));
1045
d71ef5a4
KZ
1046 /* primary header */
1047 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1048 &gpt->ents);
766d5156
DB
1049
1050 /*
1051 * TODO: If the primary GPT is corrupt, we must check the last LBA of the
1052 * device to see if it has a valid GPT Header and point to a valid GPT
1053 * Partition Entry Array.
1054 * If it points to a valid GPT Partition Entry Array, then software should
1055 * restore the primary GPT if allowed by platform policy settings.
1056 *
1057 * For now we just abort GPT probing!
1058 */
d71ef5a4 1059 if (!gpt->pheader || !gpt->ents)
766d5156
DB
1060 goto failed;
1061
1062 /* OK, probing passed, now initialize backup header and fdisk variables. */
d71ef5a4
KZ
1063 gpt->bheader = gpt_read_header(cxt, last_lba(cxt), NULL);
1064
9ffeb235
KZ
1065 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1066 cxt->label->nparts_cur = partitions_in_use(gpt->pheader, gpt->ents);
9fcd49d5 1067
83df5feb
KZ
1068 fdisk_warnx(cxt, _("WARNING: fdisk GPT support is currently new, and therefore "
1069 "in an experimental phase. Use at your own discretion."));
766d5156
DB
1070
1071 return 1;
1072failed:
4e0e8253 1073 DBG(LABEL, dbgprint("GPT probe failed"));
9ffeb235 1074 gpt_deinit(cxt->label);
766d5156
DB
1075 return 0;
1076}
1077
1078/*
1079 * Stolen from libblkid - can be removed once partition semantics
1080 * are added to the fdisk API.
1081 */
1082static char *encode_to_utf8(unsigned char *src, size_t count)
1083{
1084 uint16_t c;
d06f321d 1085 char *dest;
766d5156 1086 size_t i, j, len = count;
3f731001 1087
d06f321d
KZ
1088 dest = calloc(1, count);
1089 if (!dest)
1090 return NULL;
766d5156
DB
1091
1092 for (j = i = 0; i + 2 <= count; i += 2) {
1093 /* always little endian */
1094 c = (src[i+1] << 8) | src[i];
1095 if (c == 0) {
1096 dest[j] = '\0';
1097 break;
1098 } else if (c < 0x80) {
1099 if (j+1 >= len)
1100 break;
1101 dest[j++] = (uint8_t) c;
1102 } else if (c < 0x800) {
1103 if (j+2 >= len)
1104 break;
1105 dest[j++] = (uint8_t) (0xc0 | (c >> 6));
1106 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1107 } else {
1108 if (j+3 >= len)
1109 break;
1110 dest[j++] = (uint8_t) (0xe0 | (c >> 12));
1111 dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
1112 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1113 }
1114 }
1115 dest[j] = '\0';
1116
1117 return dest;
1118}
1119
1120/*
1121 * List label partitions.
1122 * This function must currently exist to comply with standard fdisk
1123 * requirements, but once partition semantics are added to the fdisk
1124 * API it can be removed for custom implementation (see gpt_label struct).
1125 */
3c5fb475 1126static int gpt_list_disklabel(struct fdisk_context *cxt)
766d5156 1127{
b1920e0b 1128 int rc, trunc = TT_FL_TRUNC;
766d5156 1129 uint32_t i;
9ffeb235 1130 struct fdisk_gpt_label *gpt;
76b3b13d 1131 struct gpt_header *h;
9ffeb235
KZ
1132 uint64_t fu;
1133 uint64_t lu;
d9948c37 1134 struct tt *tb = NULL;
9ffeb235
KZ
1135
1136 assert(cxt);
1137 assert(cxt->label);
1138 assert(fdisk_is_disklabel(cxt, GPT));
1139
1140 gpt = self_label(cxt);
76b3b13d 1141 h = gpt->pheader;
9ffeb235
KZ
1142 fu = le64_to_cpu(gpt->pheader->first_usable_lba);
1143 lu = le64_to_cpu(gpt->pheader->last_usable_lba);
766d5156 1144
d9948c37
KZ
1145 tb = tt_new_table(TT_FL_FREEDATA);
1146 if (!tb)
3c5fb475
KZ
1147 return -ENOMEM;
1148
b1920e0b 1149 /* don't trunc anything in expert mode */
76b3b13d 1150 if (fdisk_context_display_details(cxt)) {
b1920e0b 1151 trunc = 0;
76b3b13d
KZ
1152 fdisk_info(cxt, _("First LBA: %ju"), h->first_usable_lba);
1153 fdisk_info(cxt, _("Last LBA: %ju"), h->last_usable_lba);
1154 fdisk_info(cxt, _("Alternative LBA: %ju"), h->alternative_lba);
1155 fdisk_info(cxt, _("Partitions entries LBA: %ju"), h->partition_entry_lba);
1156 fdisk_info(cxt, _("Allocated partition entries: %ju"), h->npartition_entries);
1157 }
b1920e0b 1158 tt_define_column(tb, _("Device"), 0.1, 0);
9af7ed4e
KZ
1159 tt_define_column(tb, _("Start"), 12, TT_FL_RIGHT);
1160 tt_define_column(tb, _("End"), 12, TT_FL_RIGHT);
1161 tt_define_column(tb, _("Size"), 6, TT_FL_RIGHT);
b1920e0b
KZ
1162 tt_define_column(tb, _("Type"), 0.1, trunc);
1163
1164 if (fdisk_context_display_details(cxt)) {
1165 tt_define_column(tb, _("UUID"), 36, 0);
1166 tt_define_column(tb, _("Name"), 0.2, trunc);
1167 }
766d5156 1168
76b3b13d 1169 for (i = 0; i < le32_to_cpu(h->npartition_entries); i++) {
b1920e0b
KZ
1170 struct gpt_entry *e = &gpt->ents[i];
1171 char *sizestr = NULL, *p;
1172 uint64_t start = gpt_partition_start(e);
1173 uint64_t size = gpt_partition_size(e);
766d5156 1174 struct fdisk_parttype *t;
d9948c37 1175 struct tt_line *ln;
b1920e0b 1176 char u_str[37];
766d5156 1177
46667ba4 1178 if (partition_unused(&gpt->ents[i]) || start == 0)
766d5156 1179 continue;
766d5156
DB
1180 /* the partition has to inside usable range */
1181 if (start < fu || start + size - 1 > lu)
1182 continue;
d9948c37
KZ
1183 ln = tt_add_line(tb, NULL);
1184 if (!ln)
1185 continue;
766d5156 1186
b1920e0b
KZ
1187 if (fdisk_context_display_details(cxt) &&
1188 asprintf(&p, "%ju", size * cxt->sector_size) > 0)
1189 sizestr = p;
1190 else
1191 sizestr = size_to_human_string(SIZE_SUFFIX_1LETTER,
766d5156 1192 size * cxt->sector_size);
766d5156
DB
1193 t = fdisk_get_partition_type(cxt, i);
1194
b1920e0b 1195 /* basic columns */
aec8d883
KZ
1196 p = fdisk_partname(cxt->dev_path, i + 1);
1197 if (p)
d9948c37
KZ
1198 tt_line_set_data(ln, 0, p);
1199 if (asprintf(&p, "%ju", start) > 0)
1200 tt_line_set_data(ln, 1, p);
b1920e0b 1201 if (asprintf(&p, "%ju", gpt_partition_end(e)) > 0)
d9948c37
KZ
1202 tt_line_set_data(ln, 2, p);
1203 if (sizestr)
1204 tt_line_set_data(ln, 3, sizestr);
1205 if (t && t->name)
1206 tt_line_set_data(ln, 4, strdup(t->name));
b1920e0b
KZ
1207
1208 /* expert menu column(s) */
1209 if (fdisk_context_display_details(cxt)) {
1210 char *name = encode_to_utf8(
1211 (unsigned char *)e->name,
1212 sizeof(e->name));
1213
1214 if (guid_to_string(&e->partition_guid, u_str))
1215 tt_line_set_data(ln, 5, strdup(u_str));
1216 if (name)
1217 tt_line_set_data(ln, 6, name);
1218 }
766d5156 1219
9475cc78 1220 fdisk_warn_alignment(cxt, start, i);
766d5156
DB
1221 fdisk_free_parttype(t);
1222 }
d9948c37 1223
3c5fb475 1224 rc = fdisk_print_table(cxt, tb);
d9948c37 1225 tt_free_table(tb);
3c5fb475
KZ
1226
1227 return rc;
766d5156
DB
1228}
1229
1230/*
1231 * Write partitions.
1232 * Returns 0 on success, or corresponding error otherwise.
1233 */
1234static int gpt_write_partitions(struct fdisk_context *cxt,
d71ef5a4 1235 struct gpt_header *header, struct gpt_entry *ents)
766d5156
DB
1236{
1237 off_t offset = le64_to_cpu(header->partition_entry_lba) * cxt->sector_size;
1238 uint32_t nparts = le32_to_cpu(header->npartition_entries);
1239 uint32_t totwrite = nparts * le32_to_cpu(header->sizeof_partition_entry);
130820a8 1240 ssize_t rc;
766d5156
DB
1241
1242 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1243 goto fail;
d71ef5a4
KZ
1244
1245 rc = write(cxt->dev_fd, ents, totwrite);
130820a8 1246 if (rc > 0 && totwrite == (uint32_t) rc)
766d5156
DB
1247 return 0;
1248fail:
1249 return -errno;
1250}
1251
1252/*
1253 * Write a GPT header to a specified LBA
1254 * Returns 0 on success, or corresponding error otherwise.
1255 */
1256static int gpt_write_header(struct fdisk_context *cxt,
1257 struct gpt_header *header, uint64_t lba)
1258{
1259 off_t offset = lba * cxt->sector_size;
1260
1261 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1262 goto fail;
1263 if (cxt->sector_size ==
1264 (size_t) write(cxt->dev_fd, header, cxt->sector_size))
1265 return 0;
1266fail:
1267 return -errno;
1268}
1269
1270/*
1271 * Write the protective MBR.
1272 * Returns 0 on success, or corresponding error otherwise.
1273 */
1274static int gpt_write_pmbr(struct fdisk_context *cxt)
1275{
1276 off_t offset;
1277 struct gpt_legacy_mbr *pmbr = NULL;
1278
9ffeb235
KZ
1279 assert(cxt);
1280 assert(cxt->firstsector);
766d5156
DB
1281
1282 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
1283
1284 /* zero out the legacy partitions */
1285 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
1286
1287 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
1288 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
1289 pmbr->partition_record[0].start_sector = 1;
1290 pmbr->partition_record[0].end_head = 0xFE;
1291 pmbr->partition_record[0].end_sector = 0xFF;
1292 pmbr->partition_record[0].end_track = 0xFF;
1293 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
1294
1295 /*
1296 * Set size_in_lba to the size of the disk minus one. If the size of the disk
1297 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
1298 */
1299 if (cxt->total_sectors - 1 > 0xFFFFFFFFULL)
1300 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
1301 else
1302 pmbr->partition_record[0].size_in_lba =
1303 cpu_to_le32(cxt->total_sectors - 1UL);
1304
1305 offset = GPT_PMBR_LBA * cxt->sector_size;
1306 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1307 goto fail;
1308
19613111
DB
1309 /* pMBR covers the first sector (LBA) of the disk */
1310 if (write_all(cxt->dev_fd, pmbr, cxt->sector_size))
1311 goto fail;
1312 return 0;
766d5156
DB
1313fail:
1314 return -errno;
1315}
1316
1317/*
1318 * Writes in-memory GPT and pMBR data to disk.
1319 * Returns 0 if successful write, otherwise, a corresponding error.
1320 * Any indication of error will abort the operation.
1321 */
9ffeb235 1322static int gpt_write_disklabel(struct fdisk_context *cxt)
766d5156 1323{
9ffeb235 1324 struct fdisk_gpt_label *gpt;
d71ef5a4 1325
9ffeb235
KZ
1326 assert(cxt);
1327 assert(cxt->label);
1328 assert(fdisk_is_disklabel(cxt, GPT));
1329
1330 gpt = self_label(cxt);
766d5156
DB
1331
1332 /* we do not want to mess up hybrid MBRs by creating a valid pmbr */
1333 if (valid_pmbr(cxt) == GPT_MBR_HYBRID)
1334 goto err0;
1335
1336 /* check that disk is big enough to handle the backup header */
c15aec86 1337 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
766d5156
DB
1338 goto err0;
1339
1340 /* check that the backup header is properly placed */
c15aec86 1341 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1)
766d5156
DB
1342 /* TODO: correct this (with user authorization) and write */
1343 goto err0;
1344
d71ef5a4 1345 if (partition_check_overlaps(gpt->pheader, gpt->ents))
766d5156
DB
1346 goto err0;
1347
1348 /* recompute CRCs for both headers */
d71ef5a4
KZ
1349 gpt_recompute_crc(gpt->pheader, gpt->ents);
1350 gpt_recompute_crc(gpt->bheader, gpt->ents);
766d5156
DB
1351
1352 /*
1353 * UEFI requires writing in this specific order:
1354 * 1) backup partition tables
1355 * 2) backup GPT header
1356 * 3) primary partition tables
1357 * 4) primary GPT header
1358 * 5) protective MBR
1359 *
1360 * If any write fails, we abort the rest.
1361 */
d71ef5a4 1362 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
766d5156 1363 goto err1;
c15aec86
KZ
1364 if (gpt_write_header(cxt, gpt->bheader,
1365 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
766d5156 1366 goto err1;
d71ef5a4 1367 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
766d5156 1368 goto err1;
d71ef5a4 1369 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
766d5156
DB
1370 goto err1;
1371 if (gpt_write_pmbr(cxt) != 0)
1372 goto err1;
1373
c15aec86 1374 DBG(LABEL, dbgprint("GPT write success"));
766d5156
DB
1375 return 0;
1376err0:
c15aec86
KZ
1377 DBG(LABEL, dbgprint("GPT write failed: incorrect input"));
1378 errno = EINVAL;
766d5156
DB
1379 return -EINVAL;
1380err1:
c15aec86 1381 DBG(LABEL, dbgprint("GPT write failed: %m"));
766d5156
DB
1382 return -errno;
1383}
1384
1385/*
1386 * Verify data integrity and report any found problems for:
1387 * - primary and backup header validations
1388 * - paritition validations
1389 */
9ffeb235 1390static int gpt_verify_disklabel(struct fdisk_context *cxt)
766d5156 1391{
83df5feb
KZ
1392 int nerror = 0;
1393 unsigned int ptnum;
9ffeb235
KZ
1394 struct fdisk_gpt_label *gpt;
1395
1396 assert(cxt);
1397 assert(cxt->label);
1398 assert(fdisk_is_disklabel(cxt, GPT));
1399
1400 gpt = self_label(cxt);
766d5156 1401
d71ef5a4 1402 if (!gpt || !gpt->bheader) {
766d5156 1403 nerror++;
83df5feb 1404 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
766d5156
DB
1405 }
1406
d71ef5a4 1407 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
766d5156 1408 nerror++;
83df5feb 1409 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
766d5156 1410 }
d71ef5a4 1411 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
766d5156 1412 nerror++;
83df5feb 1413 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
766d5156
DB
1414 }
1415
d71ef5a4 1416 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
766d5156 1417 nerror++;
83df5feb 1418 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
766d5156
DB
1419 }
1420
d71ef5a4 1421 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
766d5156 1422 nerror++;
83df5feb 1423 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
766d5156 1424 }
d71ef5a4 1425 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
766d5156 1426 nerror++;
83df5feb 1427 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
766d5156
DB
1428 }
1429
d71ef5a4 1430 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
766d5156 1431 nerror++;
83df5feb 1432 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
766d5156 1433 }
d71ef5a4 1434 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
766d5156 1435 nerror++;
83df5feb 1436 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
766d5156
DB
1437
1438 }
c15aec86 1439 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
766d5156 1440 nerror++;
83df5feb 1441 fdisk_warnx(cxt, _("Disk is to small to hold all data."));
766d5156
DB
1442 }
1443
1444 /*
1445 * if the GPT is the primary table, check the alternateLBA
1446 * to see if it is a valid GPT
1447 */
c15aec86
KZ
1448 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
1449 le64_to_cpu(gpt->bheader->alternative_lba))) {
766d5156 1450 nerror++;
83df5feb 1451 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
766d5156
DB
1452 }
1453
d71ef5a4 1454 ptnum = partition_check_overlaps(gpt->pheader, gpt->ents);
766d5156
DB
1455 if (ptnum) {
1456 nerror++;
83df5feb
KZ
1457 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
1458 ptnum, ptnum+1);
766d5156
DB
1459 }
1460
d71ef5a4 1461 ptnum = partition_check_too_big(gpt->pheader, gpt->ents, cxt->total_sectors);
766d5156
DB
1462 if (ptnum) {
1463 nerror++;
83df5feb
KZ
1464 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
1465 ptnum);
766d5156
DB
1466 }
1467
d71ef5a4 1468 ptnum = partition_start_after_end(gpt->pheader, gpt->ents);
766d5156
DB
1469 if (ptnum) {
1470 nerror++;
83df5feb
KZ
1471 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
1472 ptnum);
766d5156
DB
1473 }
1474
1475 if (!nerror) { /* yay :-) */
1476 uint32_t nsegments = 0;
1477 uint64_t free_sectors = 0, largest_segment = 0;
1478
83df5feb
KZ
1479 fdisk_info(cxt, _("No errors detected"));
1480 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
1481 fdisk_info(cxt, _("Using %u out of %d partitions."),
d71ef5a4
KZ
1482 partitions_in_use(gpt->pheader, gpt->ents),
1483 le32_to_cpu(gpt->pheader->npartition_entries));
766d5156 1484
d71ef5a4 1485 free_sectors = get_free_sectors(cxt, gpt->pheader, gpt->ents,
766d5156 1486 &nsegments, &largest_segment);
83df5feb
KZ
1487 fdisk_info(cxt, _("A total of %ld free sectors available in %d segment(s) "
1488 "(largest %ld)."),
766d5156
DB
1489 free_sectors, nsegments, largest_segment);
1490 } else
83df5feb 1491 fdisk_warnx(cxt, _("Detected %d error(s)."), nerror);
766d5156
DB
1492
1493 return 0;
1494}
1495
1496/* Delete a single GPT partition, specified by partnum. */
8a95621d 1497static int gpt_delete_partition(struct fdisk_context *cxt,
9ffeb235 1498 size_t partnum)
766d5156 1499{
9ffeb235 1500 struct fdisk_gpt_label *gpt;
d71ef5a4 1501
9ffeb235
KZ
1502 assert(cxt);
1503 assert(cxt->label);
1504 assert(fdisk_is_disklabel(cxt, GPT));
d71ef5a4 1505
9ffeb235
KZ
1506 gpt = self_label(cxt);
1507
1508 if (partnum >= cxt->label->nparts_max
1509 || partition_unused(&gpt->ents[partnum]))
1f5eb51b 1510 return -EINVAL;
766d5156
DB
1511
1512 /* hasta la vista, baby! */
d71ef5a4
KZ
1513 memset(&gpt->ents[partnum], 0, sizeof(struct gpt_entry));
1514 if (!partition_unused(&gpt->ents[partnum]))
1f5eb51b 1515 return -EINVAL;
766d5156 1516 else {
d71ef5a4
KZ
1517 gpt_recompute_crc(gpt->pheader, gpt->ents);
1518 gpt_recompute_crc(gpt->bheader, gpt->ents);
9ffeb235
KZ
1519 cxt->label->nparts_cur--;
1520 fdisk_label_set_changed(cxt->label, 1);
766d5156 1521 }
1f5eb51b
DB
1522
1523 return 0;
766d5156
DB
1524}
1525
c0d14b09 1526static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
766d5156 1527{
d45fa25d
KZ
1528 e->type = *uuid;
1529 DBG(LABEL, dbgprint_uuid("new type", &(e->type)));
766d5156
DB
1530}
1531
1532/*
1533 * Create a new GPT partition entry, specified by partnum, and with a range
1534 * of fsect to lsenct sectors, of type t.
1535 * Returns 0 on success, or negative upon failure.
1536 */
d71ef5a4 1537static int gpt_create_new_partition(struct fdisk_context *cxt,
9ffeb235 1538 size_t partnum, uint64_t fsect, uint64_t lsect,
766d5156
DB
1539 struct gpt_guid *type,
1540 struct gpt_entry *entries)
1541{
1542 struct gpt_entry *e = NULL;
d71ef5a4 1543 struct fdisk_gpt_label *gpt;
766d5156 1544
9ffeb235
KZ
1545 assert(cxt);
1546 assert(cxt->label);
1547 assert(fdisk_is_disklabel(cxt, GPT));
766d5156 1548
9ffeb235
KZ
1549 gpt = self_label(cxt);
1550
1551 if (fsect > lsect || partnum >= cxt->label->nparts_max)
1552 return -EINVAL;
d71ef5a4 1553
46667ba4
KZ
1554 e = calloc(1, sizeof(*e));
1555 if (!e)
1556 return -ENOMEM;
766d5156
DB
1557 e->lba_end = cpu_to_le64(lsect);
1558 e->lba_start = cpu_to_le64(fsect);
1559
1560 gpt_entry_set_type(e, type);
1561
766d5156
DB
1562 /*
1563 * Any time a new partition entry is created a new GUID must be
1564 * generated for that partition, and every partition is guaranteed
1565 * to have a unique GUID.
1566 */
d45fa25d
KZ
1567 uuid_generate_random((unsigned char *) &e->partition_guid);
1568 swap_efi_guid(&e->partition_guid);
766d5156 1569
d71ef5a4 1570 memcpy(&entries[partnum], e, sizeof(*e));
766d5156 1571
d71ef5a4
KZ
1572 gpt_recompute_crc(gpt->pheader, entries);
1573 gpt_recompute_crc(gpt->bheader, entries);
766d5156
DB
1574
1575 free(e);
1576 return 0;
1577}
1578
1579/* Performs logical checks to add a new partition entry */
8a95621d
KZ
1580static int gpt_add_partition(
1581 struct fdisk_context *cxt,
9ffeb235 1582 size_t partnum,
8a95621d 1583 struct fdisk_parttype *t)
766d5156 1584{
512a430f
KZ
1585 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
1586 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
1587 uint64_t dflt_f, dflt_l; /* largest segment (default) */
c0d14b09 1588 struct gpt_guid typeid;
9ffeb235 1589 struct fdisk_gpt_label *gpt;
d71ef5a4
KZ
1590 struct gpt_header *pheader;
1591 struct gpt_entry *ents;
4114da08
KZ
1592 struct fdisk_ask *ask = NULL;
1593 int rc;
766d5156 1594
9ffeb235
KZ
1595 assert(cxt);
1596 assert(cxt->label);
1597 assert(fdisk_is_disklabel(cxt, GPT));
1598
1599 gpt = self_label(cxt);
1600
1601 if (partnum >= cxt->label->nparts_max)
8254c3a5 1602 return -EINVAL;
d71ef5a4
KZ
1603
1604 pheader = gpt->pheader;
1605 ents = gpt->ents;
1606
874aa9c3 1607 if (!partition_unused(&ents[partnum])) {
83df5feb
KZ
1608 fdisk_warnx(cxt, _("Partition %zd is already defined. "
1609 "Delete it before re-adding it."), partnum +1);
8254c3a5 1610 return -EINVAL;
766d5156 1611 }
d71ef5a4
KZ
1612 if (le32_to_cpu(pheader->npartition_entries) ==
1613 partitions_in_use(pheader, ents)) {
83df5feb 1614 fdisk_warnx(cxt, _("All partitions are already in use."));
8254c3a5 1615 return -EINVAL;
766d5156
DB
1616 }
1617
512a430f 1618 if (!get_free_sectors(cxt, pheader, ents, NULL, NULL)) {
83df5feb 1619 fdisk_warnx(cxt, _("No free sectors available."));
8254c3a5 1620 return -ENOSPC;
766d5156
DB
1621 }
1622
512a430f
KZ
1623 disk_f = find_first_available(pheader, ents, 0);
1624 disk_l = find_last_free_sector(pheader, ents);
1625
1626 /* the default is the largest free space */
1627 dflt_f = find_first_in_largest(pheader, ents);
1628 dflt_l = find_last_free(pheader, ents, dflt_f);
1629
1630 /* align the default in range <dflt_f,dflt_l>*/
9475cc78 1631 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
766d5156 1632
c0d14b09 1633 string_to_guid(t && t->typestr ? t->typestr : GPT_DEFAULT_ENTRY_TYPE, &typeid);
766d5156
DB
1634
1635 /* get user input for first and last sectors of the new partition */
766d5156 1636 for (;;) {
4114da08
KZ
1637 if (!ask)
1638 ask = fdisk_new_ask();
1639 else
1640 fdisk_reset_ask(ask);
1641
1642 /* First sector */
1643 fdisk_ask_set_query(ask, _("First sector"));
1644 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
1645 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
1646 fdisk_ask_number_set_default(ask, dflt_f); /* default */
1647 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
1648
1649 rc = fdisk_do_ask(cxt, ask);
1650 if (rc)
1651 goto done;
1652
1653 user_f = fdisk_ask_number_get_result(ask);
e3443e8f 1654 if (user_f != find_first_available(pheader, ents, user_f)) {
83df5feb 1655 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
512a430f 1656 continue;
e3443e8f 1657 }
512a430f 1658
4114da08
KZ
1659 fdisk_reset_ask(ask);
1660
512a430f
KZ
1661 /* Last sector */
1662 dflt_l = find_last_free(pheader, ents, user_f);
512a430f 1663
4114da08
KZ
1664 fdisk_ask_set_query(ask, _("Last sector, +sectors or +size{K,M,G,T,P}"));
1665 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
1666 fdisk_ask_number_set_low(ask, user_f); /* minimal */
1667 fdisk_ask_number_set_default(ask, dflt_l); /* default */
1668 fdisk_ask_number_set_high(ask, dflt_l); /* maximal */
1669 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
1670 fdisk_ask_number_set_unit(ask, cxt->sector_size);
1671
1672 rc = fdisk_do_ask(cxt, ask);
1673 if (rc)
1674 goto done;
1675
1676 user_l = fdisk_ask_number_get_result(ask);
1677 if (fdisk_ask_number_is_relative(ask))
1678 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l) - 1;
512a430f
KZ
1679 if (user_l > user_f && user_l <= disk_l)
1680 break;
766d5156
DB
1681 }
1682
d71ef5a4 1683 if (gpt_create_new_partition(cxt, partnum,
c0d14b09 1684 user_f, user_l, &typeid, ents) != 0)
83df5feb 1685 fdisk_warnx(cxt, _("Could not create partition %zd"), partnum + 1);
9fcd49d5 1686 else {
83df5feb 1687 fdisk_info(cxt, _("Created partition %zd\n"), partnum + 1);
9ffeb235
KZ
1688 cxt->label->nparts_cur++;
1689 fdisk_label_set_changed(cxt->label, 1);
9fcd49d5 1690 }
8254c3a5 1691
4114da08
KZ
1692 rc = 0;
1693done:
1694 fdisk_free_ask(ask);
1695 return rc;
766d5156
DB
1696}
1697
3f731001
DB
1698/*
1699 * Create a new GPT disklabel - destroys any previous data.
1700 */
9ffeb235 1701static int gpt_create_disklabel(struct fdisk_context *cxt)
3f731001
DB
1702{
1703 int rc = 0;
46667ba4 1704 ssize_t esz = 0;
21fe3dde 1705 char str[37];
9ffeb235
KZ
1706 struct fdisk_gpt_label *gpt;
1707
1708 assert(cxt);
1709 assert(cxt->label);
1710 assert(fdisk_is_disklabel(cxt, GPT));
1711
1712 gpt = self_label(cxt);
3f731001 1713
d71ef5a4 1714 /* label private stuff has to be empty, see gpt_deinit() */
d71ef5a4
KZ
1715 assert(gpt->pheader == NULL);
1716 assert(gpt->bheader == NULL);
4e0e8253 1717
3f731001 1718 /*
3f731001
DB
1719 * When no header, entries or pmbr is set, we're probably
1720 * dealing with a new, empty disk - so always allocate memory
1721 * to deal with the data structures whatever the case is.
1722 */
3f731001
DB
1723 rc = gpt_mknew_pmbr(cxt);
1724 if (rc < 0)
1725 goto done;
1726
d71ef5a4 1727 /* primary */
46667ba4
KZ
1728 gpt->pheader = calloc(1, sizeof(*gpt->pheader));
1729 if (!gpt->pheader) {
1730 rc = -ENOMEM;
1731 goto done;
1732 }
d71ef5a4 1733 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
3f731001
DB
1734 if (rc < 0)
1735 goto done;
1736
d71ef5a4 1737 /* backup ("copy" primary) */
46667ba4
KZ
1738 gpt->bheader = calloc(1, sizeof(*gpt->bheader));
1739 if (!gpt->bheader) {
1740 rc = -ENOMEM;
1741 goto done;
1742 }
d71ef5a4
KZ
1743 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
1744 last_lba(cxt), gpt->pheader);
3f731001
DB
1745 if (rc < 0)
1746 goto done;
1747
46667ba4
KZ
1748 esz = le32_to_cpu(gpt->pheader->npartition_entries) *
1749 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
1750 gpt->ents = calloc(1, esz);
1751 if (!gpt->ents) {
1752 rc = -ENOMEM;
1753 goto done;
1754 }
d71ef5a4
KZ
1755 gpt_recompute_crc(gpt->pheader, gpt->ents);
1756 gpt_recompute_crc(gpt->bheader, gpt->ents);
3f731001 1757
9ffeb235
KZ
1758 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1759 cxt->label->nparts_cur = 0;
9fcd49d5 1760
21fe3dde
KZ
1761 guid_to_string(&gpt->pheader->disk_guid, str);
1762 fdisk_info(cxt, _("Building a new GPT disklabel (GUID: %s)"), str);
9ffeb235 1763 fdisk_label_set_changed(cxt->label, 1);
3f731001
DB
1764done:
1765 return rc;
1766}
1767
21fe3dde
KZ
1768static int gpt_get_disklabel_id(struct fdisk_context *cxt, char **id)
1769{
1770 struct fdisk_gpt_label *gpt;
1771 char str[37];
1772
1773 assert(cxt);
1774 assert(id);
1775 assert(cxt->label);
1776 assert(fdisk_is_disklabel(cxt, GPT));
1777
1778 gpt = self_label(cxt);
1779 guid_to_string(&gpt->pheader->disk_guid, str);
1780
1781 *id = strdup(str);
1782 if (!*id)
1783 return -ENOMEM;
1784 return 0;
1785}
1786
35b1f0a4
KZ
1787static int gpt_set_disklabel_id(struct fdisk_context *cxt)
1788{
1789 struct fdisk_gpt_label *gpt;
1790 struct gpt_guid uuid;
1791 char *str, *old, *new;
1792 int rc;
1793
1794 assert(cxt);
1795 assert(cxt->label);
1796 assert(fdisk_is_disklabel(cxt, GPT));
1797
1798 gpt = self_label(cxt);
1799 if (fdisk_ask_string(cxt,
1800 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &str))
1801 return -EINVAL;
1802
1803 rc = string_to_guid(str, &uuid);
1804 free(str);
1805
1806 if (rc) {
1807 fdisk_warnx(cxt, _("Failed to parse your UUID."));
1808 return rc;
1809 }
1810
1811 gpt_get_disklabel_id(cxt, &old);
1812
1813 gpt->pheader->disk_guid = uuid;
1814 gpt->bheader->disk_guid = uuid;
1815
1816 gpt_recompute_crc(gpt->pheader, gpt->ents);
1817 gpt_recompute_crc(gpt->bheader, gpt->ents);
1818
1819 gpt_get_disklabel_id(cxt, &new);
1820
1821 fdisk_info(cxt, _("Changing disk identifier from %s to %s."), old, new);
1822
1823 free(old);
1824 free(new);
1825 fdisk_label_set_changed(cxt->label, 1);
1826 return 0;
1827}
1828
1829
8a95621d
KZ
1830static struct fdisk_parttype *gpt_get_partition_type(
1831 struct fdisk_context *cxt,
9ffeb235 1832 size_t i)
766d5156
DB
1833{
1834 struct fdisk_parttype *t;
766d5156 1835 char str[37];
9ffeb235 1836 struct fdisk_gpt_label *gpt;
d71ef5a4 1837
9ffeb235
KZ
1838 assert(cxt);
1839 assert(cxt->label);
1840 assert(fdisk_is_disklabel(cxt, GPT));
766d5156 1841
9ffeb235
KZ
1842 gpt = self_label(cxt);
1843
1844 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
766d5156
DB
1845 return NULL;
1846
d45fa25d 1847 guid_to_string(&gpt->ents[i].type, str);
766d5156
DB
1848 t = fdisk_get_parttype_from_string(cxt, str);
1849 if (!t)
1850 t = fdisk_new_unknown_parttype(0, str);
1851
1852 return t;
1853}
1854
1855
8a95621d
KZ
1856static int gpt_set_partition_type(
1857 struct fdisk_context *cxt,
9ffeb235 1858 size_t i,
8a95621d 1859 struct fdisk_parttype *t)
766d5156
DB
1860{
1861 struct gpt_guid uuid;
9ffeb235 1862 struct fdisk_gpt_label *gpt;
d71ef5a4 1863
9ffeb235
KZ
1864 assert(cxt);
1865 assert(cxt->label);
1866 assert(fdisk_is_disklabel(cxt, GPT));
766d5156 1867
9ffeb235
KZ
1868 gpt = self_label(cxt);
1869 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries)
c0d14b09 1870 || !t || !t->typestr || string_to_guid(t->typestr, &uuid) != 0)
766d5156
DB
1871 return -EINVAL;
1872
d71ef5a4
KZ
1873 gpt_entry_set_type(&gpt->ents[i], &uuid);
1874 gpt_recompute_crc(gpt->pheader, gpt->ents);
1875 gpt_recompute_crc(gpt->bheader, gpt->ents);
bddd84e7 1876
9ffeb235 1877 fdisk_label_set_changed(cxt->label, 1);
766d5156
DB
1878 return 0;
1879}
1880
47b8e7c0
KZ
1881static int gpt_get_partition_status(
1882 struct fdisk_context *cxt,
9ffeb235 1883 size_t i,
47b8e7c0
KZ
1884 int *status)
1885{
9ffeb235 1886 struct fdisk_gpt_label *gpt;
47b8e7c0
KZ
1887 struct gpt_entry *e;
1888
9ffeb235
KZ
1889 assert(cxt);
1890 assert(cxt->label);
1891 assert(fdisk_is_disklabel(cxt, GPT));
1892
1893 gpt = self_label(cxt);
1894
1895 if (!status || (uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
47b8e7c0
KZ
1896 return -EINVAL;
1897
1898 e = &gpt->ents[i];
1899 *status = FDISK_PARTSTAT_NONE;
1900
46667ba4 1901 if (!partition_unused(e) || gpt_partition_start(e))
47b8e7c0
KZ
1902 *status = FDISK_PARTSTAT_USED;
1903
1904 return 0;
1905}
1906
34b06299
KZ
1907int fdisk_gpt_partition_set_uuid(struct fdisk_context *cxt, size_t i)
1908{
1909 struct fdisk_gpt_label *gpt;
1910 struct gpt_entry *e;
1911 struct gpt_guid uuid;
1912 char *str, new_u[37], old_u[37];
1913 int rc;
1914
1915 assert(cxt);
1916 assert(cxt->label);
1917 assert(fdisk_is_disklabel(cxt, GPT));
1918
1054699c 1919 DBG(LABEL, dbgprint("UUID change requested partno=%zd", i));
34b06299
KZ
1920
1921 gpt = self_label(cxt);
1922
1923 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
1924 return -EINVAL;
1925
1926 if (fdisk_ask_string(cxt,
1927 _("New UUID (in 8-4-4-4-12 format)"), &str))
1928 return -EINVAL;
1929
1930 rc = string_to_guid(str, &uuid);
1931 free(str);
1932
35b1f0a4
KZ
1933 if (rc) {
1934 fdisk_warnx(cxt, _("Failed to parse your UUID."));
34b06299 1935 return rc;
35b1f0a4 1936 }
34b06299
KZ
1937
1938 e = &gpt->ents[i];
1939
d45fa25d 1940 guid_to_string(&e->partition_guid, old_u);
34b06299
KZ
1941 guid_to_string(&uuid, new_u);
1942 fdisk_info(cxt, _("Changing partition UUID from %s to %s"),
1943 old_u, new_u);
1944
d45fa25d 1945 e->partition_guid = uuid;
34b06299
KZ
1946 gpt_recompute_crc(gpt->pheader, gpt->ents);
1947 gpt_recompute_crc(gpt->bheader, gpt->ents);
1948
1949 fdisk_label_set_changed(cxt->label, 1);
1950 return 0;
1951}
47b8e7c0 1952
1054699c
KZ
1953int fdisk_gpt_partition_set_name(struct fdisk_context *cxt, size_t i)
1954{
1955 struct fdisk_gpt_label *gpt;
1956 struct gpt_entry *e;
1957 char *str, *old, name[GPT_PART_NAME_LEN] = { 0 };
1958 size_t sz;
1959
1960 assert(cxt);
1961 assert(cxt->label);
1962 assert(fdisk_is_disklabel(cxt, GPT));
1963
1964 DBG(LABEL, dbgprint("NAME change requested partno=%zd", i));
1965
1966 gpt = self_label(cxt);
1967
1968 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
1969 return -EINVAL;
1970
1971 if (fdisk_ask_string(cxt, _("New name"), &str))
1972 return -EINVAL;
1973
1974 e = &gpt->ents[i];
1975 old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
1976
1977 fdisk_info(cxt, _("Changing partition name from '%s' to '%.*s'"),
1978 old, GPT_PART_NAME_LEN, str);
1979 sz = strlen(str);
1980 if (sz) {
1981 if (sz > GPT_PART_NAME_LEN)
1982 sz = GPT_PART_NAME_LEN;
1983 memcpy(name, str, sz);
1984 }
1985 free(str);
1986 free(old);
1987
1988 for (i = 0; i < GPT_PART_NAME_LEN; i++)
1989 e->name[i] = cpu_to_le16((uint16_t) name[i]);
1990
1991 gpt_recompute_crc(gpt->pheader, gpt->ents);
1992 gpt_recompute_crc(gpt->bheader, gpt->ents);
1993
1994 fdisk_label_set_changed(cxt->label, 1);
1995 return 0;
1996}
1997
1998
4e0e8253
KZ
1999/*
2000 * Deinitialize fdisk-specific variables
2001 */
d71ef5a4 2002static void gpt_deinit(struct fdisk_label *lb)
4e0e8253 2003{
d71ef5a4
KZ
2004 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
2005
2006 if (!gpt)
2007 return;
2008
2009 free(gpt->ents);
2010 free(gpt->pheader);
2011 free(gpt->bheader);
2012
2013 gpt->ents = NULL;
2014 gpt->pheader = NULL;
2015 gpt->bheader = NULL;
4e0e8253
KZ
2016}
2017
0c5d095e 2018static const struct fdisk_label_operations gpt_operations =
766d5156 2019{
0c5d095e
KZ
2020 .probe = gpt_probe_label,
2021 .write = gpt_write_disklabel,
2022 .verify = gpt_verify_disklabel,
2023 .create = gpt_create_disklabel,
3c5fb475 2024 .list = gpt_list_disklabel,
21fe3dde 2025 .get_id = gpt_get_disklabel_id,
35b1f0a4 2026 .set_id = gpt_set_disklabel_id,
21fe3dde 2027
0c5d095e
KZ
2028 .part_add = gpt_add_partition,
2029 .part_delete = gpt_delete_partition,
2030 .part_get_type = gpt_get_partition_type,
4e0e8253
KZ
2031 .part_set_type = gpt_set_partition_type,
2032
47b8e7c0
KZ
2033 .part_get_status = gpt_get_partition_status,
2034
4e0e8253 2035 .deinit = gpt_deinit
766d5156 2036};
0c5d095e
KZ
2037
2038/*
2039 * allocates GPT in-memory stuff
2040 */
2041struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt)
2042{
2043 struct fdisk_label *lb;
2044 struct fdisk_gpt_label *gpt;
2045
2046 assert(cxt);
2047
2048 gpt = calloc(1, sizeof(*gpt));
2049 if (!gpt)
2050 return NULL;
2051
2052 /* initialize generic part of the driver */
2053 lb = (struct fdisk_label *) gpt;
2054 lb->name = "gpt";
53b422ab 2055 lb->id = FDISK_DISKLABEL_GPT;
0c5d095e
KZ
2056 lb->op = &gpt_operations;
2057 lb->parttypes = gpt_parttypes;
2058 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
2059
2060 return lb;
2061}