1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright (C) 2008 RuggedCom, Inc.
4 * Richard Retanubun <RichardRetanubun@RuggedCom.com>
5 */
6
7/*
8 * NOTE:
9 *   when CONFIG_SYS_64BIT_LBA is not defined, lbaint_t is 32 bits; this
10 *   limits the maximum size of addressable storage to < 2 tebibytes
11 */
12
13#define LOG_CATEGORY LOGC_FS
14
15#include <common.h>
16#include <blk.h>
17#include <log.h>
18#include <part.h>
19#include <uuid.h>
20#include <asm/cache.h>
21#include <asm/global_data.h>
22#include <asm/unaligned.h>
23#include <command.h>
24#include <fdtdec.h>
25#include <ide.h>
26#include <malloc.h>
27#include <memalign.h>
28#include <part_efi.h>
29#include <dm/ofnode.h>
30#include <linux/compiler.h>
31#include <linux/ctype.h>
32#include <linux/printk.h>
33#include <u-boot/crc.h>
34
35/* GUID for basic data partitons */
36#if CONFIG_IS_ENABLED(EFI_PARTITION)
37static const efi_guid_t partition_basic_data_guid = PARTITION_BASIC_DATA_GUID;
38#endif
39
40/**
41 * efi_crc32() - EFI version of crc32 function
42 * @buf: buffer to calculate crc32 of
43 * @len - length of buf
44 *
45 * Description: Returns EFI-style CRC32 value for @buf
46 */
47static inline u32 efi_crc32(const void *buf, u32 len)
48{
49	return crc32(0, buf, len);
50}
51
52/*
53 * Private function prototypes
54 */
55
56static int pmbr_part_valid(struct partition *part);
57static int is_pmbr_valid(legacy_mbr * mbr);
58static int is_gpt_valid(struct blk_desc *desc, u64 lba, gpt_header *pgpt_head,
59			gpt_entry **pgpt_pte);
60static gpt_entry *alloc_read_gpt_entries(struct blk_desc *desc,
61					 gpt_header *pgpt_head);
62static int is_pte_valid(gpt_entry * pte);
63static int find_valid_gpt(struct blk_desc *desc, gpt_header *gpt_head,
64			  gpt_entry **pgpt_pte);
65
66static char *print_efiname(gpt_entry *pte)
67{
68	static char name[PARTNAME_SZ + 1];
69	int i;
70	for (i = 0; i < PARTNAME_SZ; i++) {
71		u8 c;
72		c = pte->partition_name[i] & 0xff;
73		c = (c && !isprint(c)) ? '.' : c;
74		name[i] = c;
75	}
76	name[PARTNAME_SZ] = 0;
77	return name;
78}
79
80static const efi_guid_t system_guid = PARTITION_SYSTEM_GUID;
81
82static int get_bootable(gpt_entry *p)
83{
84	int ret = 0;
85
86	if (!memcmp(&p->partition_type_guid, &system_guid, sizeof(efi_guid_t)))
87		ret |=  PART_EFI_SYSTEM_PARTITION;
88	if (p->attributes.fields.legacy_bios_bootable)
89		ret |=  PART_BOOTABLE;
90	return ret;
91}
92
93static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
94		lbaint_t lastlba)
95{
96	uint32_t crc32_backup = 0;
97	uint32_t calc_crc32;
98
99	/* Check the GPT header signature */
100	if (le64_to_cpu(gpt_h->signature) != GPT_HEADER_SIGNATURE_UBOOT) {
101		log_debug("%s signature is wrong: %#llX != %#llX\n",
102			  "GUID Partition Table Header",
103			  le64_to_cpu(gpt_h->signature),
104			  GPT_HEADER_SIGNATURE_UBOOT);
105		return -1;
106	}
107
108	/* Check the GUID Partition Table CRC */
109	memcpy(&crc32_backup, &gpt_h->header_crc32, sizeof(crc32_backup));
110	memset(&gpt_h->header_crc32, 0, sizeof(gpt_h->header_crc32));
111
112	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
113		le32_to_cpu(gpt_h->header_size));
114
115	memcpy(&gpt_h->header_crc32, &crc32_backup, sizeof(crc32_backup));
116
117	if (calc_crc32 != le32_to_cpu(crc32_backup)) {
118		log_debug("%s: CRC is wrong: %#x != %#x\n",
119			  "GUID Partition Table Header",
120			  le32_to_cpu(crc32_backup), calc_crc32);
121		return -1;
122	}
123
124	/*
125	 * Check that the my_lba entry points to the LBA that contains the GPT
126	 */
127	if (le64_to_cpu(gpt_h->my_lba) != lba) {
128		log_debug("GPT: my_lba incorrect: %llX != " LBAF "\n",
129			  le64_to_cpu(gpt_h->my_lba), lba);
130		return -1;
131	}
132
133	/*
134	 * Check that the first_usable_lba and that the last_usable_lba are
135	 * within the disk.
136	 */
137	if (le64_to_cpu(gpt_h->first_usable_lba) > lastlba) {
138		log_debug("GPT: first_usable_lba incorrect: %llX > " LBAF "\n",
139			  le64_to_cpu(gpt_h->first_usable_lba), lastlba);
140		return -1;
141	}
142	if (le64_to_cpu(gpt_h->last_usable_lba) > lastlba) {
143		log_debug("GPT: last_usable_lba incorrect: %llX > " LBAF "\n",
144			  le64_to_cpu(gpt_h->last_usable_lba), lastlba);
145		return -1;
146	}
147
148	debug("GPT: first_usable_lba: %llX last_usable_lba: %llX last lba: "
149	      LBAF "\n", le64_to_cpu(gpt_h->first_usable_lba),
150	      le64_to_cpu(gpt_h->last_usable_lba), lastlba);
151
152	return 0;
153}
154
155static int validate_gpt_entries(gpt_header *gpt_h, gpt_entry *gpt_e)
156{
157	uint32_t calc_crc32;
158
159	/* Check the GUID Partition Table Entry Array CRC */
160	calc_crc32 = efi_crc32((const unsigned char *)gpt_e,
161		le32_to_cpu(gpt_h->num_partition_entries) *
162		le32_to_cpu(gpt_h->sizeof_partition_entry));
163
164	if (calc_crc32 != le32_to_cpu(gpt_h->partition_entry_array_crc32)) {
165		log_debug("%s: %#x != %#x\n",
166			  "GUID Partition Table Entry Array CRC is wrong",
167			  le32_to_cpu(gpt_h->partition_entry_array_crc32),
168			  calc_crc32);
169		return -1;
170	}
171
172	return 0;
173}
174
175static void prepare_backup_gpt_header(gpt_header *gpt_h)
176{
177	uint32_t calc_crc32;
178	uint64_t val;
179
180	/* recalculate the values for the Backup GPT Header */
181	val = le64_to_cpu(gpt_h->my_lba);
182	gpt_h->my_lba = gpt_h->alternate_lba;
183	gpt_h->alternate_lba = cpu_to_le64(val);
184	gpt_h->partition_entry_lba =
185			cpu_to_le64(le64_to_cpu(gpt_h->last_usable_lba) + 1);
186	gpt_h->header_crc32 = 0;
187
188	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
189			       le32_to_cpu(gpt_h->header_size));
190	gpt_h->header_crc32 = cpu_to_le32(calc_crc32);
191}
192
193#if CONFIG_IS_ENABLED(EFI_PARTITION)
194/*
195 * Public Functions (include/part.h)
196 */
197
198/*
199 * UUID is displayed as 32 hexadecimal digits, in 5 groups,
200 * separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters
201 */
202int get_disk_guid(struct blk_desc *desc, char *guid)
203{
204	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1, desc->blksz);
205	gpt_entry *gpt_pte = NULL;
206	unsigned char *guid_bin;
207
208	/* This function validates AND fills in the GPT header and PTE */
209	if (find_valid_gpt(desc, gpt_head, &gpt_pte) != 1)
210		return -EINVAL;
211
212	guid_bin = gpt_head->disk_guid.b;
213	uuid_bin_to_str(guid_bin, guid, UUID_STR_FORMAT_GUID);
214
215	/* Remember to free pte */
216	free(gpt_pte);
217	return 0;
218}
219
220void part_print_efi(struct blk_desc *desc)
221{
222	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1, desc->blksz);
223	gpt_entry *gpt_pte = NULL;
224	int i = 0;
225	unsigned char *uuid;
226
227	/* This function validates AND fills in the GPT header and PTE */
228	if (find_valid_gpt(desc, gpt_head, &gpt_pte) != 1)
229		return;
230
231	debug("%s: gpt-entry at %p\n", __func__, gpt_pte);
232
233	printf("Part\tStart LBA\tEnd LBA\t\tName\n");
234	printf("\tAttributes\n");
235	printf("\tType GUID\n");
236	printf("\tPartition GUID\n");
237
238	for (i = 0; i < le32_to_cpu(gpt_head->num_partition_entries); i++) {
239		/* Skip invalid PTE */
240		if (!is_pte_valid(&gpt_pte[i]))
241			continue;
242
243		printf("%3d\t0x%08llx\t0x%08llx\t\"%s\"\n", (i + 1),
244			le64_to_cpu(gpt_pte[i].starting_lba),
245			le64_to_cpu(gpt_pte[i].ending_lba),
246			print_efiname(&gpt_pte[i]));
247		printf("\tattrs:\t0x%016llx\n", gpt_pte[i].attributes.raw);
248		uuid = (unsigned char *)gpt_pte[i].partition_type_guid.b;
249		if (IS_ENABLED(CONFIG_PARTITION_TYPE_GUID))
250			printf("\ttype:\t%pUl\n\t\t(%pUs)\n", uuid, uuid);
251		else
252			printf("\ttype:\t%pUl\n", uuid);
253		uuid = (unsigned char *)gpt_pte[i].unique_partition_guid.b;
254		printf("\tguid:\t%pUl\n", uuid);
255	}
256
257	/* Remember to free pte */
258	free(gpt_pte);
259	return;
260}
261
262int part_get_info_efi(struct blk_desc *desc, int part,
263		      struct disk_partition *info)
264{
265	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1, desc->blksz);
266	gpt_entry *gpt_pte = NULL;
267
268	/* "part" argument must be at least 1 */
269	if (part < 1) {
270		log_debug("Invalid Argument(s)\n");
271		return -EINVAL;
272	}
273
274	/* This function validates AND fills in the GPT header and PTE */
275	if (find_valid_gpt(desc, gpt_head, &gpt_pte) != 1)
276		return -EINVAL;
277
278	if (part > le32_to_cpu(gpt_head->num_partition_entries) ||
279	    !is_pte_valid(&gpt_pte[part - 1])) {
280		log_debug("Invalid partition number %d\n", part);
281		free(gpt_pte);
282		return -EPERM;
283	}
284
285	/* The 'lbaint_t' casting may limit the maximum disk size to 2 TB */
286	info->start = (lbaint_t)le64_to_cpu(gpt_pte[part - 1].starting_lba);
287	/* The ending LBA is inclusive, to calculate size, add 1 to it */
288	info->size = (lbaint_t)le64_to_cpu(gpt_pte[part - 1].ending_lba) + 1
289		     - info->start;
290	info->blksz = desc->blksz;
291
292	snprintf((char *)info->name, sizeof(info->name), "%s",
293		 print_efiname(&gpt_pte[part - 1]));
294	strcpy((char *)info->type, "U-Boot");
295	info->bootable = get_bootable(&gpt_pte[part - 1]);
296	if (CONFIG_IS_ENABLED(PARTITION_UUIDS)) {
297		uuid_bin_to_str(gpt_pte[part - 1].unique_partition_guid.b,
298				(char *)disk_partition_uuid(info),
299				UUID_STR_FORMAT_GUID);
300	}
301	if (IS_ENABLED(CONFIG_PARTITION_TYPE_GUID)) {
302		uuid_bin_to_str(gpt_pte[part - 1].partition_type_guid.b,
303				(char *)disk_partition_type_guid(info),
304				UUID_STR_FORMAT_GUID);
305	}
306
307	log_debug("start 0x" LBAF ", size 0x" LBAF ", name %s\n", info->start,
308		  info->size, info->name);
309
310	/* Remember to free pte */
311	free(gpt_pte);
312	return 0;
313}
314
315static int part_test_efi(struct blk_desc *desc)
316{
317	ALLOC_CACHE_ALIGN_BUFFER_PAD(legacy_mbr, legacymbr, 1, desc->blksz);
318
319	/* Read legacy MBR from block 0 and validate it */
320	if ((blk_dread(desc, 0, 1, (ulong *)legacymbr) != 1)
321		|| (is_pmbr_valid(legacymbr) != 1)) {
322		return -1;
323	}
324	return 0;
325}
326
327/**
328 * set_protective_mbr(): Set the EFI protective MBR
329 * @param desc - block device descriptor
330 *
331 * Return: - zero on success, otherwise error
332 */
333static int set_protective_mbr(struct blk_desc *desc)
334{
335	/* Setup the Protective MBR */
336	ALLOC_CACHE_ALIGN_BUFFER_PAD(legacy_mbr, p_mbr, 1, desc->blksz);
337	if (p_mbr == NULL) {
338		log_debug("calloc failed!\n");
339		return -ENOMEM;
340	}
341
342	/* Read MBR to backup boot code if it exists */
343	if (blk_dread(desc, 0, 1, p_mbr) != 1) {
344		log_debug("** Can't read from device %d **\n",
345			  desc->devnum);
346		return -EIO;
347	}
348
349	/* Clear all data in MBR except of backed up boot code */
350	memset((char *)p_mbr + MSDOS_MBR_BOOT_CODE_SIZE, 0, sizeof(*p_mbr) -
351			MSDOS_MBR_BOOT_CODE_SIZE);
352
353	/* Append signature */
354	p_mbr->signature = MSDOS_MBR_SIGNATURE;
355	p_mbr->partition_record[0].sys_ind = EFI_PMBR_OSTYPE_EFI_GPT;
356	p_mbr->partition_record[0].start_sect = 1;
357	p_mbr->partition_record[0].nr_sects = (u32)desc->lba - 1;
358
359	/* Write MBR sector to the MMC device */
360	if (blk_dwrite(desc, 0, 1, p_mbr) != 1) {
361		log_debug("** Can't write to device %d **\n", desc->devnum);
362		return -EIO;
363	}
364
365	return 0;
366}
367
368int write_gpt_table(struct blk_desc *desc, gpt_header *gpt_h, gpt_entry *gpt_e)
369{
370	const int pte_blk_cnt = BLOCK_CNT((gpt_h->num_partition_entries
371					   * sizeof(gpt_entry)), desc);
372	u32 calc_crc32;
373
374	debug("max lba: %x\n", (u32)desc->lba);
375	/* Setup the Protective MBR */
376	if (set_protective_mbr(desc) < 0)
377		goto err;
378
379	/* Generate CRC for the Primary GPT Header */
380	calc_crc32 = efi_crc32((const unsigned char *)gpt_e,
381			      le32_to_cpu(gpt_h->num_partition_entries) *
382			      le32_to_cpu(gpt_h->sizeof_partition_entry));
383	gpt_h->partition_entry_array_crc32 = cpu_to_le32(calc_crc32);
384
385	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
386			      le32_to_cpu(gpt_h->header_size));
387	gpt_h->header_crc32 = cpu_to_le32(calc_crc32);
388
389	/* Write the First GPT to the block right after the Legacy MBR */
390	if (blk_dwrite(desc, 1, 1, gpt_h) != 1)
391		goto err;
392
393	if (blk_dwrite(desc, le64_to_cpu(gpt_h->partition_entry_lba),
394		       pte_blk_cnt, gpt_e) != pte_blk_cnt)
395		goto err;
396
397	prepare_backup_gpt_header(gpt_h);
398
399	if (blk_dwrite(desc, (lbaint_t)le64_to_cpu(gpt_h->last_usable_lba)
400		       + 1, pte_blk_cnt, gpt_e) != pte_blk_cnt)
401		goto err;
402
403	if (blk_dwrite(desc, (lbaint_t)le64_to_cpu(gpt_h->my_lba), 1,
404		       gpt_h) != 1)
405		goto err;
406
407	debug("GPT successfully written to block device!\n");
408	return 0;
409
410 err:
411	log_debug("** Can't write to device %d **\n", desc->devnum);
412	return -EIO;
413}
414
415int gpt_fill_pte(struct blk_desc *desc,
416		 gpt_header *gpt_h, gpt_entry *gpt_e,
417		 struct disk_partition *partitions, int parts)
418{
419	lbaint_t offset = (lbaint_t)le64_to_cpu(gpt_h->first_usable_lba);
420	lbaint_t last_usable_lba = (lbaint_t)
421			le64_to_cpu(gpt_h->last_usable_lba);
422	int i, k;
423	size_t efiname_len, dosname_len;
424	unsigned char *bin_uuid;
425#ifdef CONFIG_PARTITION_TYPE_GUID
426	char *str_type_guid;
427	unsigned char *bin_type_guid;
428#endif
429	size_t hdr_start = gpt_h->my_lba;
430	size_t hdr_end = hdr_start + 1;
431
432	size_t pte_start = gpt_h->partition_entry_lba;
433	size_t pte_end = pte_start +
434		gpt_h->num_partition_entries * gpt_h->sizeof_partition_entry /
435		desc->blksz;
436
437	for (i = 0; i < parts; i++) {
438		/* partition starting lba */
439		lbaint_t start = partitions[i].start;
440		lbaint_t size = partitions[i].size;
441
442		if (start) {
443			offset = start + size;
444		} else {
445			start = offset;
446			offset += size;
447		}
448
449		/*
450		 * If our partition overlaps with either the GPT
451		 * header, or the partition entry, reject it.
452		 */
453		if (((start < hdr_end && hdr_start < (start + size)) ||
454		     (start < pte_end && pte_start < (start + size)))) {
455			log_debug("Partition overlap\n");
456			return -ENOSPC;
457		}
458
459		gpt_e[i].starting_lba = cpu_to_le64(start);
460
461		if (offset > (last_usable_lba + 1)) {
462			log_debug("Partitions layout exceeds disk size\n");
463			return -E2BIG;
464		}
465		/* partition ending lba */
466		if ((i == parts - 1) && (size == 0))
467			/* extend the last partition to maximuim */
468			gpt_e[i].ending_lba = gpt_h->last_usable_lba;
469		else
470			gpt_e[i].ending_lba = cpu_to_le64(offset - 1);
471
472#ifdef CONFIG_PARTITION_TYPE_GUID
473		str_type_guid = partitions[i].type_guid;
474		bin_type_guid = gpt_e[i].partition_type_guid.b;
475		if (strlen(str_type_guid)) {
476			if (uuid_str_to_bin(str_type_guid, bin_type_guid,
477					    UUID_STR_FORMAT_GUID)) {
478				log_debug("Partition no. %d: invalid type guid: %s\n",
479					  i, str_type_guid);
480				return -EINVAL;
481			}
482		} else {
483			/* default partition type GUID */
484			memcpy(bin_type_guid,
485			       &partition_basic_data_guid, 16);
486		}
487#else
488		/* partition type GUID */
489		memcpy(gpt_e[i].partition_type_guid.b,
490			&partition_basic_data_guid, 16);
491#endif
492
493		if (CONFIG_IS_ENABLED(PARTITION_UUIDS)) {
494			const char *str_uuid;
495
496			str_uuid = disk_partition_uuid(&partitions[i]);
497			bin_uuid = gpt_e[i].unique_partition_guid.b;
498
499			if (uuid_str_to_bin(str_uuid, bin_uuid,
500					    UUID_STR_FORMAT_GUID)) {
501				log_debug("Partition no. %d: invalid guid: %s\n",
502					  i, str_uuid);
503				return -EINVAL;
504			}
505		}
506
507		/* partition attributes */
508		memset(&gpt_e[i].attributes, 0,
509		       sizeof(gpt_entry_attributes));
510
511		if (partitions[i].bootable & PART_BOOTABLE)
512			gpt_e[i].attributes.fields.legacy_bios_bootable = 1;
513
514		/* partition name */
515		efiname_len = sizeof(gpt_e[i].partition_name)
516			/ sizeof(efi_char16_t);
517		dosname_len = sizeof(partitions[i].name);
518
519		memset(gpt_e[i].partition_name, 0,
520		       sizeof(gpt_e[i].partition_name));
521
522		for (k = 0; k < min(dosname_len, efiname_len); k++)
523			gpt_e[i].partition_name[k] =
524				(efi_char16_t)(partitions[i].name[k]);
525
526		debug("%s: name: %s offset[%d]: 0x" LBAF
527		      " size[%d]: 0x" LBAF "\n",
528		      __func__, partitions[i].name, i,
529		      offset, i, size);
530	}
531
532	return 0;
533}
534
535static uint32_t partition_entries_offset(struct blk_desc *desc)
536{
537	uint32_t offset_blks = 2;
538	uint32_t __maybe_unused offset_bytes;
539	int __maybe_unused config_offset;
540
541#if defined(CONFIG_EFI_PARTITION_ENTRIES_OFF)
542	/*
543	 * Some architectures require their SPL loader at a fixed
544	 * address within the first 16KB of the disk.  To avoid an
545	 * overlap with the partition entries of the EFI partition
546	 * table, the first safe offset (in bytes, from the start of
547	 * the disk) for the entries can be set in
548	 * CONFIG_EFI_PARTITION_ENTRIES_OFF.
549	 */
550	offset_bytes =
551		PAD_TO_BLOCKSIZE(CONFIG_EFI_PARTITION_ENTRIES_OFF, desc);
552	offset_blks = offset_bytes / desc->blksz;
553#endif
554
555#if defined(CONFIG_OF_CONTROL)
556	/*
557	 * Allow the offset of the first partition entires (in bytes
558	 * from the start of the device) to be specified as a property
559	 * of the device tree '/config' node.
560	 */
561	config_offset = ofnode_conf_read_int(
562		"u-boot,efi-partition-entries-offset", -EINVAL);
563	if (config_offset != -EINVAL) {
564		offset_bytes = PAD_TO_BLOCKSIZE(config_offset, desc);
565		offset_blks = offset_bytes / desc->blksz;
566	}
567#endif
568
569	debug("efi: partition entries offset (in blocks): %d\n", offset_blks);
570
571	/*
572	 * The earliest LBA this can be at is LBA#2 (i.e. right behind
573	 * the (protective) MBR and the GPT header.
574	 */
575	if (offset_blks < 2)
576		offset_blks = 2;
577
578	return offset_blks;
579}
580
581int gpt_fill_header(struct blk_desc *desc, gpt_header *gpt_h, char *str_guid,
582		    int parts_count)
583{
584	gpt_h->signature = cpu_to_le64(GPT_HEADER_SIGNATURE_UBOOT);
585	gpt_h->revision = cpu_to_le32(GPT_HEADER_REVISION_V1);
586	gpt_h->header_size = cpu_to_le32(sizeof(gpt_header));
587	gpt_h->my_lba = cpu_to_le64(1);
588	gpt_h->alternate_lba = cpu_to_le64(desc->lba - 1);
589	gpt_h->last_usable_lba = cpu_to_le64(desc->lba - 34);
590	gpt_h->partition_entry_lba =
591		cpu_to_le64(partition_entries_offset(desc));
592	gpt_h->first_usable_lba =
593		cpu_to_le64(le64_to_cpu(gpt_h->partition_entry_lba) + 32);
594	gpt_h->num_partition_entries = cpu_to_le32(GPT_ENTRY_NUMBERS);
595	gpt_h->sizeof_partition_entry = cpu_to_le32(sizeof(gpt_entry));
596	gpt_h->header_crc32 = 0;
597	gpt_h->partition_entry_array_crc32 = 0;
598
599	if (uuid_str_to_bin(str_guid, gpt_h->disk_guid.b, UUID_STR_FORMAT_GUID))
600		return -1;
601
602	return 0;
603}
604
605int gpt_restore(struct blk_desc *desc, char *str_disk_guid,
606		struct disk_partition *partitions, int parts_count)
607{
608	gpt_header *gpt_h;
609	gpt_entry *gpt_e;
610	int ret, size;
611
612	size = PAD_TO_BLOCKSIZE(sizeof(gpt_header), desc);
613	gpt_h = malloc_cache_aligned(size);
614	if (gpt_h == NULL) {
615		log_debug("calloc failed!\n");
616		return -ENOMEM;
617	}
618	memset(gpt_h, 0, size);
619
620	size = PAD_TO_BLOCKSIZE(GPT_ENTRY_NUMBERS * sizeof(gpt_entry),
621				desc);
622	gpt_e = malloc_cache_aligned(size);
623	if (gpt_e == NULL) {
624		log_debug("calloc failed!\n");
625		free(gpt_h);
626		return -ENOMEM;
627	}
628	memset(gpt_e, 0, size);
629
630	/* Generate Primary GPT header (LBA1) */
631	ret = gpt_fill_header(desc, gpt_h, str_disk_guid, parts_count);
632	if (ret)
633		goto err;
634
635	/* Generate partition entries */
636	ret = gpt_fill_pte(desc, gpt_h, gpt_e, partitions, parts_count);
637	if (ret)
638		goto err;
639
640	/* Write GPT partition table */
641	ret = write_gpt_table(desc, gpt_h, gpt_e);
642
643err:
644	free(gpt_e);
645	free(gpt_h);
646	return ret;
647}
648
649/**
650 * gpt_convert_efi_name_to_char() - convert u16 string to char string
651 *
652 * TODO: this conversion only supports ANSI characters
653 *
654 * @s:	target buffer
655 * @es:	u16 string to be converted
656 * @n:	size of target buffer
657 */
658static void gpt_convert_efi_name_to_char(char *s, void *es, int n)
659{
660	char *ess = es;
661	int i, j;
662
663	memset(s, '\0', n);
664
665	for (i = 0, j = 0; j < n; i += 2, j++) {
666		s[j] = ess[i];
667		if (!ess[i])
668			return;
669	}
670}
671
672int gpt_verify_headers(struct blk_desc *desc, gpt_header *gpt_head,
673		       gpt_entry **gpt_pte)
674{
675	/*
676	 * This function validates AND
677	 * fills in the GPT header and PTE
678	 */
679	if (is_gpt_valid(desc,
680			 GPT_PRIMARY_PARTITION_TABLE_LBA,
681			 gpt_head, gpt_pte) != 1) {
682		log_debug("Invalid GPT\n");
683		return -1;
684	}
685
686	/* Free pte before allocating again */
687	free(*gpt_pte);
688
689	/*
690	 * Check that the alternate_lba entry points to the last LBA
691	 */
692	if (le64_to_cpu(gpt_head->alternate_lba) != (desc->lba - 1)) {
693		log_debug("Misplaced Backup GPT\n");
694		return -1;
695	}
696
697	if (is_gpt_valid(desc, (desc->lba - 1),
698			 gpt_head, gpt_pte) != 1) {
699		log_debug("Invalid Backup GPT\n");
700		return -1;
701	}
702
703	return 0;
704}
705
706static void restore_primary_gpt_header(gpt_header *gpt_h, struct blk_desc *desc)
707{
708	u32 calc_crc32;
709	u64 val;
710
711	/* recalculate the values for the Primary GPT Header */
712	val = le64_to_cpu(gpt_h->my_lba);
713	gpt_h->my_lba = gpt_h->alternate_lba;
714	gpt_h->alternate_lba = cpu_to_le64(val);
715	gpt_h->partition_entry_lba = cpu_to_le64(partition_entries_offset(desc));
716
717	gpt_h->header_crc32 = 0;
718
719	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
720			       le32_to_cpu(gpt_h->header_size));
721	gpt_h->header_crc32 = cpu_to_le32(calc_crc32);
722}
723
724static int write_one_gpt_table(struct blk_desc *desc, gpt_header *gpt_h,
725			       gpt_entry *gpt_e)
726{
727	const int pte_blk_cnt = BLOCK_CNT((gpt_h->num_partition_entries
728					   * sizeof(gpt_entry)), desc);
729	lbaint_t start;
730	int ret = 0;
731
732	start = le64_to_cpu(gpt_h->my_lba);
733	if (blk_dwrite(desc, start, 1, gpt_h) != 1) {
734		ret = -1;
735		goto out;
736	}
737
738	start = le64_to_cpu(gpt_h->partition_entry_lba);
739	if (blk_dwrite(desc, start, pte_blk_cnt, gpt_e) != pte_blk_cnt) {
740		ret = -1;
741		goto out;
742	}
743
744 out:
745	return ret;
746}
747
748int gpt_repair_headers(struct blk_desc *desc)
749{
750	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_h1, 1, desc->blksz);
751	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_h2, 1, desc->blksz);
752	gpt_entry *gpt_e1 = NULL, *gpt_e2 = NULL;
753	int is_gpt1_valid, is_gpt2_valid;
754	int ret = -1;
755
756	is_gpt1_valid = is_gpt_valid(desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
757				     gpt_h1, &gpt_e1);
758	is_gpt2_valid = is_gpt_valid(desc, desc->lba - 1,
759				     gpt_h2, &gpt_e2);
760
761	if (is_gpt1_valid && is_gpt2_valid) {
762		ret = 0;
763		goto out;
764	}
765
766	if (is_gpt1_valid && !is_gpt2_valid) {
767		prepare_backup_gpt_header(gpt_h1);
768		ret = write_one_gpt_table(desc, gpt_h1, gpt_e1);
769		goto out;
770	}
771
772	if (!is_gpt1_valid && is_gpt2_valid) {
773		restore_primary_gpt_header(gpt_h2, desc);
774		ret = write_one_gpt_table(desc, gpt_h2, gpt_e2);
775		goto out;
776	}
777
778	if (!is_gpt1_valid && !is_gpt2_valid) {
779		ret = -1;
780		goto out;
781	}
782
783 out:
784	if (is_gpt1_valid)
785		free(gpt_e1);
786	if (is_gpt2_valid)
787		free(gpt_e2);
788
789	return ret;
790}
791
792int gpt_verify_partitions(struct blk_desc *desc,
793			  struct disk_partition *partitions, int parts,
794			  gpt_header *gpt_head, gpt_entry **gpt_pte)
795{
796	char efi_str[PARTNAME_SZ + 1];
797	u64 gpt_part_size;
798	gpt_entry *gpt_e;
799	int ret, i;
800
801	ret = gpt_verify_headers(desc, gpt_head, gpt_pte);
802	if (ret)
803		return ret;
804
805	gpt_e = *gpt_pte;
806
807	for (i = 0; i < parts; i++) {
808		if (i == gpt_head->num_partition_entries) {
809			pr_err("More partitions than allowed!\n");
810			return -1;
811		}
812
813		/* Check if GPT and ENV partition names match */
814		gpt_convert_efi_name_to_char(efi_str, gpt_e[i].partition_name,
815					     PARTNAME_SZ + 1);
816
817		debug("%s: part: %2d name - GPT: %16s, ENV: %16s ",
818		      __func__, i, efi_str, partitions[i].name);
819
820		if (strncmp(efi_str, (char *)partitions[i].name,
821			    sizeof(partitions->name))) {
822			pr_err("Partition name: %s does not match %s!\n",
823			      efi_str, (char *)partitions[i].name);
824			return -1;
825		}
826
827		/* Check if GPT and ENV sizes match */
828		gpt_part_size = le64_to_cpu(gpt_e[i].ending_lba) -
829			le64_to_cpu(gpt_e[i].starting_lba) + 1;
830		debug("size(LBA) - GPT: %8llu, ENV: %8llu ",
831		      (unsigned long long)gpt_part_size,
832		      (unsigned long long)partitions[i].size);
833
834		if (le64_to_cpu(gpt_part_size) != partitions[i].size) {
835			/* We do not check the extend partition size */
836			if ((i == parts - 1) && (partitions[i].size == 0))
837				continue;
838
839			pr_err("Partition %s size: %llu does not match %llu!\n",
840			      efi_str, (unsigned long long)gpt_part_size,
841			      (unsigned long long)partitions[i].size);
842			return -1;
843		}
844
845		/*
846		 * Start address is optional - check only if provided
847		 * in '$partition' variable
848		 */
849		if (!partitions[i].start) {
850			debug("\n");
851			continue;
852		}
853
854		/* Check if GPT and ENV start LBAs match */
855		debug("start LBA - GPT: %8llu, ENV: %8llu\n",
856		      le64_to_cpu(gpt_e[i].starting_lba),
857		      (unsigned long long)partitions[i].start);
858
859		if (le64_to_cpu(gpt_e[i].starting_lba) != partitions[i].start) {
860			pr_err("Partition %s start: %llu does not match %llu!\n",
861			      efi_str, le64_to_cpu(gpt_e[i].starting_lba),
862			      (unsigned long long)partitions[i].start);
863			return -1;
864		}
865	}
866
867	return 0;
868}
869
870int is_valid_gpt_buf(struct blk_desc *desc, void *buf)
871{
872	gpt_header *gpt_h;
873	gpt_entry *gpt_e;
874
875	/* determine start of GPT Header in the buffer */
876	gpt_h = buf + (GPT_PRIMARY_PARTITION_TABLE_LBA * desc->blksz);
877	if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
878				desc->lba))
879		return -1;
880
881	/* determine start of GPT Entries in the buffer */
882	gpt_e = buf + (le64_to_cpu(gpt_h->partition_entry_lba) *
883		       desc->blksz);
884	if (validate_gpt_entries(gpt_h, gpt_e))
885		return -1;
886
887	return 0;
888}
889
890int write_mbr_and_gpt_partitions(struct blk_desc *desc, void *buf)
891{
892	gpt_header *gpt_h;
893	gpt_entry *gpt_e;
894	int gpt_e_blk_cnt;
895	lbaint_t lba;
896	int cnt;
897
898	if (is_valid_gpt_buf(desc, buf))
899		return -1;
900
901	/* determine start of GPT Header in the buffer */
902	gpt_h = buf + (GPT_PRIMARY_PARTITION_TABLE_LBA * desc->blksz);
903
904	/* determine start of GPT Entries in the buffer */
905	gpt_e = buf + (le64_to_cpu(gpt_h->partition_entry_lba) * desc->blksz);
906	gpt_e_blk_cnt = BLOCK_CNT((le32_to_cpu(gpt_h->num_partition_entries) *
907				   le32_to_cpu(gpt_h->sizeof_partition_entry)),
908				  desc);
909
910	/* write MBR */
911	lba = 0;	/* MBR is always at 0 */
912	cnt = 1;	/* MBR (1 block) */
913	if (blk_dwrite(desc, lba, cnt, buf) != cnt) {
914		log_debug("failed writing '%s' (%d blks at 0x" LBAF ")\n",
915			  "MBR", cnt, lba);
916		return 1;
917	}
918
919	/* write Primary GPT */
920	lba = GPT_PRIMARY_PARTITION_TABLE_LBA;
921	cnt = 1;	/* GPT Header (1 block) */
922	if (blk_dwrite(desc, lba, cnt, gpt_h) != cnt) {
923		log_debug("failed writing '%s' (%d blks at 0x" LBAF ")\n",
924			  "Primary GPT Header", cnt, lba);
925		return 1;
926	}
927
928	lba = le64_to_cpu(gpt_h->partition_entry_lba);
929	cnt = gpt_e_blk_cnt;
930	if (blk_dwrite(desc, lba, cnt, gpt_e) != cnt) {
931		log_debug("failed writing '%s' (%d blks at 0x" LBAF ")\n",
932			  "Primary GPT Entries", cnt, lba);
933		return 1;
934	}
935
936	prepare_backup_gpt_header(gpt_h);
937
938	/* write Backup GPT */
939	lba = le64_to_cpu(gpt_h->partition_entry_lba);
940	cnt = gpt_e_blk_cnt;
941	if (blk_dwrite(desc, lba, cnt, gpt_e) != cnt) {
942		log_debug("failed writing '%s' (%d blks at 0x" LBAF ")\n",
943			  "Backup GPT Entries", cnt, lba);
944		return 1;
945	}
946
947	lba = le64_to_cpu(gpt_h->my_lba);
948	cnt = 1;	/* GPT Header (1 block) */
949	if (blk_dwrite(desc, lba, cnt, gpt_h) != cnt) {
950		log_debug("failed writing '%s' (%d blks at 0x" LBAF ")\n",
951			  "Backup GPT Header", cnt, lba);
952		return 1;
953	}
954
955	/* Update the partition table entries*/
956	part_init(desc);
957
958	return 0;
959}
960#endif
961
962/*
963 * Private functions
964 */
965/*
966 * pmbr_part_valid(): Check for EFI partition signature
967 *
968 * Returns: 1 if EFI GPT partition type is found.
969 */
970static int pmbr_part_valid(struct partition *part)
971{
972	if (part->sys_ind == EFI_PMBR_OSTYPE_EFI_GPT &&
973		get_unaligned_le32(&part->start_sect) == 1UL) {
974		return 1;
975	}
976
977	return 0;
978}
979
980/*
981 * is_pmbr_valid(): test Protective MBR for validity
982 *
983 * @mbr: Pointer to Master Boot-Record data
984 *
985 * Returns: 1 if PMBR is valid, 0 otherwise.
986 * Validity depends on two things:
987 *  1) MSDOS signature is in the last two bytes of the MBR
988 *  2) One partition of type 0xEE is found, checked by pmbr_part_valid()
989 */
990static int is_pmbr_valid(legacy_mbr *mbr)
991{
992	uint sig = le16_to_cpu(mbr->signature);
993	int i = 0;
994
995	if (sig != MSDOS_MBR_SIGNATURE) {
996		log_debug("Invalid signature %x\n", sig);
997		return 0;
998	}
999	log_debug("Signature %x valid\n", sig);
1000
1001	for (i = 0; i < 4; i++) {
1002		if (pmbr_part_valid(&mbr->partition_record[i])) {
1003			return 1;
1004		}
1005	}
1006	return 0;
1007}
1008
1009/**
1010 * is_gpt_valid() - tests one GPT header and PTEs for validity
1011 *
1012 * lba is the logical block address of the GPT header to test
1013 * gpt is a GPT header ptr, filled on return.
1014 * ptes is a PTEs ptr, filled on return.
1015 *
1016 * Description: returns 1 if valid,  0 on error, 2 if ignored header
1017 * If valid, returns pointers to PTEs.
1018 */
1019static int is_gpt_valid(struct blk_desc *desc, u64 lba, gpt_header *pgpt_head,
1020			gpt_entry **pgpt_pte)
1021{
1022	/* Confirm valid arguments prior to allocation. */
1023	if (!desc || !pgpt_head) {
1024		log_debug("Invalid Argument(s)\n");
1025		return 0;
1026	}
1027
1028	ALLOC_CACHE_ALIGN_BUFFER_PAD(legacy_mbr, mbr, 1, desc->blksz);
1029
1030	/* Read MBR Header from device */
1031	if (blk_dread(desc, 0, 1, (ulong *)mbr) != 1) {
1032		log_debug("Can't read MBR header\n");
1033		return 0;
1034	}
1035
1036	/* Read GPT Header from device */
1037	if (blk_dread(desc, (lbaint_t)lba, 1, pgpt_head) != 1) {
1038		log_debug("Can't read GPT header\n");
1039		return 0;
1040	}
1041
1042	/* Invalid but nothing to yell about. */
1043	if (le64_to_cpu(pgpt_head->signature) == GPT_HEADER_CHROMEOS_IGNORE) {
1044		log_debug("ChromeOS 'IGNOREME' GPT header found and ignored\n");
1045		return 2;
1046	}
1047
1048	if (validate_gpt_header(pgpt_head, (lbaint_t)lba, desc->lba))
1049		return 0;
1050
1051	if (desc->sig_type == SIG_TYPE_NONE) {
1052		efi_guid_t empty = {};
1053		if (memcmp(&pgpt_head->disk_guid, &empty, sizeof(empty))) {
1054			desc->sig_type = SIG_TYPE_GUID;
1055			memcpy(&desc->guid_sig, &pgpt_head->disk_guid,
1056			       sizeof(empty));
1057		} else if (mbr->unique_mbr_signature != 0) {
1058			desc->sig_type = SIG_TYPE_MBR;
1059			desc->mbr_sig = mbr->unique_mbr_signature;
1060		}
1061	}
1062
1063	/* Read and allocate Partition Table Entries */
1064	*pgpt_pte = alloc_read_gpt_entries(desc, pgpt_head);
1065	if (!*pgpt_pte)
1066		return 0;
1067
1068	if (validate_gpt_entries(pgpt_head, *pgpt_pte)) {
1069		free(*pgpt_pte);
1070		return 0;
1071	}
1072
1073	/* We're done, all's well */
1074	return 1;
1075}
1076
1077/**
1078 * find_valid_gpt() - finds a valid GPT header and PTEs
1079 *
1080 * gpt is a GPT header ptr, filled on return.
1081 * ptes is a PTEs ptr, filled on return.
1082 *
1083 * Description: returns 1 if found a valid gpt,  0 on error.
1084 * If valid, returns pointers to PTEs.
1085 */
1086static int find_valid_gpt(struct blk_desc *desc, gpt_header *gpt_head,
1087			  gpt_entry **pgpt_pte)
1088{
1089	int r;
1090
1091	r = is_gpt_valid(desc, GPT_PRIMARY_PARTITION_TABLE_LBA, gpt_head,
1092			 pgpt_pte);
1093
1094	if (r != 1) {
1095		if (r != 2)
1096			log_debug("Invalid GPT\n");
1097
1098		if (is_gpt_valid(desc, desc->lba - 1, gpt_head, pgpt_pte)
1099		    != 1) {
1100			log_debug("Invalid Backup GPT\n");
1101			return 0;
1102		}
1103		if (r != 2)
1104			log_debug("        Using Backup GPT\n");
1105	}
1106	return 1;
1107}
1108
1109/**
1110 * alloc_read_gpt_entries(): reads partition entries from disk
1111 * @desc
1112 * @gpt - GPT header
1113 *
1114 * Description: Returns ptes on success,  NULL on error.
1115 * Allocates space for PTEs based on information found in @gpt.
1116 * Notes: remember to free pte when you're done!
1117 */
1118static gpt_entry *alloc_read_gpt_entries(struct blk_desc *desc,
1119					 gpt_header *pgpt_head)
1120{
1121	size_t count = 0, blk_cnt;
1122	lbaint_t blk;
1123	gpt_entry *pte = NULL;
1124
1125	if (!desc || !pgpt_head) {
1126		log_debug("Invalid Argument(s)\n");
1127		return NULL;
1128	}
1129
1130	count = le32_to_cpu(pgpt_head->num_partition_entries) *
1131		le32_to_cpu(pgpt_head->sizeof_partition_entry);
1132
1133	log_debug("count = %u * %u = %lu\n",
1134		  (u32)le32_to_cpu(pgpt_head->num_partition_entries),
1135		  (u32)le32_to_cpu(pgpt_head->sizeof_partition_entry),
1136		  (ulong)count);
1137
1138	/* Allocate memory for PTE, remember to FREE */
1139	if (count != 0) {
1140		pte = memalign(ARCH_DMA_MINALIGN,
1141			       PAD_TO_BLOCKSIZE(count, desc));
1142	}
1143
1144	if (count == 0 || pte == NULL) {
1145		log_debug("ERROR: Can't allocate %#lX bytes for GPT Entries\n",
1146			  (ulong)count);
1147		return NULL;
1148	}
1149
1150	/* Read GPT Entries from device */
1151	blk = le64_to_cpu(pgpt_head->partition_entry_lba);
1152	blk_cnt = BLOCK_CNT(count, desc);
1153	if (blk_dread(desc, blk, (lbaint_t)blk_cnt, pte) != blk_cnt) {
1154		log_debug("Can't read GPT Entries\n");
1155		free(pte);
1156		return NULL;
1157	}
1158	return pte;
1159}
1160
1161/**
1162 * is_pte_valid(): validates a single Partition Table Entry
1163 * @gpt_entry - Pointer to a single Partition Table Entry
1164 *
1165 * Description: returns 1 if valid,  0 on error.
1166 */
1167static int is_pte_valid(gpt_entry * pte)
1168{
1169	efi_guid_t unused_guid;
1170
1171	if (!pte) {
1172		log_debug("Invalid Argument(s)\n");
1173		return 0;
1174	}
1175
1176	/* Only one validation for now:
1177	 * The GUID Partition Type != Unused Entry (ALL-ZERO)
1178	 */
1179	memset(unused_guid.b, 0, sizeof(unused_guid.b));
1180
1181	if (memcmp(pte->partition_type_guid.b, unused_guid.b,
1182		sizeof(unused_guid.b)) == 0) {
1183
1184		log_debug("Found an unused PTE GUID at 0x%08X\n",
1185			  (unsigned int)(uintptr_t)pte);
1186
1187		return 0;
1188	} else {
1189		return 1;
1190	}
1191}
1192
1193/*
1194 * Add an 'a_' prefix so it comes before 'dos' in the linker list. We need to
1195 * check EFI first, since a DOS partition is often used as a 'protective MBR'
1196 * with EFI.
1197 */
1198U_BOOT_PART_TYPE(a_efi) = {
1199	.name		= "EFI",
1200	.part_type	= PART_TYPE_EFI,
1201	.max_entries	= GPT_ENTRY_NUMBERS,
1202	.get_info	= part_get_info_ptr(part_get_info_efi),
1203	.print		= part_print_ptr(part_print_efi),
1204	.test		= part_test_efi,
1205};
1206