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