]> git.ipfire.org Git - thirdparty/util-linux.git/blame - libfdisk/src/gpt.c
libfdisk: make it possible to use zero for size and start
[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 */
01086b80
KZ
70enum {
71 /* UEFI specific */
72 GPT_ATTRBIT_REQ = 0,
73 GPT_ATTRBIT_NOBLOCK = 1,
74 GPT_ATTRBIT_LEGACY = 2,
75
76 /* GUID specific (range 48..64)*/
77 GPT_ATTRBIT_GUID_FIRST = 48,
78 GPT_ATTRBIT_GUID_COUNT = 16
79};
c83f772e 80
01086b80
KZ
81#define GPT_ATTRSTR_REQ "RequiredPartiton"
82#define GPT_ATTRSTR_NOBLOCK "NoBlockIOProtocol"
83#define GPT_ATTRSTR_LEGACY "LegacyBIOSBootable"
c83f772e 84
766d5156
DB
85/* The GPT Partition entry array contains an array of GPT entries. */
86struct gpt_entry {
d45fa25d
KZ
87 struct gpt_guid type; /* purpose and type of the partition */
88 struct gpt_guid partition_guid;
766d5156
DB
89 uint64_t lba_start;
90 uint64_t lba_end;
01086b80 91 uint64_t attrs;
d45fa25d 92 uint16_t name[GPT_PART_NAME_LEN];
766d5156
DB
93} __attribute__ ((packed));
94
95/* GPT header */
96struct gpt_header {
97 uint64_t signature; /* header identification */
98 uint32_t revision; /* header version */
99 uint32_t size; /* in bytes */
100 uint32_t crc32; /* header CRC checksum */
101 uint32_t reserved1; /* must be 0 */
9ed38607 102 uint64_t my_lba; /* LBA of block that contains this struct (LBA 1) */
766d5156
DB
103 uint64_t alternative_lba; /* backup GPT header */
104 uint64_t first_usable_lba; /* first usable logical block for partitions */
105 uint64_t last_usable_lba; /* last usable logical block for partitions */
3f731001 106 struct gpt_guid disk_guid; /* unique disk identifier */
9ed38607 107 uint64_t partition_entry_lba; /* LBA of start of partition entries array */
766d5156
DB
108 uint32_t npartition_entries; /* total partition entries - normally 128 */
109 uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
110 uint32_t partition_entry_array_crc32; /* partition CRC checksum */
9ed38607 111 uint8_t reserved2[512 - 92]; /* must all be 0 */
766d5156
DB
112} __attribute__ ((packed));
113
114struct gpt_record {
115 uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
116 uint8_t start_head; /* unused by EFI, pt start in CHS */
117 uint8_t start_sector; /* unused by EFI, pt start in CHS */
118 uint8_t start_track;
119 uint8_t os_type; /* EFI and legacy non-EFI OS types */
120 uint8_t end_head; /* unused by EFI, pt end in CHS */
121 uint8_t end_sector; /* unused by EFI, pt end in CHS */
122 uint8_t end_track; /* unused by EFI, pt end in CHS */
123 uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
124 uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
125} __attribute__ ((packed));
126
127/* Protected MBR and legacy MBR share same structure */
128struct gpt_legacy_mbr {
129 uint8_t boot_code[440];
130 uint32_t unique_mbr_signature;
131 uint16_t unknown;
132 struct gpt_record partition_record[4];
133 uint16_t signature;
134} __attribute__ ((packed));
135
136/*
137 * Here be dragons!
138 * See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
139 */
140#define DEF_GUID(_u, _n) \
141 { \
142 .typestr = (_u), \
143 .name = (_n), \
144 }
145
146static struct fdisk_parttype gpt_parttypes[] =
147{
148 /* Generic OS */
149 DEF_GUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", N_("EFI System")),
150
151 DEF_GUID("024DEE41-33E7-11D3-9D69-0008C781F39F", N_("MBR partition scheme")),
ae488940
KZ
152 DEF_GUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593", N_("Intel Fast Flash")),
153
766d5156 154 /* Hah!IdontneedEFI */
5a1b4999 155 DEF_GUID("21686148-6449-6E6F-744E-656564454649", N_("BIOS boot")),
766d5156
DB
156
157 /* Windows */
158 DEF_GUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE", N_("Microsoft reserved")),
159 DEF_GUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", N_("Microsoft basic data")),
160 DEF_GUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3", N_("Microsoft LDM metadata")),
161 DEF_GUID("AF9B60A0-1431-4F62-BC68-3311714A69AD", N_("Microsoft LDM data")),
0d0d12ad 162 DEF_GUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC", N_("Windows recovery environment")),
766d5156 163 DEF_GUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174", N_("IBM General Parallel Fs")),
210d4595 164 DEF_GUID("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D", N_("Microsoft Storage Spaces")),
766d5156
DB
165
166 /* HP-UX */
5a1b4999
KZ
167 DEF_GUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000", N_("HP-UX data")),
168 DEF_GUID("E2A1E728-32E3-11D6-A682-7B03A0000000", N_("HP-UX service")),
766d5156 169
5a1b4999
KZ
170 /* Linux (http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec) */
171 DEF_GUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", N_("Linux swap")),
766d5156 172 DEF_GUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4", N_("Linux filesystem")),
5a1b4999
KZ
173 DEF_GUID("3B8F8425-20E0-4F3B-907F-1A25A76F98E8", N_("Linux server data")),
174 DEF_GUID("44479540-F297-41B2-9AF7-D131D5F0458A", N_("Linux root (x86)")),
175 DEF_GUID("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709", N_("Linux root (x86-64)")),
176 DEF_GUID("8DA63339-0007-60C0-C436-083AC8230908", N_("Linux reserved")),
177 DEF_GUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915", N_("Linux home")),
766d5156 178 DEF_GUID("A19D880F-05FC-4D3B-A006-743F0F84911E", N_("Linux RAID")),
5a1b4999 179 DEF_GUID("BC13C2FF-59E6-4262-A352-B275FD6F7172", N_("Linux extended boot")),
766d5156 180 DEF_GUID("E6D6D379-F507-44C2-A23C-238F2A3DF928", N_("Linux LVM")),
766d5156 181
e9bf0935 182 /* FreeBSD */
766d5156
DB
183 DEF_GUID("516E7CB4-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD data")),
184 DEF_GUID("83BD6B9D-7F41-11DC-BE0B-001560B84F0F", N_("FreeBSD boot")),
185 DEF_GUID("516E7CB5-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD swap")),
186 DEF_GUID("516E7CB6-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD UFS")),
187 DEF_GUID("516E7CBA-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD ZFS")),
188 DEF_GUID("516E7CB8-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD Vinum")),
189
190 /* Apple OSX */
191 DEF_GUID("48465300-0000-11AA-AA11-00306543ECAC", N_("Apple HFS/HFS+")),
192 DEF_GUID("55465300-0000-11AA-AA11-00306543ECAC", N_("Apple UFS")),
193 DEF_GUID("52414944-0000-11AA-AA11-00306543ECAC", N_("Apple RAID")),
194 DEF_GUID("52414944-5F4F-11AA-AA11-00306543ECAC", N_("Apple RAID offline")),
195 DEF_GUID("426F6F74-0000-11AA-AA11-00306543ECAC", N_("Apple boot")),
196 DEF_GUID("4C616265-6C00-11AA-AA11-00306543ECAC", N_("Apple label")),
197 DEF_GUID("5265636F-7665-11AA-AA11-00306543ECAC", N_("Apple TV recovery")),
198 DEF_GUID("53746F72-6167-11AA-AA11-00306543ECAC", N_("Apple Core storage")),
199
200 /* Solaris */
201 DEF_GUID("6A82CB45-1DD2-11B2-99A6-080020736631", N_("Solaris boot")),
202 DEF_GUID("6A85CF4D-1DD2-11B2-99A6-080020736631", N_("Solaris root")),
203 /* same as Apple ZFS */
204 DEF_GUID("6A898CC3-1DD2-11B2-99A6-080020736631", N_("Solaris /usr & Apple ZFS")),
205 DEF_GUID("6A87C46F-1DD2-11B2-99A6-080020736631", N_("Solaris swap")),
206 DEF_GUID("6A8B642B-1DD2-11B2-99A6-080020736631", N_("Solaris backup")),
207 DEF_GUID("6A8EF2E9-1DD2-11B2-99A6-080020736631", N_("Solaris /var")),
208 DEF_GUID("6A90BA39-1DD2-11B2-99A6-080020736631", N_("Solaris /home")),
209 DEF_GUID("6A9283A5-1DD2-11B2-99A6-080020736631", N_("Solaris alternate sector")),
210 DEF_GUID("6A945A3B-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 1")),
211 DEF_GUID("6A9630D1-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 2")),
212 DEF_GUID("6A980767-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 3")),
213 DEF_GUID("6A96237F-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 4")),
214 DEF_GUID("6A8D2AC7-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 5")),
215
216 /* NetBSD */
217 DEF_GUID("49F48D32-B10E-11DC-B99B-0019D1879648", N_("NetBSD swap")),
218 DEF_GUID("49F48D5A-B10E-11DC-B99B-0019D1879648", N_("NetBSD FFS")),
219 DEF_GUID("49F48D82-B10E-11DC-B99B-0019D1879648", N_("NetBSD LFS")),
220 DEF_GUID("2DB519C4-B10E-11DC-B99B-0019D1879648", N_("NetBSD concatenated")),
221 DEF_GUID("2DB519EC-B10E-11DC-B99B-0019D1879648", N_("NetBSD encrypted")),
222 DEF_GUID("49F48DAA-B10E-11DC-B99B-0019D1879648", N_("NetBSD RAID")),
223
224 /* ChromeOS */
225 DEF_GUID("FE3A2A5D-4F32-41A7-B725-ACCC3285A309", N_("ChromeOS kernel")),
226 DEF_GUID("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC", N_("ChromeOS root fs")),
227 DEF_GUID("2E0A753D-9E48-43B0-8337-B15192CB1B5E", N_("ChromeOS reserved")),
228
229 /* MidnightBSD */
230 DEF_GUID("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD data")),
231 DEF_GUID("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD boot")),
232 DEF_GUID("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD swap")),
233 DEF_GUID("0394Ef8B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD UFS")),
234 DEF_GUID("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD ZFS")),
235 DEF_GUID("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD Vinum")),
236};
237
d71ef5a4 238/* gpt_entry macros */
874aa9c3
KZ
239#define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
240#define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
241
d71ef5a4
KZ
242/*
243 * in-memory fdisk GPT stuff
244 */
245struct fdisk_gpt_label {
246 struct fdisk_label head; /* generic part */
247
248 /* gpt specific part */
249 struct gpt_header *pheader; /* primary header */
250 struct gpt_header *bheader; /* backup header */
251 struct gpt_entry *ents; /* entries (partitions) */
252};
253
254static void gpt_deinit(struct fdisk_label *lb);
255
9ffeb235 256static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
d71ef5a4 257{
d71ef5a4
KZ
258 return (struct fdisk_gpt_label *) cxt->label;
259}
260
874aa9c3
KZ
261/*
262 * Returns the partition length, or 0 if end is before beginning.
263 */
264static uint64_t gpt_partition_size(const struct gpt_entry *e)
265{
266 uint64_t start = gpt_partition_start(e);
267 uint64_t end = gpt_partition_end(e);
268
269 return start > end ? 0 : end - start + 1ULL;
270}
271
c0d14b09 272/* prints UUID in the real byte order! */
88141067 273static void gpt_debug_uuid(const char *mesg, struct gpt_guid *guid)
c0d14b09
KZ
274{
275 const unsigned char *uuid = (unsigned char *) guid;
276
277 fprintf(stderr, "%s: "
278 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
279 mesg,
280 uuid[0], uuid[1], uuid[2], uuid[3],
281 uuid[4], uuid[5],
282 uuid[6], uuid[7],
283 uuid[8], uuid[9],
284 uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
285}
c0d14b09 286
766d5156
DB
287/*
288 * UUID is traditionally 16 byte big-endian array, except Intel EFI
289 * specification where the UUID is a structure of little-endian fields.
290 */
291static void swap_efi_guid(struct gpt_guid *uid)
292{
293 uid->time_low = swab32(uid->time_low);
294 uid->time_mid = swab16(uid->time_mid);
295 uid->time_hi_and_version = swab16(uid->time_hi_and_version);
5dbff4c0
KZ
296}
297
c0d14b09 298static int string_to_guid(const char *in, struct gpt_guid *guid)
766d5156 299{
c0d14b09 300 if (uuid_parse(in, (unsigned char *) guid)) /* BE */
766d5156 301 return -1;
c0d14b09 302 swap_efi_guid(guid); /* LE */
766d5156
DB
303 return 0;
304}
305
7f539277 306static char *guid_to_string(const struct gpt_guid *guid, char *out)
766d5156 307{
c0d14b09
KZ
308 struct gpt_guid u = *guid; /* LE */
309
310 swap_efi_guid(&u); /* BE */
311 uuid_unparse_upper((unsigned char *) &u, out);
312
46667ba4 313 return out;
766d5156
DB
314}
315
7f539277
KZ
316static struct fdisk_parttype *gpt_partition_parttype(
317 struct fdisk_context *cxt,
318 const struct gpt_entry *e)
319{
320 struct fdisk_parttype *t;
321 char str[37];
322
323 guid_to_string(&e->type, str);
a745611d 324 t = fdisk_label_get_parttype_from_string(cxt->label, str);
7f539277
KZ
325 return t ? : fdisk_new_unknown_parttype(0, str);
326}
327
b0a484a8
KZ
328static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
329{
330 e->type = *uuid;
331 DBG(LABEL, gpt_debug_uuid("new type", &(e->type)));
332}
333
334static void gpt_entry_set_name(struct gpt_entry *e, char *str)
335{
336 char name[GPT_PART_NAME_LEN] = { 0 };
337 size_t i, sz = strlen(str);
338
339 if (sz) {
340 if (sz > GPT_PART_NAME_LEN)
341 sz = GPT_PART_NAME_LEN;
342 memcpy(name, str, sz);
343 }
344
345 for (i = 0; i < GPT_PART_NAME_LEN; i++)
346 e->name[i] = cpu_to_le16((uint16_t) name[i]);
347}
348
349static int gpt_entry_set_uuid(struct gpt_entry *e, char *str)
350{
351 struct gpt_guid uuid;
352 int rc;
353
354 rc = string_to_guid(str, &uuid);
355 if (rc)
356 return rc;
357
358 e->partition_guid = uuid;
359 return 0;
360}
7f539277
KZ
361
362
766d5156
DB
363static const char *gpt_get_header_revstr(struct gpt_header *header)
364{
365 if (!header)
366 goto unknown;
367
368 switch (header->revision) {
369 case GPT_HEADER_REVISION_V1_02:
370 return "1.2";
371 case GPT_HEADER_REVISION_V1_00:
372 return "1.0";
373 case GPT_HEADER_REVISION_V0_99:
374 return "0.99";
375 default:
376 goto unknown;
377 }
378
379unknown:
380 return "unknown";
381}
382
874aa9c3 383static inline int partition_unused(const struct gpt_entry *e)
766d5156 384{
d45fa25d 385 return !memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
766d5156
DB
386 sizeof(struct gpt_guid));
387}
388
3f731001
DB
389/*
390 * Builds a clean new valid protective MBR - will wipe out any existing data.
391 * Returns 0 on success, otherwise < 0 on error.
392 */
393static int gpt_mknew_pmbr(struct fdisk_context *cxt)
394{
395 struct gpt_legacy_mbr *pmbr = NULL;
7c2cfb18 396 int rc;
3f731001
DB
397
398 if (!cxt || !cxt->firstsector)
399 return -ENOSYS;
400
7c2cfb18
KZ
401 rc = fdisk_init_firstsector_buffer(cxt);
402 if (rc)
403 return rc;
3f731001
DB
404
405 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
406
407 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
408 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
409 pmbr->partition_record[0].start_sector = 1;
410 pmbr->partition_record[0].end_head = 0xFE;
411 pmbr->partition_record[0].end_sector = 0xFF;
412 pmbr->partition_record[0].end_track = 0xFF;
413 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
414 pmbr->partition_record[0].size_in_lba =
415 cpu_to_le32(min((uint32_t) cxt->total_sectors - 1, 0xFFFFFFFF));
416
417 return 0;
418}
419
420/* some universal differences between the headers */
421static void gpt_mknew_header_common(struct fdisk_context *cxt,
422 struct gpt_header *header, uint64_t lba)
423{
424 if (!cxt || !header)
425 return;
426
427 header->my_lba = cpu_to_le64(lba);
428
429 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) { /* primary */
430 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1);
431 header->partition_entry_lba = cpu_to_le64(2);
432 } else { /* backup */
433 uint64_t esz = le32_to_cpu(header->npartition_entries) * sizeof(struct gpt_entry);
434 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
435
436 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
437 header->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1 - esects);
438 }
439}
440
441/*
442 * Builds a new GPT header (at sector lba) from a backup header2.
443 * If building a primary header, then backup is the secondary, and vice versa.
444 *
445 * Always pass a new (zeroized) header to build upon as we don't
446 * explicitly zero-set some values such as CRCs and reserved.
447 *
448 * Returns 0 on success, otherwise < 0 on error.
449 */
450static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
451 struct gpt_header *header,
452 uint64_t lba,
453 struct gpt_header *header2)
454{
455 if (!cxt || !header || !header2)
456 return -ENOSYS;
457
458 header->signature = header2->signature;
459 header->revision = header2->revision;
460 header->size = header2->size;
461 header->npartition_entries = header2->npartition_entries;
462 header->sizeof_partition_entry = header2->sizeof_partition_entry;
463 header->first_usable_lba = header2->first_usable_lba;
464 header->last_usable_lba = header2->last_usable_lba;
465
466 memcpy(&header->disk_guid,
467 &header2->disk_guid, sizeof(header2->disk_guid));
468 gpt_mknew_header_common(cxt, header, lba);
469
470 return 0;
471}
472
45ddb828
KZ
473static struct gpt_header *gpt_copy_header(struct fdisk_context *cxt,
474 struct gpt_header *src)
475{
476 struct gpt_header *res;
477
478 if (!cxt || !src)
479 return NULL;
480
481 res = calloc(1, sizeof(*res));
482 if (!res) {
483 fdisk_warn(cxt, _("failed to allocate GPT header"));
484 return NULL;
485 }
486
487 res->my_lba = src->alternative_lba;
488 res->alternative_lba = src->my_lba;
489
490 res->signature = src->signature;
491 res->revision = src->revision;
492 res->size = src->size;
493 res->npartition_entries = src->npartition_entries;
494 res->sizeof_partition_entry = src->sizeof_partition_entry;
495 res->first_usable_lba = src->first_usable_lba;
496 res->last_usable_lba = src->last_usable_lba;
497
498 memcpy(&res->disk_guid, &src->disk_guid, sizeof(src->disk_guid));
499
500
501 if (res->my_lba == GPT_PRIMARY_PARTITION_TABLE_LBA)
502 res->partition_entry_lba = cpu_to_le64(2);
503 else {
504 uint64_t esz = le32_to_cpu(src->npartition_entries) * sizeof(struct gpt_entry);
505 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
506
507 res->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1 - esects);
508 }
509
510 return res;
511}
512
1240f549
KZ
513static void count_first_last_lba(struct fdisk_context *cxt,
514 uint64_t *first, uint64_t *last)
515{
516 uint64_t esz = 0;
517
518 assert(cxt);
519
520 esz = sizeof(struct gpt_entry) * GPT_NPARTITIONS / cxt->sector_size;
521 *last = cxt->total_sectors - 2 - esz;
522 *first = esz + 2;
523
524 if (*first < cxt->first_lba && cxt->first_lba < *last)
525 /* Align according to topology */
526 *first = cxt->first_lba;
527}
528
3f731001
DB
529/*
530 * Builds a clean new GPT header (currently under revision 1.0).
531 *
532 * Always pass a new (zeroized) header to build upon as we don't
533 * explicitly zero-set some values such as CRCs and reserved.
534 *
535 * Returns 0 on success, otherwise < 0 on error.
536 */
537static int gpt_mknew_header(struct fdisk_context *cxt,
538 struct gpt_header *header, uint64_t lba)
539{
1240f549 540 uint64_t first, last;
4b43f7c9 541 int has_id = 0;
3f731001
DB
542
543 if (!cxt || !header)
544 return -ENOSYS;
545
3f731001
DB
546 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
547 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
548 header->size = cpu_to_le32(sizeof(struct gpt_header));
549
550 /*
09af3db4 551 * 128 partitions are the default. It can go beyond that, but
3f731001
DB
552 * we're creating a de facto header here, so no funny business.
553 */
554 header->npartition_entries = cpu_to_le32(GPT_NPARTITIONS);
555 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
b4184690 556
1240f549 557 count_first_last_lba(cxt, &first, &last);
b4184690
KZ
558 header->first_usable_lba = cpu_to_le64(first);
559 header->last_usable_lba = cpu_to_le64(last);
3f731001
DB
560
561 gpt_mknew_header_common(cxt, header, lba);
3f731001 562
4b43f7c9
KZ
563 if (cxt->script) {
564 const char *id = fdisk_script_get_header(cxt->script, "label-id");
565 if (id && string_to_guid(id, &header->disk_guid) == 0)
566 has_id = 1;
567 }
568
569 if (!has_id) {
570 uuid_generate_random((unsigned char *) &header->disk_guid);
571 swap_efi_guid(&header->disk_guid);
572 }
3f731001
DB
573 return 0;
574}
575
766d5156
DB
576/*
577 * Checks if there is a valid protective MBR partition table.
578 * Returns 0 if it is invalid or failure. Otherwise, return
579 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depeding on the detection.
580 */
581static int valid_pmbr(struct fdisk_context *cxt)
582{
879fadf1 583 int i, part = 0, ret = 0; /* invalid by default */
766d5156 584 struct gpt_legacy_mbr *pmbr = NULL;
1fd10841 585 uint32_t sz_lba = 0;
766d5156
DB
586
587 if (!cxt->firstsector)
588 goto done;
589
590 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
591
f67c524e 592 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
766d5156
DB
593 goto done;
594
595 /* LBA of the GPT partition header */
596 if (pmbr->partition_record[0].starting_lba !=
597 cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
598 goto done;
599
600 /* seems like a valid MBR was found, check DOS primary partitions */
f67c524e 601 for (i = 0; i < 4; i++) {
766d5156
DB
602 if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
603 /*
604 * Ok, we at least know that there's a protective MBR,
605 * now check if there are other partition types for
606 * hybrid MBR.
607 */
879fadf1 608 part = i;
766d5156
DB
609 ret = GPT_MBR_PROTECTIVE;
610 goto check_hybrid;
611 }
f67c524e 612 }
ac920fed 613
766d5156
DB
614 if (ret != GPT_MBR_PROTECTIVE)
615 goto done;
ac920fed 616check_hybrid:
f67c524e 617 for (i = 0 ; i < 4; i++) {
766d5156
DB
618 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
619 (pmbr->partition_record[i].os_type != 0x00))
620 ret = GPT_MBR_HYBRID;
f67c524e 621 }
766d5156
DB
622
623 /*
624 * Protective MBRs take up the lesser of the whole disk
625 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
1fd10841
DB
626 * Some partitioning programs, nonetheless, choose to set
627 * the size to the maximum 32-bit limitation, disregarding
628 * the disk size.
766d5156
DB
629 *
630 * Hybrid MBRs do not necessarily comply with this.
59db52ad
KZ
631 *
632 * Consider a bad value here to be a warning to support dd-ing
633 * an image from a smaller disk to a bigger disk.
766d5156 634 */
f67c524e 635 if (ret == GPT_MBR_PROTECTIVE) {
1fd10841 636 sz_lba = le32_to_cpu(pmbr->partition_record[part].size_in_lba);
59db52ad
KZ
637 if (sz_lba != (uint32_t) cxt->total_sectors - 1 && sz_lba != 0xFFFFFFFF) {
638 fdisk_warnx(cxt, _("GPT PMBR size mismatch (%u != %u) "
639 "will be corrected by w(rite)."),
640 sz_lba,
641 (uint32_t) cxt->total_sectors - 1);
1572fb3e 642 fdisk_label_set_changed(cxt->label, 1);
59db52ad 643 }
f67c524e 644 }
766d5156
DB
645done:
646 return ret;
647}
648
649static uint64_t last_lba(struct fdisk_context *cxt)
5dbff4c0 650{
5dbff4c0 651 struct stat s;
cbebd20d 652 uint64_t sectors = 0;
5dbff4c0 653
766d5156
DB
654 memset(&s, 0, sizeof(s));
655 if (fstat(cxt->dev_fd, &s) == -1) {
83df5feb 656 fdisk_warn(cxt, _("gpt: stat() failed"));
5dbff4c0
KZ
657 return 0;
658 }
766d5156 659
5dbff4c0 660 if (S_ISBLK(s.st_mode))
cbebd20d
KZ
661 sectors = cxt->total_sectors - 1;
662 else if (S_ISREG(s.st_mode))
663 sectors = ((uint64_t) s.st_size /
664 (uint64_t) cxt->sector_size) - 1ULL;
665 else
83df5feb 666 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
cbebd20d
KZ
667
668 DBG(LABEL, ul_debug("GPT last LBA: %ju", sectors));
669 return sectors;
5dbff4c0
KZ
670}
671
766d5156
DB
672static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
673 void *buffer, const size_t bytes)
5dbff4c0 674{
766d5156 675 off_t offset = lba * cxt->sector_size;
5dbff4c0 676
bbe8e6a9
KZ
677 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
678 return -1;
679 return read(cxt->dev_fd, buffer, bytes) != bytes;
5dbff4c0
KZ
680}
681
766d5156
DB
682
683/* Returns the GPT entry array */
be5f8061 684static struct gpt_entry *gpt_read_entries(struct fdisk_context *cxt,
d71ef5a4 685 struct gpt_header *header)
5dbff4c0 686{
d71ef5a4
KZ
687 ssize_t sz;
688 struct gpt_entry *ret = NULL;
689 off_t offset;
690
691 assert(cxt);
692 assert(header);
693
694 sz = le32_to_cpu(header->npartition_entries) *
695 le32_to_cpu(header->sizeof_partition_entry);
696
46667ba4 697 ret = calloc(1, sz);
d71ef5a4
KZ
698 if (!ret)
699 return NULL;
700 offset = le64_to_cpu(header->partition_entry_lba) *
766d5156
DB
701 cxt->sector_size;
702
703 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
d71ef5a4 704 goto fail;
766d5156 705 if (sz != read(cxt->dev_fd, ret, sz))
d71ef5a4 706 goto fail;
766d5156
DB
707
708 return ret;
d71ef5a4
KZ
709
710fail:
711 free(ret);
712 return NULL;
766d5156
DB
713}
714
715static inline uint32_t count_crc32(const unsigned char *buf, size_t len)
716{
717 return (crc32(~0L, buf, len) ^ ~0L);
718}
719
720/*
721 * Recompute header and partition array 32bit CRC checksums.
722 * This function does not fail - if there's corruption, then it
723 * will be reported when checksuming it again (ie: probing or verify).
724 */
d71ef5a4 725static void gpt_recompute_crc(struct gpt_header *header, struct gpt_entry *ents)
766d5156
DB
726{
727 uint32_t crc = 0;
728 size_t entry_sz = 0;
729
730 if (!header)
731 return;
732
733 /* header CRC */
734 header->crc32 = 0;
735 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
736 header->crc32 = cpu_to_le32(crc);
737
738 /* partition entry array CRC */
739 header->partition_entry_array_crc32 = 0;
740 entry_sz = le32_to_cpu(header->npartition_entries) *
741 le32_to_cpu(header->sizeof_partition_entry);
742
d71ef5a4 743 crc = count_crc32((unsigned char *) ents, entry_sz);
766d5156
DB
744 header->partition_entry_array_crc32 = cpu_to_le32(crc);
745}
746
747/*
748 * Compute the 32bit CRC checksum of the partition table header.
749 * Returns 1 if it is valid, otherwise 0.
750 */
d71ef5a4 751static int gpt_check_header_crc(struct gpt_header *header, struct gpt_entry *ents)
766d5156
DB
752{
753 uint32_t crc, orgcrc = le32_to_cpu(header->crc32);
754
755 header->crc32 = 0;
756 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
757 header->crc32 = cpu_to_le32(orgcrc);
758
d71ef5a4
KZ
759 if (crc == le32_to_cpu(header->crc32))
760 return 1;
761
766d5156
DB
762 /*
763 * If we have checksum mismatch it may be due to stale data,
764 * like a partition being added or deleted. Recompute the CRC again
765 * and make sure this is not the case.
766 */
d71ef5a4 767 if (ents) {
766d5156
DB
768 gpt_recompute_crc(header, ents);
769 orgcrc = le32_to_cpu(header->crc32);
770 header->crc32 = 0;
771 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
772 header->crc32 = cpu_to_le32(orgcrc);
773
774 return crc == le32_to_cpu(header->crc32);
d71ef5a4
KZ
775 }
776
777 return 0;
766d5156
DB
778}
779
780/*
781 * It initializes the partition entry array.
782 * Returns 1 if the checksum is valid, otherwise 0.
783 */
d71ef5a4
KZ
784static int gpt_check_entryarr_crc(struct gpt_header *header,
785 struct gpt_entry *ents)
766d5156
DB
786{
787 int ret = 0;
788 ssize_t entry_sz;
789 uint32_t crc;
790
d71ef5a4 791 if (!header || !ents)
766d5156
DB
792 goto done;
793
794 entry_sz = le32_to_cpu(header->npartition_entries) *
795 le32_to_cpu(header->sizeof_partition_entry);
796
797 if (!entry_sz)
798 goto done;
799
766d5156
DB
800 crc = count_crc32((unsigned char *) ents, entry_sz);
801 ret = (crc == le32_to_cpu(header->partition_entry_array_crc32));
802done:
803 return ret;
804}
805
806static int gpt_check_lba_sanity(struct fdisk_context *cxt, struct gpt_header *header)
807{
808 int ret = 0;
809 uint64_t lu, fu, lastlba = last_lba(cxt);
810
811 fu = le64_to_cpu(header->first_usable_lba);
812 lu = le64_to_cpu(header->last_usable_lba);
813
814 /* check if first and last usable LBA make sense */
815 if (lu < fu) {
88141067 816 DBG(LABEL, ul_debug("error: header last LBA is before first LBA"));
766d5156 817 goto done;
5dbff4c0 818 }
766d5156
DB
819
820 /* check if first and last usable LBAs with the disk's last LBA */
821 if (fu > lastlba || lu > lastlba) {
88141067 822 DBG(LABEL, ul_debug("error: header LBAs are after the disk's last LBA"));
766d5156
DB
823 goto done;
824 }
825
826 /* the header has to be outside usable range */
827 if (fu < GPT_PRIMARY_PARTITION_TABLE_LBA &&
828 GPT_PRIMARY_PARTITION_TABLE_LBA < lu) {
88141067 829 DBG(LABEL, ul_debug("error: header outside of usable range"));
766d5156
DB
830 goto done;
831 }
832
833 ret = 1; /* sane */
834done:
835 return ret;
836}
837
838/* Check if there is a valid header signature */
839static int gpt_check_signature(struct gpt_header *header)
840{
841 return header->signature == cpu_to_le64(GPT_HEADER_SIGNATURE);
842}
843
844/*
845 * Return the specified GPT Header, or NULL upon failure/invalid.
846 * Note that all tests must pass to ensure a valid header,
847 * we do not rely on only testing the signature for a valid probe.
848 */
d71ef5a4
KZ
849static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
850 uint64_t lba,
851 struct gpt_entry **_ents)
766d5156
DB
852{
853 struct gpt_header *header = NULL;
d71ef5a4 854 struct gpt_entry *ents = NULL;
e9bf0935 855 uint32_t hsz;
766d5156
DB
856
857 if (!cxt)
858 return NULL;
859
46667ba4
KZ
860 header = calloc(1, sizeof(*header));
861 if (!header)
862 return NULL;
766d5156 863
d71ef5a4 864 /* read and verify header */
bbe8e6a9 865 if (read_lba(cxt, lba, header, sizeof(struct gpt_header)) != 0)
766d5156
DB
866 goto invalid;
867
868 if (!gpt_check_signature(header))
869 goto invalid;
870
d71ef5a4
KZ
871 if (!gpt_check_header_crc(header, NULL))
872 goto invalid;
873
874 /* read and verify entries */
875 ents = gpt_read_entries(cxt, header);
876 if (!ents)
877 goto invalid;
878
879 if (!gpt_check_entryarr_crc(header, ents))
766d5156
DB
880 goto invalid;
881
882 if (!gpt_check_lba_sanity(cxt, header))
883 goto invalid;
884
885 /* valid header must be at MyLBA */
886 if (le64_to_cpu(header->my_lba) != lba)
887 goto invalid;
888
e9bf0935
DB
889 /* make sure header size is between 92 and sector size bytes */
890 hsz = le32_to_cpu(header->size);
891 if (hsz < GPT_HEADER_MINSZ || hsz > cxt->sector_size)
892 goto invalid;
893
d71ef5a4
KZ
894 if (_ents)
895 *_ents = ents;
896 else
897 free(ents);
898
88141067 899 DBG(LABEL, ul_debug("found valid GPT Header on LBA %ju", lba));
766d5156
DB
900 return header;
901invalid:
902 free(header);
d71ef5a4 903 free(ents);
45ddb828 904
88141067 905 DBG(LABEL, ul_debug("read GPT Header on LBA %ju failed", lba));
766d5156
DB
906 return NULL;
907}
908
775001ad
KZ
909
910static int gpt_locate_disklabel(struct fdisk_context *cxt, int n,
911 const char **name, off_t *offset, size_t *size)
912{
913 struct fdisk_gpt_label *gpt;
914
915 assert(cxt);
916
917 *name = NULL;
918 *offset = 0;
919 *size = 0;
920
921 switch (n) {
922 case 0:
923 *name = "PMBR";
924 *offset = 0;
925 *size = 512;
926 break;
927 case 1:
928 *name = _("GPT Header");
929 *offset = GPT_PRIMARY_PARTITION_TABLE_LBA * cxt->sector_size;
930 *size = sizeof(struct gpt_header);
931 break;
932 case 2:
933 *name = _("GPT Entries");
934 gpt = self_label(cxt);
935 *offset = le64_to_cpu(gpt->pheader->partition_entry_lba) * cxt->sector_size;
936 *size = le32_to_cpu(gpt->pheader->npartition_entries) *
937 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
938 break;
939 default:
940 return 1; /* no more chunks */
941 }
942
943 return 0;
944}
945
946
947
766d5156
DB
948/*
949 * Returns the number of partitions that are in use.
950 */
130820a8 951static unsigned partitions_in_use(struct gpt_header *header, struct gpt_entry *e)
766d5156
DB
952{
953 uint32_t i, used = 0;
954
955 if (!header || ! e)
956 return 0;
957
958 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
874aa9c3 959 if (!partition_unused(&e[i]))
766d5156
DB
960 used++;
961 return used;
962}
963
766d5156
DB
964
965/*
966 * Check if a partition is too big for the disk (sectors).
967 * Returns the faulting partition number, otherwise 0.
968 */
83df5feb 969static uint32_t partition_check_too_big(struct gpt_header *header,
766d5156
DB
970 struct gpt_entry *e, uint64_t sectors)
971{
972 uint32_t i;
973
974 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3 975 if (partition_unused(&e[i]))
766d5156 976 continue;
874aa9c3 977 if (gpt_partition_end(&e[i]) >= sectors)
766d5156 978 return i + 1;
5dbff4c0 979 }
766d5156
DB
980
981 return 0;
5dbff4c0
KZ
982}
983
766d5156
DB
984/*
985 * Check if a partition ends before it begins
986 * Returns the faulting partition number, otherwise 0.
5dbff4c0 987 */
83df5feb 988static uint32_t partition_start_after_end(struct gpt_header *header, struct gpt_entry *e)
5dbff4c0 989{
766d5156 990 uint32_t i;
5dbff4c0 991
766d5156 992 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3 993 if (partition_unused(&e[i]))
766d5156 994 continue;
874aa9c3 995 if (gpt_partition_start(&e[i]) > gpt_partition_end(&e[i]))
766d5156 996 return i + 1;
5dbff4c0 997 }
766d5156
DB
998
999 return 0;
5dbff4c0
KZ
1000}
1001
766d5156 1002/*
09af3db4 1003 * Check if partition e1 overlaps with partition e2.
766d5156 1004 */
874aa9c3 1005static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
5dbff4c0 1006{
874aa9c3
KZ
1007 uint64_t start1 = gpt_partition_start(e1);
1008 uint64_t end1 = gpt_partition_end(e1);
1009 uint64_t start2 = gpt_partition_start(e2);
1010 uint64_t end2 = gpt_partition_end(e2);
1011
1012 return (start1 && start2 && (start1 <= end2) != (end1 < start2));
766d5156
DB
1013}
1014
1015/*
09af3db4 1016 * Find any partitions that overlap.
766d5156 1017 */
83df5feb 1018static uint32_t partition_check_overlaps(struct gpt_header *header, struct gpt_entry *e)
766d5156
DB
1019{
1020 uint32_t i, j;
1021
1022 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
1023 for (j = 0; j < i; j++) {
874aa9c3
KZ
1024 if (partition_unused(&e[i]) ||
1025 partition_unused(&e[j]))
766d5156 1026 continue;
c15aec86 1027 if (partition_overlap(&e[i], &e[j])) {
88141067 1028 DBG(LABEL, ul_debug("GPT partitions overlap detected [%u vs. %u]", i, j));
766d5156 1029 return i + 1;
c15aec86 1030 }
766d5156
DB
1031 }
1032
1033 return 0;
1034}
1035
1036/*
1037 * Find the first available block after the starting point; returns 0 if
1038 * there are no available blocks left, or error. From gdisk.
1039 */
1040static uint64_t find_first_available(struct gpt_header *header,
1041 struct gpt_entry *e, uint64_t start)
1042{
1043 uint64_t first;
1044 uint32_t i, first_moved = 0;
1045
602ebe7d
KZ
1046 uint64_t fu, lu;
1047
766d5156 1048 if (!header || !e)
5dbff4c0 1049 return 0;
766d5156 1050
602ebe7d
KZ
1051 fu = le64_to_cpu(header->first_usable_lba);
1052 lu = le64_to_cpu(header->last_usable_lba);
1053
766d5156
DB
1054 /*
1055 * Begin from the specified starting point or from the first usable
1056 * LBA, whichever is greater...
1057 */
602ebe7d 1058 first = start < fu ? fu : start;
766d5156
DB
1059
1060 /*
1061 * Now search through all partitions; if first is within an
1062 * existing partition, move it to the next sector after that
1063 * partition and repeat. If first was moved, set firstMoved
1064 * flag; repeat until firstMoved is not set, so as to catch
1065 * cases where partitions are out of sequential order....
1066 */
1067 do {
1068 first_moved = 0;
1069 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3 1070 if (partition_unused(&e[i]))
766d5156 1071 continue;
874aa9c3 1072 if (first < gpt_partition_start(&e[i]))
766d5156 1073 continue;
874aa9c3
KZ
1074 if (first <= gpt_partition_end(&e[i])) {
1075 first = gpt_partition_end(&e[i]) + 1;
766d5156
DB
1076 first_moved = 1;
1077 }
1078 }
1079 } while (first_moved == 1);
1080
602ebe7d 1081 if (first > lu)
766d5156
DB
1082 first = 0;
1083
1084 return first;
5dbff4c0
KZ
1085}
1086
766d5156
DB
1087
1088/* Returns last available sector in the free space pointed to by start. From gdisk. */
1089static uint64_t find_last_free(struct gpt_header *header,
1090 struct gpt_entry *e, uint64_t start)
5dbff4c0 1091{
766d5156
DB
1092 uint32_t i;
1093 uint64_t nearest_start;
1094
1095 if (!header || !e)
1096 return 0;
1097
602ebe7d
KZ
1098 nearest_start = le64_to_cpu(header->last_usable_lba);
1099
766d5156 1100 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
602ebe7d
KZ
1101 uint64_t ps = gpt_partition_start(&e[i]);
1102
1103 if (nearest_start > ps && ps > start)
1104 nearest_start = ps - 1;
5dbff4c0 1105 }
766d5156
DB
1106
1107 return nearest_start;
5dbff4c0 1108}
766d5156
DB
1109
1110/* Returns the last free sector on the disk. From gdisk. */
1111static uint64_t find_last_free_sector(struct gpt_header *header,
1112 struct gpt_entry *e)
1113{
1114 uint32_t i, last_moved;
1115 uint64_t last = 0;
1116
1117 if (!header || !e)
1118 goto done;
1119
1120 /* start by assuming the last usable LBA is available */
602ebe7d 1121 last = le64_to_cpu(header->last_usable_lba);
766d5156
DB
1122 do {
1123 last_moved = 0;
1124 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
874aa9c3
KZ
1125 if ((last >= gpt_partition_start(&e[i])) &&
1126 (last <= gpt_partition_end(&e[i]))) {
1127 last = gpt_partition_start(&e[i]) - 1;
766d5156
DB
1128 last_moved = 1;
1129 }
1130 }
1131 } while (last_moved == 1);
1132done:
1133 return last;
1134}
1135
1136/*
1137 * Finds the first available sector in the largest block of unallocated
1138 * space on the disk. Returns 0 if there are no available blocks left.
1139 * From gdisk.
1140 */
1141static uint64_t find_first_in_largest(struct gpt_header *header, struct gpt_entry *e)
1142{
1143 uint64_t start = 0, first_sect, last_sect;
1144 uint64_t segment_size, selected_size = 0, selected_segment = 0;
1145
1146 if (!header || !e)
1147 goto done;
1148
1149 do {
1150 first_sect = find_first_available(header, e, start);
1151 if (first_sect != 0) {
1152 last_sect = find_last_free(header, e, first_sect);
1153 segment_size = last_sect - first_sect + 1;
1154
1155 if (segment_size > selected_size) {
1156 selected_size = segment_size;
1157 selected_segment = first_sect;
1158 }
1159 start = last_sect + 1;
1160 }
1161 } while (first_sect != 0);
1162
1163done:
1164 return selected_segment;
1165}
1166
1167/*
1168 * Find the total number of free sectors, the number of segments in which
1169 * they reside, and the size of the largest of those segments. From gdisk.
1170 */
1171static uint64_t get_free_sectors(struct fdisk_context *cxt, struct gpt_header *header,
1172 struct gpt_entry *e, uint32_t *nsegments,
1173 uint64_t *largest_segment)
1174{
1175 uint32_t num = 0;
1176 uint64_t first_sect, last_sect;
1177 uint64_t largest_seg = 0, segment_sz;
1178 uint64_t totfound = 0, start = 0; /* starting point for each search */
1179
1180 if (!cxt->total_sectors)
1181 goto done;
1182
1183 do {
1184 first_sect = find_first_available(header, e, start);
1185 if (first_sect) {
1186 last_sect = find_last_free(header, e, first_sect);
1187 segment_sz = last_sect - first_sect + 1;
1188
1189 if (segment_sz > largest_seg)
1190 largest_seg = segment_sz;
1191 totfound += segment_sz;
1192 num++;
1193 start = last_sect + 1;
1194 }
1195 } while (first_sect);
1196
1197done:
512a430f
KZ
1198 if (nsegments)
1199 *nsegments = num;
1200 if (largest_segment)
1201 *largest_segment = largest_seg;
766d5156
DB
1202
1203 return totfound;
1204}
1205
9ffeb235 1206static int gpt_probe_label(struct fdisk_context *cxt)
766d5156
DB
1207{
1208 int mbr_type;
9ffeb235 1209 struct fdisk_gpt_label *gpt;
766d5156 1210
9ffeb235
KZ
1211 assert(cxt);
1212 assert(cxt->label);
aa36c2cf 1213 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1214
1215 gpt = self_label(cxt);
766d5156 1216
d2d9efa1
KZ
1217 /* TODO: it would be nice to support scenario when GPT headers are OK,
1218 * but PMBR is corrupt */
766d5156
DB
1219 mbr_type = valid_pmbr(cxt);
1220 if (!mbr_type)
1221 goto failed;
1222
88141067 1223 DBG(LABEL, ul_debug("found a %s MBR", mbr_type == GPT_MBR_PROTECTIVE ?
766d5156
DB
1224 "protective" : "hybrid"));
1225
d71ef5a4
KZ
1226 /* primary header */
1227 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1228 &gpt->ents);
45ddb828
KZ
1229
1230 if (gpt->pheader)
1231 /* primary OK, try backup from alternative LBA */
1232 gpt->bheader = gpt_read_header(cxt,
1233 le64_to_cpu(gpt->pheader->alternative_lba),
1234 NULL);
1235 else
1236 /* primary corrupted -- try last LBA */
1237 gpt->bheader = gpt_read_header(cxt, last_lba(cxt), &gpt->ents);
766d5156 1238
d2d9efa1 1239 if (!gpt->pheader && !gpt->bheader)
766d5156
DB
1240 goto failed;
1241
d2d9efa1
KZ
1242 /* primary OK, backup corrupted -- recovery */
1243 if (gpt->pheader && !gpt->bheader) {
1244 fdisk_warnx(cxt, _("The backup GPT table is corrupt, but the "
1245 "primary appears OK, so that will be used."));
45ddb828
KZ
1246 gpt->bheader = gpt_copy_header(cxt, gpt->pheader);
1247 if (!gpt->bheader)
d2d9efa1 1248 goto failed;
d2d9efa1
KZ
1249 gpt_recompute_crc(gpt->bheader, gpt->ents);
1250
1251 /* primary corrupted, backup OK -- recovery */
1252 } else if (!gpt->pheader && gpt->bheader) {
1253 fdisk_warnx(cxt, _("The primary GPT table is corrupt, but the "
1254 "backup appears OK, so that will be used."));
45ddb828
KZ
1255 gpt->pheader = gpt_copy_header(cxt, gpt->bheader);
1256 if (!gpt->pheader)
d2d9efa1 1257 goto failed;
d2d9efa1
KZ
1258 gpt_recompute_crc(gpt->pheader, gpt->ents);
1259 }
d71ef5a4 1260
9ffeb235
KZ
1261 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1262 cxt->label->nparts_cur = partitions_in_use(gpt->pheader, gpt->ents);
766d5156
DB
1263 return 1;
1264failed:
88141067 1265 DBG(LABEL, ul_debug("GPT probe failed"));
9ffeb235 1266 gpt_deinit(cxt->label);
766d5156
DB
1267 return 0;
1268}
1269
1270/*
1271 * Stolen from libblkid - can be removed once partition semantics
1272 * are added to the fdisk API.
1273 */
1274static char *encode_to_utf8(unsigned char *src, size_t count)
1275{
1276 uint16_t c;
d06f321d 1277 char *dest;
766d5156 1278 size_t i, j, len = count;
3f731001 1279
d06f321d
KZ
1280 dest = calloc(1, count);
1281 if (!dest)
1282 return NULL;
766d5156
DB
1283
1284 for (j = i = 0; i + 2 <= count; i += 2) {
1285 /* always little endian */
1286 c = (src[i+1] << 8) | src[i];
1287 if (c == 0) {
1288 dest[j] = '\0';
1289 break;
1290 } else if (c < 0x80) {
1291 if (j+1 >= len)
1292 break;
1293 dest[j++] = (uint8_t) c;
1294 } else if (c < 0x800) {
1295 if (j+2 >= len)
1296 break;
1297 dest[j++] = (uint8_t) (0xc0 | (c >> 6));
1298 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1299 } else {
1300 if (j+3 >= len)
1301 break;
1302 dest[j++] = (uint8_t) (0xe0 | (c >> 12));
1303 dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
1304 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1305 }
1306 }
1307 dest[j] = '\0';
1308
1309 return dest;
1310}
1311
01086b80 1312static int gpt_entry_attrs_to_string(struct gpt_entry *e, char **res)
c83f772e 1313{
01086b80
KZ
1314 unsigned int n, count = 0;
1315 size_t l;
1316 char *bits, *p;
1317 uint64_t attrs;
1318
1319 assert(e);
1320 assert(res);
1321
1322 *res = NULL;
1323 attrs = le64_to_cpu(e->attrs);
1324 if (!attrs)
1325 return 0; /* no attributes at all */
1326
1327 bits = (char *) &attrs;
1328
1329 /* Note that sizeof() is correct here, we need separators between
1330 * the strings so also count \0 is correct */
1331 *res = calloc(1, sizeof(GPT_ATTRSTR_NOBLOCK) +
1332 sizeof(GPT_ATTRSTR_REQ) +
1333 sizeof(GPT_ATTRSTR_LEGACY) +
1334 sizeof("GUID:") + (GPT_ATTRBIT_GUID_COUNT * 3));
c83f772e 1335 if (!*res)
01086b80
KZ
1336 return -errno;
1337
1338 p = *res;
1339 if (isset(bits, GPT_ATTRBIT_REQ)) {
1340 memcpy(p, GPT_ATTRSTR_REQ, (l = sizeof(GPT_ATTRSTR_REQ)));
1341 p += l - 1;
1342 }
1343 if (isset(bits, GPT_ATTRBIT_NOBLOCK)) {
1344 if (p > *res)
1345 *p++ = ' ';
1346 memcpy(p, GPT_ATTRSTR_NOBLOCK, (l = sizeof(GPT_ATTRSTR_NOBLOCK)));
1347 p += l - 1;
1348 }
1349 if (isset(bits, GPT_ATTRBIT_LEGACY)) {
1350 if (p > *res)
1351 *p++ = ' ';
1352 memcpy(p, GPT_ATTRSTR_LEGACY, (l = sizeof(GPT_ATTRSTR_LEGACY)));
1353 p += l - 1;
1354 }
1355
1356 for (n = GPT_ATTRBIT_GUID_FIRST;
1357 n < GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT; n++) {
c83f772e 1358
01086b80 1359 if (!isset(bits, n))
c83f772e 1360 continue;
01086b80
KZ
1361 if (!count) {
1362 if (p > *res)
1363 *p++ = ' ';
1364 p += sprintf(p, "GUID:%u", n);
1365 } else
1366 p += sprintf(p, ",%u", n);
c83f772e 1367 count++;
c83f772e
KZ
1368 }
1369
01086b80 1370 return 0;
c83f772e
KZ
1371}
1372
c77ba531
KZ
1373static int gpt_entry_attrs_from_string(
1374 struct fdisk_context *cxt,
1375 struct gpt_entry *e,
1376 const char *str)
1377{
1378 const char *p = str;
1379 uint64_t attrs = 0;
1380 char *bits;
1381
1382 assert(e);
1383 assert(p);
1384
1385 DBG(LABEL, ul_debug("GPT: parsing string attributes '%s'", p));
1386
1387 bits = (char *) &attrs;
1388
1389 while (p && *p) {
1390 int bit = -1;
1391
1392 while (isblank(*p)) p++;
1393 if (!*p)
1394 break;
1395
1396 DBG(LABEL, ul_debug(" parsing item '%s'", p));
1397
1398 if (strncmp(p, "GUID:", 5) == 0) {
1399 p += 5;
1400 continue;
1401 } else if (strncmp(p, GPT_ATTRSTR_REQ,
1402 sizeof(GPT_ATTRSTR_REQ) - 1) == 0) {
1403 bit = GPT_ATTRBIT_REQ;
1404 p += sizeof(GPT_ATTRSTR_REQ) - 1;
1405 } else if (strncmp(p, GPT_ATTRSTR_LEGACY,
1406 sizeof(GPT_ATTRSTR_LEGACY) - 1) == 0) {
1407 bit = GPT_ATTRBIT_LEGACY;
1408 p += sizeof(GPT_ATTRSTR_LEGACY) - 1;
1409 } else if (strncmp(p, GPT_ATTRSTR_NOBLOCK,
1410 sizeof(GPT_ATTRSTR_NOBLOCK) - 1) == 0) {
1411 bit = GPT_ATTRBIT_NOBLOCK;
1412 p += sizeof(GPT_ATTRSTR_NOBLOCK) - 1;
1413 } else if (isdigit((unsigned int) *p)) {
1414 char *end = NULL;
1415
1416 errno = 0;
1417 bit = strtol(p, &end, 0);
1418 if (errno || !end || end == str
1419 || bit < GPT_ATTRBIT_GUID_FIRST
1420 || bit >= GPT_ATTRBIT_GUID_FIRST + GPT_ATTRBIT_GUID_COUNT)
1421 bit = -1;
1422 else
1423 p = end;
1424 }
1425
1426 if (bit < 0) {
1427 fdisk_warnx(cxt, _("unssuported GPT attribute bit '%s'"), p);
1428 return -EINVAL;
1429 }
1430
1431 setbit(bits, bit);
1432
1433 while (isblank(*p)) p++;
1434 if (*p == ',')
1435 p++;
1436 }
1437
1438 e->attrs = cpu_to_le64(attrs);
1439 return 0;
1440}
1441
8c0a7f91
KZ
1442static int gpt_get_partition(struct fdisk_context *cxt, size_t n,
1443 struct fdisk_partition *pa)
766d5156 1444{
9ffeb235 1445 struct fdisk_gpt_label *gpt;
6941952e 1446 struct gpt_entry *e;
01086b80
KZ
1447 char u_str[37];
1448 int rc = 0;
9ffeb235
KZ
1449
1450 assert(cxt);
1451 assert(cxt->label);
aa36c2cf 1452 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1453
1454 gpt = self_label(cxt);
766d5156 1455
6941952e
KZ
1456 if ((uint32_t) n >= le32_to_cpu(gpt->pheader->npartition_entries))
1457 return -EINVAL;
3c5fb475 1458
6941952e
KZ
1459 gpt = self_label(cxt);
1460 e = &gpt->ents[n];
b1920e0b 1461
8c0a7f91
KZ
1462 pa->used = !partition_unused(e) || gpt_partition_start(e);
1463 if (!pa->used)
1464 return 0;
766d5156 1465
8c0a7f91
KZ
1466 pa->start = gpt_partition_start(e);
1467 pa->end = gpt_partition_end(e);
77d6a70a 1468 pa->size = gpt_partition_size(e);
7f539277 1469 pa->type = gpt_partition_parttype(cxt, e);
766d5156 1470
8c0a7f91
KZ
1471 if (guid_to_string(&e->partition_guid, u_str)) {
1472 pa->uuid = strdup(u_str);
01086b80
KZ
1473 if (!pa->uuid) {
1474 rc = -errno;
1475 goto done;
1476 }
8c0a7f91
KZ
1477 } else
1478 pa->uuid = NULL;
1479
01086b80
KZ
1480 rc = gpt_entry_attrs_to_string(e, &pa->attrs);
1481 if (rc)
1482 goto done;
b1920e0b 1483
8c0a7f91 1484 pa->name = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
8c0a7f91 1485 return 0;
01086b80 1486done:
8c0a7f91 1487 fdisk_reset_partition(pa);
01086b80 1488 return rc;
6941952e 1489}
766d5156 1490
9348ef25 1491
b0a484a8
KZ
1492static int gpt_set_partition(struct fdisk_context *cxt, size_t n,
1493 struct fdisk_partition *pa)
1494{
1495 struct fdisk_gpt_label *gpt;
1496 struct gpt_entry *e;
1497 int rc = 0;
1498
1499 assert(cxt);
1500 assert(cxt->label);
1501 assert(fdisk_is_label(cxt, GPT));
1502
1503 gpt = self_label(cxt);
1504
1505 if ((uint32_t) n >= le32_to_cpu(gpt->pheader->npartition_entries))
1506 return -EINVAL;
1507
1508 gpt = self_label(cxt);
1509 e = &gpt->ents[n];
1510
1511 if (pa->uuid) {
6936c081
KZ
1512 char new_u[37], old_u[37];
1513
1514 guid_to_string(&e->partition_guid, old_u);
b0a484a8
KZ
1515 rc = gpt_entry_set_uuid(e, pa->uuid);
1516 if (rc)
1517 return rc;
6936c081
KZ
1518 guid_to_string(&e->partition_guid, new_u);
1519 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
1520 _("Partition UUID changed from %s to %s."),
1521 old_u, new_u);
b0a484a8
KZ
1522 }
1523
6936c081
KZ
1524 if (pa->name) {
1525 char *old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
b0a484a8
KZ
1526 gpt_entry_set_name(e, pa->name);
1527
6936c081
KZ
1528 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
1529 _("Partition name changed from '%s' to '%.*s'."),
1530 old, (int) GPT_PART_NAME_LEN, pa->name);
1531 free(old);
1532 }
1533
b0a484a8
KZ
1534 if (pa->type && pa->type->typestr) {
1535 struct gpt_guid typeid;
1536
a48c0985
KZ
1537 rc = string_to_guid(pa->type->typestr, &typeid);
1538 if (rc)
1539 return rc;
b0a484a8
KZ
1540 gpt_entry_set_type(e, &typeid);
1541 }
c77ba531
KZ
1542 if (pa->attrs) {
1543 rc = gpt_entry_attrs_from_string(cxt, e, pa->attrs);
1544 if (rc)
1545 return rc;
1546 }
b0a484a8 1547
ecf40cda 1548 if (fdisk_partition_has_start(pa))
b0a484a8 1549 e->lba_start = cpu_to_le64(pa->start);
ecf40cda 1550 if (fdisk_partition_has_size(pa))
b0a484a8
KZ
1551 e->lba_end = cpu_to_le64(gpt_partition_start(e) + pa->size - 1ULL);
1552
b0a484a8
KZ
1553 gpt_recompute_crc(gpt->pheader, gpt->ents);
1554 gpt_recompute_crc(gpt->bheader, gpt->ents);
1555
1556 fdisk_label_set_changed(cxt->label, 1);
1557 return rc;
1558}
1559
1560
6941952e
KZ
1561/*
1562 * List label partitions.
1563 */
1564static int gpt_list_disklabel(struct fdisk_context *cxt)
1565{
1566 assert(cxt);
1567 assert(cxt->label);
aa36c2cf 1568 assert(fdisk_is_label(cxt, GPT));
d9948c37 1569
6a632136 1570 if (fdisk_is_details(cxt)) {
6941952e 1571 struct gpt_header *h = self_label(cxt)->pheader;
3c5fb475 1572
412791a9
KZ
1573 fdisk_info(cxt, _("First LBA: %ju"), h->first_usable_lba);
1574 fdisk_info(cxt, _("Last LBA: %ju"), h->last_usable_lba);
9ed38607 1575 /* TRANSLATORS: The LBA (Logical Block Address) of the backup GPT header. */
412791a9 1576 fdisk_info(cxt, _("Alternative LBA: %ju"), h->alternative_lba);
9ed38607
BS
1577 /* TRANSLATORS: The start of the array of partition entries. */
1578 fdisk_info(cxt, _("Partition entries LBA: %ju"), h->partition_entry_lba);
412791a9 1579 fdisk_info(cxt, _("Allocated partition entries: %u"), h->npartition_entries);
6941952e
KZ
1580 }
1581
6c89f750 1582 return 0;
766d5156
DB
1583}
1584
1585/*
1586 * Write partitions.
1587 * Returns 0 on success, or corresponding error otherwise.
1588 */
1589static int gpt_write_partitions(struct fdisk_context *cxt,
d71ef5a4 1590 struct gpt_header *header, struct gpt_entry *ents)
766d5156
DB
1591{
1592 off_t offset = le64_to_cpu(header->partition_entry_lba) * cxt->sector_size;
1593 uint32_t nparts = le32_to_cpu(header->npartition_entries);
1594 uint32_t totwrite = nparts * le32_to_cpu(header->sizeof_partition_entry);
130820a8 1595 ssize_t rc;
766d5156
DB
1596
1597 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1598 goto fail;
d71ef5a4
KZ
1599
1600 rc = write(cxt->dev_fd, ents, totwrite);
130820a8 1601 if (rc > 0 && totwrite == (uint32_t) rc)
766d5156
DB
1602 return 0;
1603fail:
1604 return -errno;
1605}
1606
1607/*
1608 * Write a GPT header to a specified LBA
1609 * Returns 0 on success, or corresponding error otherwise.
1610 */
1611static int gpt_write_header(struct fdisk_context *cxt,
1612 struct gpt_header *header, uint64_t lba)
1613{
1614 off_t offset = lba * cxt->sector_size;
1615
1616 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1617 goto fail;
1618 if (cxt->sector_size ==
1619 (size_t) write(cxt->dev_fd, header, cxt->sector_size))
1620 return 0;
1621fail:
1622 return -errno;
1623}
1624
1625/*
1626 * Write the protective MBR.
1627 * Returns 0 on success, or corresponding error otherwise.
1628 */
1629static int gpt_write_pmbr(struct fdisk_context *cxt)
1630{
1631 off_t offset;
1632 struct gpt_legacy_mbr *pmbr = NULL;
1633
9ffeb235
KZ
1634 assert(cxt);
1635 assert(cxt->firstsector);
766d5156
DB
1636
1637 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
1638
1639 /* zero out the legacy partitions */
1640 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
1641
1642 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
1643 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
1644 pmbr->partition_record[0].start_sector = 1;
1645 pmbr->partition_record[0].end_head = 0xFE;
1646 pmbr->partition_record[0].end_sector = 0xFF;
1647 pmbr->partition_record[0].end_track = 0xFF;
1648 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
1649
1650 /*
1651 * Set size_in_lba to the size of the disk minus one. If the size of the disk
1652 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
1653 */
1654 if (cxt->total_sectors - 1 > 0xFFFFFFFFULL)
1655 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
1656 else
1657 pmbr->partition_record[0].size_in_lba =
1658 cpu_to_le32(cxt->total_sectors - 1UL);
1659
1660 offset = GPT_PMBR_LBA * cxt->sector_size;
1661 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1662 goto fail;
1663
19613111
DB
1664 /* pMBR covers the first sector (LBA) of the disk */
1665 if (write_all(cxt->dev_fd, pmbr, cxt->sector_size))
1666 goto fail;
1667 return 0;
766d5156
DB
1668fail:
1669 return -errno;
1670}
1671
1672/*
1673 * Writes in-memory GPT and pMBR data to disk.
1674 * Returns 0 if successful write, otherwise, a corresponding error.
1675 * Any indication of error will abort the operation.
1676 */
9ffeb235 1677static int gpt_write_disklabel(struct fdisk_context *cxt)
766d5156 1678{
9ffeb235 1679 struct fdisk_gpt_label *gpt;
433d05ff 1680 int mbr_type;
d71ef5a4 1681
9ffeb235
KZ
1682 assert(cxt);
1683 assert(cxt->label);
aa36c2cf 1684 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1685
1686 gpt = self_label(cxt);
433d05ff 1687 mbr_type = valid_pmbr(cxt);
766d5156
DB
1688
1689 /* check that disk is big enough to handle the backup header */
c15aec86 1690 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
766d5156
DB
1691 goto err0;
1692
1693 /* check that the backup header is properly placed */
c15aec86 1694 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1)
766d5156
DB
1695 /* TODO: correct this (with user authorization) and write */
1696 goto err0;
1697
d71ef5a4 1698 if (partition_check_overlaps(gpt->pheader, gpt->ents))
766d5156
DB
1699 goto err0;
1700
1701 /* recompute CRCs for both headers */
d71ef5a4
KZ
1702 gpt_recompute_crc(gpt->pheader, gpt->ents);
1703 gpt_recompute_crc(gpt->bheader, gpt->ents);
766d5156
DB
1704
1705 /*
1706 * UEFI requires writing in this specific order:
1707 * 1) backup partition tables
1708 * 2) backup GPT header
1709 * 3) primary partition tables
1710 * 4) primary GPT header
1711 * 5) protective MBR
1712 *
1713 * If any write fails, we abort the rest.
1714 */
d71ef5a4 1715 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
766d5156 1716 goto err1;
c15aec86
KZ
1717 if (gpt_write_header(cxt, gpt->bheader,
1718 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
766d5156 1719 goto err1;
d71ef5a4 1720 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
766d5156 1721 goto err1;
d71ef5a4 1722 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
766d5156 1723 goto err1;
433d05ff
KZ
1724
1725 if (mbr_type == GPT_MBR_HYBRID)
1726 fdisk_warnx(cxt, _("The device contains hybrid MBR -- writing GPT only. "
1727 "You have to sync the MBR manually."));
1728 else if (gpt_write_pmbr(cxt) != 0)
766d5156
DB
1729 goto err1;
1730
88141067 1731 DBG(LABEL, ul_debug("GPT write success"));
766d5156
DB
1732 return 0;
1733err0:
88141067 1734 DBG(LABEL, ul_debug("GPT write failed: incorrect input"));
c15aec86 1735 errno = EINVAL;
766d5156
DB
1736 return -EINVAL;
1737err1:
88141067 1738 DBG(LABEL, ul_debug("GPT write failed: %m"));
766d5156
DB
1739 return -errno;
1740}
1741
1742/*
1743 * Verify data integrity and report any found problems for:
1744 * - primary and backup header validations
1745 * - paritition validations
1746 */
9ffeb235 1747static int gpt_verify_disklabel(struct fdisk_context *cxt)
766d5156 1748{
83df5feb
KZ
1749 int nerror = 0;
1750 unsigned int ptnum;
9ffeb235
KZ
1751 struct fdisk_gpt_label *gpt;
1752
1753 assert(cxt);
1754 assert(cxt->label);
aa36c2cf 1755 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1756
1757 gpt = self_label(cxt);
766d5156 1758
d71ef5a4 1759 if (!gpt || !gpt->bheader) {
766d5156 1760 nerror++;
83df5feb 1761 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
766d5156
DB
1762 }
1763
d71ef5a4 1764 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
766d5156 1765 nerror++;
83df5feb 1766 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
766d5156 1767 }
d71ef5a4 1768 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
766d5156 1769 nerror++;
83df5feb 1770 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
766d5156
DB
1771 }
1772
d71ef5a4 1773 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
766d5156 1774 nerror++;
83df5feb 1775 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
766d5156
DB
1776 }
1777
d71ef5a4 1778 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
766d5156 1779 nerror++;
83df5feb 1780 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
766d5156 1781 }
d71ef5a4 1782 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
766d5156 1783 nerror++;
83df5feb 1784 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
766d5156
DB
1785 }
1786
d71ef5a4 1787 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
766d5156 1788 nerror++;
83df5feb 1789 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
766d5156 1790 }
d71ef5a4 1791 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
766d5156 1792 nerror++;
83df5feb 1793 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
766d5156
DB
1794
1795 }
c15aec86 1796 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
766d5156 1797 nerror++;
a1e276ae 1798 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
766d5156
DB
1799 }
1800
1801 /*
1802 * if the GPT is the primary table, check the alternateLBA
1803 * to see if it is a valid GPT
1804 */
c15aec86
KZ
1805 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
1806 le64_to_cpu(gpt->bheader->alternative_lba))) {
766d5156 1807 nerror++;
83df5feb 1808 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
766d5156
DB
1809 }
1810
d71ef5a4 1811 ptnum = partition_check_overlaps(gpt->pheader, gpt->ents);
766d5156
DB
1812 if (ptnum) {
1813 nerror++;
83df5feb
KZ
1814 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
1815 ptnum, ptnum+1);
766d5156
DB
1816 }
1817
d71ef5a4 1818 ptnum = partition_check_too_big(gpt->pheader, gpt->ents, cxt->total_sectors);
766d5156
DB
1819 if (ptnum) {
1820 nerror++;
83df5feb
KZ
1821 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
1822 ptnum);
766d5156
DB
1823 }
1824
d71ef5a4 1825 ptnum = partition_start_after_end(gpt->pheader, gpt->ents);
766d5156
DB
1826 if (ptnum) {
1827 nerror++;
83df5feb
KZ
1828 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
1829 ptnum);
766d5156
DB
1830 }
1831
1832 if (!nerror) { /* yay :-) */
1833 uint32_t nsegments = 0;
1834 uint64_t free_sectors = 0, largest_segment = 0;
6d0ed4cb 1835 char *strsz = NULL;
766d5156 1836
ac1a559a 1837 fdisk_info(cxt, _("No errors detected."));
83df5feb
KZ
1838 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
1839 fdisk_info(cxt, _("Using %u out of %d partitions."),
d71ef5a4
KZ
1840 partitions_in_use(gpt->pheader, gpt->ents),
1841 le32_to_cpu(gpt->pheader->npartition_entries));
766d5156 1842
d71ef5a4 1843 free_sectors = get_free_sectors(cxt, gpt->pheader, gpt->ents,
766d5156 1844 &nsegments, &largest_segment);
6d0ed4cb
KZ
1845 if (largest_segment)
1846 strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER,
1847 largest_segment * cxt->sector_size);
1848
4ae11fe8 1849 fdisk_info(cxt,
829f4206
KZ
1850 P_("A total of %ju free sectors is available in %u segment.",
1851 "A total of %ju free sectors is available in %u segments "
6d0ed4cb
KZ
1852 "(the largest is %s).", nsegments),
1853 free_sectors, nsegments, strsz);
1854 free(strsz);
1855
766d5156 1856 } else
a1e276ae 1857 fdisk_warnx(cxt,
8e7f944d 1858 P_("%d error detected.", "%d errors detected.", nerror),
a1e276ae 1859 nerror);
766d5156
DB
1860
1861 return 0;
1862}
1863
1864/* Delete a single GPT partition, specified by partnum. */
8a95621d 1865static int gpt_delete_partition(struct fdisk_context *cxt,
9ffeb235 1866 size_t partnum)
766d5156 1867{
9ffeb235 1868 struct fdisk_gpt_label *gpt;
d71ef5a4 1869
9ffeb235
KZ
1870 assert(cxt);
1871 assert(cxt->label);
aa36c2cf 1872 assert(fdisk_is_label(cxt, GPT));
d71ef5a4 1873
9ffeb235
KZ
1874 gpt = self_label(cxt);
1875
1876 if (partnum >= cxt->label->nparts_max
1877 || partition_unused(&gpt->ents[partnum]))
1f5eb51b 1878 return -EINVAL;
766d5156
DB
1879
1880 /* hasta la vista, baby! */
d71ef5a4
KZ
1881 memset(&gpt->ents[partnum], 0, sizeof(struct gpt_entry));
1882 if (!partition_unused(&gpt->ents[partnum]))
1f5eb51b 1883 return -EINVAL;
766d5156 1884 else {
d71ef5a4
KZ
1885 gpt_recompute_crc(gpt->pheader, gpt->ents);
1886 gpt_recompute_crc(gpt->bheader, gpt->ents);
9ffeb235
KZ
1887 cxt->label->nparts_cur--;
1888 fdisk_label_set_changed(cxt->label, 1);
766d5156 1889 }
1f5eb51b
DB
1890
1891 return 0;
766d5156
DB
1892}
1893
080633e4 1894
766d5156 1895/* Performs logical checks to add a new partition entry */
8a95621d
KZ
1896static int gpt_add_partition(
1897 struct fdisk_context *cxt,
c3bc7483
KZ
1898 struct fdisk_partition *pa,
1899 size_t *partno)
766d5156 1900{
512a430f
KZ
1901 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
1902 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
1903 uint64_t dflt_f, dflt_l; /* largest segment (default) */
c0d14b09 1904 struct gpt_guid typeid;
9ffeb235 1905 struct fdisk_gpt_label *gpt;
d71ef5a4 1906 struct gpt_header *pheader;
8d95e7e0 1907 struct gpt_entry *e, *ents;
4114da08 1908 struct fdisk_ask *ask = NULL;
77d6a70a 1909 size_t partnum;
4114da08 1910 int rc;
766d5156 1911
9ffeb235
KZ
1912 assert(cxt);
1913 assert(cxt->label);
aa36c2cf 1914 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
1915
1916 gpt = self_label(cxt);
d71ef5a4
KZ
1917 pheader = gpt->pheader;
1918 ents = gpt->ents;
1919
6c89f750 1920 rc = fdisk_partition_next_partno(pa, cxt, &partnum);
1240f549 1921 if (rc) {
88141067 1922 DBG(LABEL, ul_debug("GPT failed to get next partno"));
77d6a70a 1923 return rc;
1240f549 1924 }
874aa9c3 1925 if (!partition_unused(&ents[partnum])) {
829f4206 1926 fdisk_warnx(cxt, _("Partition %zu is already defined. "
83217641 1927 "Delete it before re-adding it."), partnum +1);
77d6a70a 1928 return -ERANGE;
766d5156 1929 }
d71ef5a4
KZ
1930 if (le32_to_cpu(pheader->npartition_entries) ==
1931 partitions_in_use(pheader, ents)) {
83df5feb 1932 fdisk_warnx(cxt, _("All partitions are already in use."));
77d6a70a 1933 return -ENOSPC;
766d5156 1934 }
512a430f 1935 if (!get_free_sectors(cxt, pheader, ents, NULL, NULL)) {
83df5feb 1936 fdisk_warnx(cxt, _("No free sectors available."));
8254c3a5 1937 return -ENOSPC;
766d5156
DB
1938 }
1939
77d6a70a
KZ
1940 string_to_guid(pa && pa->type && pa->type->typestr ?
1941 pa->type->typestr:
1942 GPT_DEFAULT_ENTRY_TYPE, &typeid);
1943
512a430f
KZ
1944 disk_f = find_first_available(pheader, ents, 0);
1945 disk_l = find_last_free_sector(pheader, ents);
1946
1947 /* the default is the largest free space */
1948 dflt_f = find_first_in_largest(pheader, ents);
1949 dflt_l = find_last_free(pheader, ents, dflt_f);
1950
1951 /* align the default in range <dflt_f,dflt_l>*/
9475cc78 1952 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
766d5156 1953
77d6a70a 1954 /* first sector */
ecf40cda
KZ
1955 if (pa && pa->start_follow_default) {
1956 user_f = dflt_f;
1957
1958 } else if (pa && fdisk_partition_has_start(pa)) {
ee50336c 1959 DBG(LABEL, ul_debug("first sector defined: %ju", pa->start));
77d6a70a
KZ
1960 if (pa->start != find_first_available(pheader, ents, pa->start)) {
1961 fdisk_warnx(cxt, _("Sector %ju already used."), pa->start);
1962 return -ERANGE;
e3443e8f 1963 }
77d6a70a 1964 user_f = pa->start;
77d6a70a
KZ
1965 } else {
1966 /* ask by dialog */
1967 for (;;) {
1968 if (!ask)
1969 ask = fdisk_new_ask();
1970 else
1971 fdisk_reset_ask(ask);
1972
1973 /* First sector */
1974 fdisk_ask_set_query(ask, _("First sector"));
1975 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
1976 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
1977 fdisk_ask_number_set_default(ask, dflt_f); /* default */
1978 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
1979
1980 rc = fdisk_do_ask(cxt, ask);
1981 if (rc)
1982 goto done;
1983
1984 user_f = fdisk_ask_number_get_result(ask);
1985 if (user_f != find_first_available(pheader, ents, user_f)) {
1986 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
1987 continue;
1988 }
512a430f 1989 break;
77d6a70a
KZ
1990 }
1991 }
1992
1240f549 1993
77d6a70a
KZ
1994 /* Last sector */
1995 dflt_l = find_last_free(pheader, ents, user_f);
1996
ecf40cda
KZ
1997 if (pa && pa->end_follow_default) {
1998 user_l = dflt_l;
1999
2000 } else if (pa && fdisk_partition_has_size(pa)) {
ee50336c
KZ
2001 user_l = user_f + pa->size - 1;
2002 DBG(LABEL, ul_debug("size defined: %ju, end: %ju (last possible: %ju)",
2003 pa->size, user_l, dflt_l));
18b266ce 2004 if (user_l != dflt_l && !pa->size_explicit)
ee50336c 2005 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l) - 1;
1240f549 2006
77d6a70a
KZ
2007 } else {
2008 for (;;) {
2009 if (!ask)
2010 ask = fdisk_new_ask();
2011 else
2012 fdisk_reset_ask(ask);
2013
2014 fdisk_ask_set_query(ask, _("Last sector, +sectors or +size{K,M,G,T,P}"));
2015 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
2016 fdisk_ask_number_set_low(ask, user_f); /* minimal */
2017 fdisk_ask_number_set_default(ask, dflt_l); /* default */
2018 fdisk_ask_number_set_high(ask, dflt_l); /* maximal */
2019 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
2020 fdisk_ask_number_set_unit(ask, cxt->sector_size);
2021
2022 rc = fdisk_do_ask(cxt, ask);
2023 if (rc)
2024 goto done;
2025
2026 user_l = fdisk_ask_number_get_result(ask);
1240f549 2027 if (fdisk_ask_number_is_relative(ask)) {
77d6a70a 2028 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l) - 1;
8d6ec09a
KZ
2029
2030 /* no space for anything useful, use all space
1240f549 2031 if (user_l + (cxt->grain / cxt->sector_size) > dflt_l)
8d6ec09a
KZ
2032 user_l = dflt_l;
2033 */
0c344037 2034 }
18b266ce
KZ
2035
2036 if (user_l > user_f && user_l <= disk_l)
77d6a70a
KZ
2037 break;
2038 }
766d5156
DB
2039 }
2040
8d95e7e0
KZ
2041
2042 if (user_f > user_l || partnum >= cxt->label->nparts_max) {
27aadd8b 2043 fdisk_warnx(cxt, _("Could not create partition %zu"), partnum + 1);
8d95e7e0 2044 rc = -EINVAL;
1240f549 2045 goto done;
8d95e7e0
KZ
2046 }
2047
ecf40cda
KZ
2048 assert(!FDISK_IS_UNDEF(user_l));
2049 assert(!FDISK_IS_UNDEF(user_f));
2050
8d95e7e0
KZ
2051 e = &ents[partnum];
2052 e->lba_end = cpu_to_le64(user_l);
2053 e->lba_start = cpu_to_le64(user_f);
2054
2055 gpt_entry_set_type(e, &typeid);
2056
2057 if (pa && pa->uuid) {
2058 /* Sometimes it's necessary to create a copy of the PT and
2059 * reuse already defined UUID
2060 */
2061 rc = gpt_entry_set_uuid(e, pa->uuid);
2062 if (rc)
2063 goto done;
1240f549 2064 } else {
8d95e7e0
KZ
2065 /* Any time a new partition entry is created a new GUID must be
2066 * generated for that partition, and every partition is guaranteed
2067 * to have a unique GUID.
2068 */
2069 uuid_generate_random((unsigned char *) &e->partition_guid);
2070 swap_efi_guid(&e->partition_guid);
2071 }
2072
2073 if (pa && pa->name && *pa->name)
2074 gpt_entry_set_name(e, pa->name);
c77ba531
KZ
2075 if (pa && pa->attrs)
2076 gpt_entry_attrs_from_string(cxt, e, pa->attrs);
8d95e7e0 2077
ee50336c
KZ
2078 DBG(LABEL, ul_debug("GPT new partition: partno=%zu, start=%ju, end=%ju, size=%ju",
2079 partnum,
2080 gpt_partition_start(e),
2081 gpt_partition_end(e),
2082 gpt_partition_size(e)));
2083
8d95e7e0
KZ
2084 gpt_recompute_crc(gpt->pheader, ents);
2085 gpt_recompute_crc(gpt->bheader, ents);
2086
2087 /* report result */
2088 {
a01b5b70
KZ
2089 struct fdisk_parttype *t;
2090
9ffeb235
KZ
2091 cxt->label->nparts_cur++;
2092 fdisk_label_set_changed(cxt->label, 1);
a01b5b70 2093
7f539277 2094 t = gpt_partition_parttype(cxt, &ents[partnum]);
a01b5b70
KZ
2095 fdisk_info_new_partition(cxt, partnum + 1, user_f, user_l, t);
2096 fdisk_free_parttype(t);
9fcd49d5 2097 }
8254c3a5 2098
4114da08 2099 rc = 0;
c3bc7483
KZ
2100 if (partno)
2101 *partno = partnum;
4114da08
KZ
2102done:
2103 fdisk_free_ask(ask);
2104 return rc;
766d5156
DB
2105}
2106
3f731001
DB
2107/*
2108 * Create a new GPT disklabel - destroys any previous data.
2109 */
9ffeb235 2110static int gpt_create_disklabel(struct fdisk_context *cxt)
3f731001
DB
2111{
2112 int rc = 0;
46667ba4 2113 ssize_t esz = 0;
21fe3dde 2114 char str[37];
9ffeb235
KZ
2115 struct fdisk_gpt_label *gpt;
2116
2117 assert(cxt);
2118 assert(cxt->label);
aa36c2cf 2119 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
2120
2121 gpt = self_label(cxt);
3f731001 2122
d71ef5a4 2123 /* label private stuff has to be empty, see gpt_deinit() */
d71ef5a4
KZ
2124 assert(gpt->pheader == NULL);
2125 assert(gpt->bheader == NULL);
4e0e8253 2126
3f731001 2127 /*
3f731001
DB
2128 * When no header, entries or pmbr is set, we're probably
2129 * dealing with a new, empty disk - so always allocate memory
2130 * to deal with the data structures whatever the case is.
2131 */
3f731001
DB
2132 rc = gpt_mknew_pmbr(cxt);
2133 if (rc < 0)
2134 goto done;
2135
d71ef5a4 2136 /* primary */
46667ba4
KZ
2137 gpt->pheader = calloc(1, sizeof(*gpt->pheader));
2138 if (!gpt->pheader) {
2139 rc = -ENOMEM;
2140 goto done;
2141 }
d71ef5a4 2142 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
3f731001
DB
2143 if (rc < 0)
2144 goto done;
2145
d71ef5a4 2146 /* backup ("copy" primary) */
46667ba4
KZ
2147 gpt->bheader = calloc(1, sizeof(*gpt->bheader));
2148 if (!gpt->bheader) {
2149 rc = -ENOMEM;
2150 goto done;
2151 }
d71ef5a4
KZ
2152 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
2153 last_lba(cxt), gpt->pheader);
3f731001
DB
2154 if (rc < 0)
2155 goto done;
2156
46667ba4
KZ
2157 esz = le32_to_cpu(gpt->pheader->npartition_entries) *
2158 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
2159 gpt->ents = calloc(1, esz);
2160 if (!gpt->ents) {
2161 rc = -ENOMEM;
2162 goto done;
2163 }
d71ef5a4
KZ
2164 gpt_recompute_crc(gpt->pheader, gpt->ents);
2165 gpt_recompute_crc(gpt->bheader, gpt->ents);
3f731001 2166
9ffeb235
KZ
2167 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
2168 cxt->label->nparts_cur = 0;
9fcd49d5 2169
21fe3dde 2170 guid_to_string(&gpt->pheader->disk_guid, str);
9ffeb235 2171 fdisk_label_set_changed(cxt->label, 1);
ac1a559a 2172 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
d6060cd3 2173 _("Created a new GPT disklabel (GUID: %s)."), str);
3f731001
DB
2174done:
2175 return rc;
2176}
2177
21fe3dde
KZ
2178static int gpt_get_disklabel_id(struct fdisk_context *cxt, char **id)
2179{
2180 struct fdisk_gpt_label *gpt;
2181 char str[37];
2182
2183 assert(cxt);
2184 assert(id);
2185 assert(cxt->label);
aa36c2cf 2186 assert(fdisk_is_label(cxt, GPT));
21fe3dde
KZ
2187
2188 gpt = self_label(cxt);
2189 guid_to_string(&gpt->pheader->disk_guid, str);
2190
2191 *id = strdup(str);
2192 if (!*id)
2193 return -ENOMEM;
2194 return 0;
2195}
2196
35b1f0a4
KZ
2197static int gpt_set_disklabel_id(struct fdisk_context *cxt)
2198{
2199 struct fdisk_gpt_label *gpt;
2200 struct gpt_guid uuid;
2201 char *str, *old, *new;
2202 int rc;
2203
2204 assert(cxt);
2205 assert(cxt->label);
aa36c2cf 2206 assert(fdisk_is_label(cxt, GPT));
35b1f0a4
KZ
2207
2208 gpt = self_label(cxt);
2209 if (fdisk_ask_string(cxt,
2210 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &str))
2211 return -EINVAL;
2212
2213 rc = string_to_guid(str, &uuid);
2214 free(str);
2215
2216 if (rc) {
2217 fdisk_warnx(cxt, _("Failed to parse your UUID."));
2218 return rc;
2219 }
2220
2221 gpt_get_disklabel_id(cxt, &old);
2222
2223 gpt->pheader->disk_guid = uuid;
2224 gpt->bheader->disk_guid = uuid;
2225
2226 gpt_recompute_crc(gpt->pheader, gpt->ents);
2227 gpt_recompute_crc(gpt->bheader, gpt->ents);
2228
2229 gpt_get_disklabel_id(cxt, &new);
2230
ac1a559a
KZ
2231 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2232 _("Disk identifier changed from %s to %s."), old, new);
35b1f0a4
KZ
2233
2234 free(old);
2235 free(new);
2236 fdisk_label_set_changed(cxt->label, 1);
2237 return 0;
2238}
2239
8c0a7f91 2240static int gpt_part_is_used(struct fdisk_context *cxt, size_t i)
47b8e7c0 2241{
9ffeb235 2242 struct fdisk_gpt_label *gpt;
47b8e7c0
KZ
2243 struct gpt_entry *e;
2244
9ffeb235
KZ
2245 assert(cxt);
2246 assert(cxt->label);
aa36c2cf 2247 assert(fdisk_is_label(cxt, GPT));
9ffeb235
KZ
2248
2249 gpt = self_label(cxt);
2250
8c0a7f91
KZ
2251 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2252 return 0;
47b8e7c0 2253 e = &gpt->ents[i];
47b8e7c0 2254
8c0a7f91 2255 return !partition_unused(e) || gpt_partition_start(e);
47b8e7c0
KZ
2256}
2257
433d05ff
KZ
2258int fdisk_gpt_is_hybrid(struct fdisk_context *cxt)
2259{
2260 assert(cxt);
2261 return valid_pmbr(cxt) == GPT_MBR_HYBRID;
2262}
2263
c83f772e
KZ
2264static int gpt_toggle_partition_flag(
2265 struct fdisk_context *cxt,
2266 size_t i,
2267 unsigned long flag)
2268{
2269 struct fdisk_gpt_label *gpt;
01086b80
KZ
2270 uint64_t attrs, tmp;
2271 char *bits;
2272 const char *name = NULL;
2273 int bit = -1, rc;
c83f772e
KZ
2274
2275 assert(cxt);
2276 assert(cxt->label);
aa36c2cf 2277 assert(fdisk_is_label(cxt, GPT));
c83f772e 2278
88141067 2279 DBG(LABEL, ul_debug("GPT entry attribute change requested partno=%zu", i));
c83f772e
KZ
2280 gpt = self_label(cxt);
2281
2282 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2283 return -EINVAL;
2284
01086b80
KZ
2285 attrs = le64_to_cpu(gpt->ents[i].attrs);
2286 bits = (char *) &attrs;
c83f772e
KZ
2287
2288 switch (flag) {
2289 case GPT_FLAG_REQUIRED:
01086b80
KZ
2290 bit = GPT_ATTRBIT_REQ;
2291 name = GPT_ATTRSTR_REQ;
c83f772e
KZ
2292 break;
2293 case GPT_FLAG_NOBLOCK:
01086b80
KZ
2294 bit = GPT_ATTRBIT_NOBLOCK;
2295 name = GPT_ATTRSTR_NOBLOCK;
c83f772e
KZ
2296 break;
2297 case GPT_FLAG_LEGACYBOOT:
01086b80
KZ
2298 bit = GPT_ATTRBIT_LEGACY;
2299 name = GPT_ATTRSTR_LEGACY;
c83f772e
KZ
2300 break;
2301 case GPT_FLAG_GUIDSPECIFIC:
01086b80 2302 rc = fdisk_ask_number(cxt, 48, 48, 63, _("Enter GUID specific bit"), &tmp);
c83f772e
KZ
2303 if (rc)
2304 return rc;
01086b80
KZ
2305 bit = tmp;
2306 break;
773aae5c
KZ
2307 default:
2308 /* already specified PT_FLAG_GUIDSPECIFIC bit */
2309 if (flag >= 48 && flag <= 63) {
2310 bit = flag;
2311 flag = GPT_FLAG_GUIDSPECIFIC;
2312 }
2313 break;
01086b80 2314 }
c83f772e 2315
773aae5c
KZ
2316 if (bit < 0) {
2317 fdisk_warnx(cxt, _("failed to toggle unsupported bit %lu"), flag);
01086b80 2318 return -EINVAL;
773aae5c 2319 }
01086b80
KZ
2320
2321 if (!isset(bits, bit))
2322 setbit(bits, bit);
2323 else
2324 clrbit(bits, bit);
2325
2326 gpt->ents[i].attrs = cpu_to_le64(attrs);
2327
2328 if (flag == GPT_FLAG_GUIDSPECIFIC)
c83f772e 2329 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
01086b80
KZ
2330 isset(bits, bit) ?
2331 _("The GUID specific bit %d on partition %zu is enabled now.") :
2332 _("The GUID specific bit %d on partition %zu is disabled now."),
c83f772e 2333 bit, i + 1);
01086b80
KZ
2334 else
2335 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2336 isset(bits, bit) ?
2337 _("The %s flag on partition %zu is enabled now.") :
2338 _("The %s flag on partition %zu is disabled now."),
2339 name, i + 1);
c83f772e
KZ
2340
2341 gpt_recompute_crc(gpt->pheader, gpt->ents);
2342 gpt_recompute_crc(gpt->bheader, gpt->ents);
01086b80 2343 fdisk_label_set_changed(cxt->label, 1);
c83f772e
KZ
2344 return 0;
2345}
1054699c 2346
9348ef25
KZ
2347static int gpt_entry_cmp_start(const void *a, const void *b)
2348{
2349 struct gpt_entry *ae = (struct gpt_entry *) a,
2350 *be = (struct gpt_entry *) b;
2351 int au = partition_unused(ae),
2352 bu = partition_unused(be);
2353
2354 if (au && bu)
2355 return 0;
2356 if (au)
2357 return 1;
2358 if (bu)
2359 return -1;
2360
2361 return gpt_partition_start(ae) - gpt_partition_start(be);
2362}
2363
2364/* sort partition by start sector */
2365static int gpt_reorder(struct fdisk_context *cxt)
2366{
2367 struct fdisk_gpt_label *gpt;
2368 size_t nparts;
2369
2370 assert(cxt);
2371 assert(cxt->label);
aa36c2cf 2372 assert(fdisk_is_label(cxt, GPT));
9348ef25
KZ
2373
2374 gpt = self_label(cxt);
2375 nparts = le32_to_cpu(gpt->pheader->npartition_entries);
2376
2377 qsort(gpt->ents, nparts, sizeof(struct gpt_entry),
2378 gpt_entry_cmp_start);
2379
2380 gpt_recompute_crc(gpt->pheader, gpt->ents);
2381 gpt_recompute_crc(gpt->bheader, gpt->ents);
2382 fdisk_label_set_changed(cxt->label, 1);
2383
2384 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS, _("Done."));
2385 return 0;
2386}
2387
1240f549
KZ
2388static int gpt_reset_alignment(struct fdisk_context *cxt)
2389{
2390 struct fdisk_gpt_label *gpt;
2391 struct gpt_header *h;
2392
2393 assert(cxt);
2394 assert(cxt->label);
aa36c2cf 2395 assert(fdisk_is_label(cxt, GPT));
1240f549
KZ
2396
2397 gpt = self_label(cxt);
2398 h = gpt ? gpt->pheader : NULL;
2399
2400 if (h) {
2401 /* always follow existing table */
2402 cxt->first_lba = h->first_usable_lba;
2403 cxt->last_lba = h->last_usable_lba;
2404 } else {
2405 /* estimate ranges for GPT */
2406 uint64_t first, last;
2407
2408 count_first_last_lba(cxt, &first, &last);
2409
2410 if (cxt->first_lba < first)
2411 cxt->first_lba = first;
2412 if (cxt->last_lba > last)
2413 cxt->last_lba = last;
2414 }
2415
2416 return 0;
2417}
4e0e8253
KZ
2418/*
2419 * Deinitialize fdisk-specific variables
2420 */
d71ef5a4 2421static void gpt_deinit(struct fdisk_label *lb)
4e0e8253 2422{
d71ef5a4
KZ
2423 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
2424
2425 if (!gpt)
2426 return;
2427
2428 free(gpt->ents);
2429 free(gpt->pheader);
2430 free(gpt->bheader);
2431
2432 gpt->ents = NULL;
2433 gpt->pheader = NULL;
2434 gpt->bheader = NULL;
4e0e8253
KZ
2435}
2436
0c5d095e 2437static const struct fdisk_label_operations gpt_operations =
766d5156 2438{
0c5d095e
KZ
2439 .probe = gpt_probe_label,
2440 .write = gpt_write_disklabel,
2441 .verify = gpt_verify_disklabel,
2442 .create = gpt_create_disklabel,
3c5fb475 2443 .list = gpt_list_disklabel,
775001ad 2444 .locate = gpt_locate_disklabel,
9348ef25 2445 .reorder = gpt_reorder,
21fe3dde 2446 .get_id = gpt_get_disklabel_id,
35b1f0a4 2447 .set_id = gpt_set_disklabel_id,
21fe3dde 2448
8c0a7f91 2449 .get_part = gpt_get_partition,
b0a484a8 2450 .set_part = gpt_set_partition,
77d6a70a 2451 .add_part = gpt_add_partition,
e11c6684 2452 .del_part = gpt_delete_partition,
8c0a7f91
KZ
2453
2454 .part_is_used = gpt_part_is_used,
c83f772e 2455 .part_toggle_flag = gpt_toggle_partition_flag,
4e0e8253 2456
1240f549
KZ
2457 .deinit = gpt_deinit,
2458
2459 .reset_alignment = gpt_reset_alignment
766d5156 2460};
0c5d095e 2461
bd85d11f 2462static const struct fdisk_field gpt_fields[] =
6941952e
KZ
2463{
2464 /* basic */
bd85d11f
KZ
2465 { FDISK_FIELD_DEVICE, N_("Device"), 10, 0 },
2466 { FDISK_FIELD_START, N_("Start"), 5, FDISK_FIELDFL_NUMBER },
2467 { FDISK_FIELD_END, N_("End"), 5, FDISK_FIELDFL_NUMBER },
2468 { FDISK_FIELD_SECTORS, N_("Sectors"), 5, FDISK_FIELDFL_NUMBER },
bd85d11f
KZ
2469 { FDISK_FIELD_SIZE, N_("Size"), 5, FDISK_FIELDFL_NUMBER | FDISK_FIELDFL_EYECANDY },
2470 { FDISK_FIELD_TYPE, N_("Type"), 0.1, FDISK_FIELDFL_EYECANDY },
6941952e 2471 /* expert */
bd85d11f
KZ
2472 { FDISK_FIELD_TYPEID, N_("Type-UUID"), 36, FDISK_FIELDFL_DETAIL },
2473 { FDISK_FIELD_UUID, N_("UUID"), 36, FDISK_FIELDFL_DETAIL },
2474 { FDISK_FIELD_NAME, N_("Name"), 0.2, FDISK_FIELDFL_DETAIL },
2475 { FDISK_FIELD_ATTR, N_("Attrs"), 0, FDISK_FIELDFL_DETAIL }
6941952e
KZ
2476};
2477
0c5d095e
KZ
2478/*
2479 * allocates GPT in-memory stuff
2480 */
2481struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt)
2482{
2483 struct fdisk_label *lb;
2484 struct fdisk_gpt_label *gpt;
2485
2486 assert(cxt);
2487
2488 gpt = calloc(1, sizeof(*gpt));
2489 if (!gpt)
2490 return NULL;
2491
2492 /* initialize generic part of the driver */
2493 lb = (struct fdisk_label *) gpt;
2494 lb->name = "gpt";
53b422ab 2495 lb->id = FDISK_DISKLABEL_GPT;
0c5d095e
KZ
2496 lb->op = &gpt_operations;
2497 lb->parttypes = gpt_parttypes;
2498 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
2499
bd85d11f
KZ
2500 lb->fields = gpt_fields;
2501 lb->nfields = ARRAY_SIZE(gpt_fields);
6941952e 2502
0c5d095e
KZ
2503 return lb;
2504}