xref: /openbmc/u-boot/disk/part_efi.c (revision 0adb5b76)
1 /*
2  * Copyright (C) 2008 RuggedCom, Inc.
3  * Richard Retanubun <RichardRetanubun@RuggedCom.com>
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 /*
9  * NOTE:
10  *   when CONFIG_SYS_64BIT_LBA is not defined, lbaint_t is 32 bits; this
11  *   limits the maximum size of addressable storage to < 2 Terra Bytes
12  */
13 #include <asm/unaligned.h>
14 #include <common.h>
15 #include <command.h>
16 #include <ide.h>
17 #include <inttypes.h>
18 #include <malloc.h>
19 #include <part_efi.h>
20 #include <linux/ctype.h>
21 
22 DECLARE_GLOBAL_DATA_PTR;
23 
24 #ifdef HAVE_BLOCK_DEVICE
25 /**
26  * efi_crc32() - EFI version of crc32 function
27  * @buf: buffer to calculate crc32 of
28  * @len - length of buf
29  *
30  * Description: Returns EFI-style CRC32 value for @buf
31  */
32 static inline u32 efi_crc32(const void *buf, u32 len)
33 {
34 	return crc32(0, buf, len);
35 }
36 
37 /*
38  * Private function prototypes
39  */
40 
41 static int pmbr_part_valid(struct partition *part);
42 static int is_pmbr_valid(legacy_mbr * mbr);
43 static int is_gpt_valid(block_dev_desc_t *dev_desc, u64 lba,
44 				gpt_header *pgpt_head, gpt_entry **pgpt_pte);
45 static gpt_entry *alloc_read_gpt_entries(block_dev_desc_t * dev_desc,
46 				gpt_header * pgpt_head);
47 static int is_pte_valid(gpt_entry * pte);
48 
49 static char *print_efiname(gpt_entry *pte)
50 {
51 	static char name[PARTNAME_SZ + 1];
52 	int i;
53 	for (i = 0; i < PARTNAME_SZ; i++) {
54 		u8 c;
55 		c = pte->partition_name[i] & 0xff;
56 		c = (c && !isprint(c)) ? '.' : c;
57 		name[i] = c;
58 	}
59 	name[PARTNAME_SZ] = 0;
60 	return name;
61 }
62 
63 static efi_guid_t system_guid = PARTITION_SYSTEM_GUID;
64 
65 static inline int is_bootable(gpt_entry *p)
66 {
67 	return p->attributes.fields.legacy_bios_bootable ||
68 		!memcmp(&(p->partition_type_guid), &system_guid,
69 			sizeof(efi_guid_t));
70 }
71 
72 static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
73 		lbaint_t lastlba)
74 {
75 	uint32_t crc32_backup = 0;
76 	uint32_t calc_crc32;
77 
78 	/* Check the GPT header signature */
79 	if (le64_to_cpu(gpt_h->signature) != GPT_HEADER_SIGNATURE) {
80 		printf("%s signature is wrong: 0x%llX != 0x%llX\n",
81 		       "GUID Partition Table Header",
82 		       le64_to_cpu(gpt_h->signature),
83 		       GPT_HEADER_SIGNATURE);
84 		return -1;
85 	}
86 
87 	/* Check the GUID Partition Table CRC */
88 	memcpy(&crc32_backup, &gpt_h->header_crc32, sizeof(crc32_backup));
89 	memset(&gpt_h->header_crc32, 0, sizeof(gpt_h->header_crc32));
90 
91 	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
92 		le32_to_cpu(gpt_h->header_size));
93 
94 	memcpy(&gpt_h->header_crc32, &crc32_backup, sizeof(crc32_backup));
95 
96 	if (calc_crc32 != le32_to_cpu(crc32_backup)) {
97 		printf("%s CRC is wrong: 0x%x != 0x%x\n",
98 		       "GUID Partition Table Header",
99 		       le32_to_cpu(crc32_backup), calc_crc32);
100 		return -1;
101 	}
102 
103 	/*
104 	 * Check that the my_lba entry points to the LBA that contains the GPT
105 	 */
106 	if (le64_to_cpu(gpt_h->my_lba) != lba) {
107 		printf("GPT: my_lba incorrect: %llX != " LBAF "\n",
108 		       le64_to_cpu(gpt_h->my_lba),
109 		       lba);
110 		return -1;
111 	}
112 
113 	/*
114 	 * Check that the first_usable_lba and that the last_usable_lba are
115 	 * within the disk.
116 	 */
117 	if (le64_to_cpu(gpt_h->first_usable_lba) > lastlba) {
118 		printf("GPT: first_usable_lba incorrect: %llX > " LBAF "\n",
119 		       le64_to_cpu(gpt_h->first_usable_lba), lastlba);
120 		return -1;
121 	}
122 	if (le64_to_cpu(gpt_h->last_usable_lba) > lastlba) {
123 		printf("GPT: last_usable_lba incorrect: %llX > " LBAF "\n",
124 		       le64_to_cpu(gpt_h->last_usable_lba), lastlba);
125 		return -1;
126 	}
127 
128 	debug("GPT: first_usable_lba: %llX last_usable_lba: %llX last lba: "
129 	      LBAF "\n", le64_to_cpu(gpt_h->first_usable_lba),
130 	      le64_to_cpu(gpt_h->last_usable_lba), lastlba);
131 
132 	return 0;
133 }
134 
135 static int validate_gpt_entries(gpt_header *gpt_h, gpt_entry *gpt_e)
136 {
137 	uint32_t calc_crc32;
138 
139 	/* Check the GUID Partition Table Entry Array CRC */
140 	calc_crc32 = efi_crc32((const unsigned char *)gpt_e,
141 		le32_to_cpu(gpt_h->num_partition_entries) *
142 		le32_to_cpu(gpt_h->sizeof_partition_entry));
143 
144 	if (calc_crc32 != le32_to_cpu(gpt_h->partition_entry_array_crc32)) {
145 		printf("%s: 0x%x != 0x%x\n",
146 		       "GUID Partition Table Entry Array CRC is wrong",
147 		       le32_to_cpu(gpt_h->partition_entry_array_crc32),
148 		       calc_crc32);
149 		return -1;
150 	}
151 
152 	return 0;
153 }
154 
155 static void prepare_backup_gpt_header(gpt_header *gpt_h)
156 {
157 	uint32_t calc_crc32;
158 	uint64_t val;
159 
160 	/* recalculate the values for the Backup GPT Header */
161 	val = le64_to_cpu(gpt_h->my_lba);
162 	gpt_h->my_lba = gpt_h->alternate_lba;
163 	gpt_h->alternate_lba = cpu_to_le64(val);
164 	gpt_h->partition_entry_lba =
165 			cpu_to_le64(le64_to_cpu(gpt_h->last_usable_lba) + 1);
166 	gpt_h->header_crc32 = 0;
167 
168 	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
169 			       le32_to_cpu(gpt_h->header_size));
170 	gpt_h->header_crc32 = cpu_to_le32(calc_crc32);
171 }
172 
173 #ifdef CONFIG_EFI_PARTITION
174 /*
175  * Public Functions (include/part.h)
176  */
177 
178 void print_part_efi(block_dev_desc_t * dev_desc)
179 {
180 	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1, dev_desc->blksz);
181 	gpt_entry *gpt_pte = NULL;
182 	int i = 0;
183 	char uuid[37];
184 	unsigned char *uuid_bin;
185 
186 	if (!dev_desc) {
187 		printf("%s: Invalid Argument(s)\n", __func__);
188 		return;
189 	}
190 	/* This function validates AND fills in the GPT header and PTE */
191 	if (is_gpt_valid(dev_desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
192 			 gpt_head, &gpt_pte) != 1) {
193 		printf("%s: *** ERROR: Invalid GPT ***\n", __func__);
194 		if (is_gpt_valid(dev_desc, (dev_desc->lba - 1),
195 				 gpt_head, &gpt_pte) != 1) {
196 			printf("%s: *** ERROR: Invalid Backup GPT ***\n",
197 			       __func__);
198 			return;
199 		} else {
200 			printf("%s: ***        Using Backup GPT ***\n",
201 			       __func__);
202 		}
203 	}
204 
205 	debug("%s: gpt-entry at %p\n", __func__, gpt_pte);
206 
207 	printf("Part\tStart LBA\tEnd LBA\t\tName\n");
208 	printf("\tAttributes\n");
209 	printf("\tType GUID\n");
210 	printf("\tPartition GUID\n");
211 
212 	for (i = 0; i < le32_to_cpu(gpt_head->num_partition_entries); i++) {
213 		/* Stop at the first non valid PTE */
214 		if (!is_pte_valid(&gpt_pte[i]))
215 			break;
216 
217 		printf("%3d\t0x%08llx\t0x%08llx\t\"%s\"\n", (i + 1),
218 			le64_to_cpu(gpt_pte[i].starting_lba),
219 			le64_to_cpu(gpt_pte[i].ending_lba),
220 			print_efiname(&gpt_pte[i]));
221 		printf("\tattrs:\t0x%016llx\n", gpt_pte[i].attributes.raw);
222 		uuid_bin = (unsigned char *)gpt_pte[i].partition_type_guid.b;
223 		uuid_bin_to_str(uuid_bin, uuid, UUID_STR_FORMAT_GUID);
224 		printf("\ttype:\t%s\n", uuid);
225 		uuid_bin = (unsigned char *)gpt_pte[i].unique_partition_guid.b;
226 		uuid_bin_to_str(uuid_bin, uuid, UUID_STR_FORMAT_GUID);
227 		printf("\tguid:\t%s\n", uuid);
228 	}
229 
230 	/* Remember to free pte */
231 	free(gpt_pte);
232 	return;
233 }
234 
235 int get_partition_info_efi(block_dev_desc_t * dev_desc, int part,
236 				disk_partition_t * info)
237 {
238 	ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1, dev_desc->blksz);
239 	gpt_entry *gpt_pte = NULL;
240 
241 	/* "part" argument must be at least 1 */
242 	if (!dev_desc || !info || part < 1) {
243 		printf("%s: Invalid Argument(s)\n", __func__);
244 		return -1;
245 	}
246 
247 	/* This function validates AND fills in the GPT header and PTE */
248 	if (is_gpt_valid(dev_desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
249 			gpt_head, &gpt_pte) != 1) {
250 		printf("%s: *** ERROR: Invalid GPT ***\n", __func__);
251 		if (is_gpt_valid(dev_desc, (dev_desc->lba - 1),
252 				 gpt_head, &gpt_pte) != 1) {
253 			printf("%s: *** ERROR: Invalid Backup GPT ***\n",
254 			       __func__);
255 			return -1;
256 		} else {
257 			printf("%s: ***        Using Backup GPT ***\n",
258 			       __func__);
259 		}
260 	}
261 
262 	if (part > le32_to_cpu(gpt_head->num_partition_entries) ||
263 	    !is_pte_valid(&gpt_pte[part - 1])) {
264 		debug("%s: *** ERROR: Invalid partition number %d ***\n",
265 			__func__, part);
266 		free(gpt_pte);
267 		return -1;
268 	}
269 
270 	/* The 'lbaint_t' casting may limit the maximum disk size to 2 TB */
271 	info->start = (lbaint_t)le64_to_cpu(gpt_pte[part - 1].starting_lba);
272 	/* The ending LBA is inclusive, to calculate size, add 1 to it */
273 	info->size = (lbaint_t)le64_to_cpu(gpt_pte[part - 1].ending_lba) + 1
274 		     - info->start;
275 	info->blksz = dev_desc->blksz;
276 
277 	sprintf((char *)info->name, "%s",
278 			print_efiname(&gpt_pte[part - 1]));
279 	sprintf((char *)info->type, "U-Boot");
280 	info->bootable = is_bootable(&gpt_pte[part - 1]);
281 #ifdef CONFIG_PARTITION_UUIDS
282 	uuid_bin_to_str(gpt_pte[part - 1].unique_partition_guid.b, info->uuid,
283 			UUID_STR_FORMAT_GUID);
284 #endif
285 
286 	debug("%s: start 0x" LBAF ", size 0x" LBAF ", name %s\n", __func__,
287 	      info->start, info->size, info->name);
288 
289 	/* Remember to free pte */
290 	free(gpt_pte);
291 	return 0;
292 }
293 
294 int get_partition_info_efi_by_name(block_dev_desc_t *dev_desc,
295 	const char *name, disk_partition_t *info)
296 {
297 	int ret;
298 	int i;
299 	for (i = 1; i < GPT_ENTRY_NUMBERS; i++) {
300 		ret = get_partition_info_efi(dev_desc, i, info);
301 		if (ret != 0) {
302 			/* no more entries in table */
303 			return -1;
304 		}
305 		if (strcmp(name, (const char *)info->name) == 0) {
306 			/* matched */
307 			return 0;
308 		}
309 	}
310 	return -2;
311 }
312 
313 int test_part_efi(block_dev_desc_t * dev_desc)
314 {
315 	ALLOC_CACHE_ALIGN_BUFFER_PAD(legacy_mbr, legacymbr, 1, dev_desc->blksz);
316 
317 	/* Read legacy MBR from block 0 and validate it */
318 	if ((dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *)legacymbr) != 1)
319 		|| (is_pmbr_valid(legacymbr) != 1)) {
320 		return -1;
321 	}
322 	return 0;
323 }
324 
325 /**
326  * set_protective_mbr(): Set the EFI protective MBR
327  * @param dev_desc - block device descriptor
328  *
329  * @return - zero on success, otherwise error
330  */
331 static int set_protective_mbr(block_dev_desc_t *dev_desc)
332 {
333 	/* Setup the Protective MBR */
334 	ALLOC_CACHE_ALIGN_BUFFER(legacy_mbr, p_mbr, 1);
335 	memset(p_mbr, 0, sizeof(*p_mbr));
336 
337 	if (p_mbr == NULL) {
338 		printf("%s: calloc failed!\n", __func__);
339 		return -1;
340 	}
341 	/* Append signature */
342 	p_mbr->signature = MSDOS_MBR_SIGNATURE;
343 	p_mbr->partition_record[0].sys_ind = EFI_PMBR_OSTYPE_EFI_GPT;
344 	p_mbr->partition_record[0].start_sect = 1;
345 	p_mbr->partition_record[0].nr_sects = (u32) dev_desc->lba - 1;
346 
347 	/* Write MBR sector to the MMC device */
348 	if (dev_desc->block_write(dev_desc->dev, 0, 1, p_mbr) != 1) {
349 		printf("** Can't write to device %d **\n",
350 			dev_desc->dev);
351 		return -1;
352 	}
353 
354 	return 0;
355 }
356 
357 int write_gpt_table(block_dev_desc_t *dev_desc,
358 		gpt_header *gpt_h, gpt_entry *gpt_e)
359 {
360 	const int pte_blk_cnt = BLOCK_CNT((gpt_h->num_partition_entries
361 					   * sizeof(gpt_entry)), dev_desc);
362 	u32 calc_crc32;
363 
364 	debug("max lba: %x\n", (u32) dev_desc->lba);
365 	/* Setup the Protective MBR */
366 	if (set_protective_mbr(dev_desc) < 0)
367 		goto err;
368 
369 	/* Generate CRC for the Primary GPT Header */
370 	calc_crc32 = efi_crc32((const unsigned char *)gpt_e,
371 			      le32_to_cpu(gpt_h->num_partition_entries) *
372 			      le32_to_cpu(gpt_h->sizeof_partition_entry));
373 	gpt_h->partition_entry_array_crc32 = cpu_to_le32(calc_crc32);
374 
375 	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
376 			      le32_to_cpu(gpt_h->header_size));
377 	gpt_h->header_crc32 = cpu_to_le32(calc_crc32);
378 
379 	/* Write the First GPT to the block right after the Legacy MBR */
380 	if (dev_desc->block_write(dev_desc->dev, 1, 1, gpt_h) != 1)
381 		goto err;
382 
383 	if (dev_desc->block_write(dev_desc->dev, 2, pte_blk_cnt, gpt_e)
384 	    != pte_blk_cnt)
385 		goto err;
386 
387 	prepare_backup_gpt_header(gpt_h);
388 
389 	if (dev_desc->block_write(dev_desc->dev,
390 				  (lbaint_t)le64_to_cpu(gpt_h->last_usable_lba)
391 				  + 1,
392 				  pte_blk_cnt, gpt_e) != pte_blk_cnt)
393 		goto err;
394 
395 	if (dev_desc->block_write(dev_desc->dev,
396 				  (lbaint_t)le64_to_cpu(gpt_h->my_lba), 1,
397 				  gpt_h) != 1)
398 		goto err;
399 
400 	debug("GPT successfully written to block device!\n");
401 	return 0;
402 
403  err:
404 	printf("** Can't write to device %d **\n", dev_desc->dev);
405 	return -1;
406 }
407 
408 int gpt_fill_pte(gpt_header *gpt_h, gpt_entry *gpt_e,
409 		disk_partition_t *partitions, int parts)
410 {
411 	lbaint_t offset = (lbaint_t)le64_to_cpu(gpt_h->first_usable_lba);
412 	lbaint_t start;
413 	lbaint_t last_usable_lba = (lbaint_t)
414 			le64_to_cpu(gpt_h->last_usable_lba);
415 	int i, k;
416 	size_t efiname_len, dosname_len;
417 #ifdef CONFIG_PARTITION_UUIDS
418 	char *str_uuid;
419 	unsigned char *bin_uuid;
420 #endif
421 
422 	for (i = 0; i < parts; i++) {
423 		/* partition starting lba */
424 		start = partitions[i].start;
425 		if (start && (start < offset)) {
426 			printf("Partition overlap\n");
427 			return -1;
428 		}
429 		if (start) {
430 			gpt_e[i].starting_lba = cpu_to_le64(start);
431 			offset = start + partitions[i].size;
432 		} else {
433 			gpt_e[i].starting_lba = cpu_to_le64(offset);
434 			offset += partitions[i].size;
435 		}
436 		if (offset >= last_usable_lba) {
437 			printf("Partitions layout exceds disk size\n");
438 			return -1;
439 		}
440 		/* partition ending lba */
441 		if ((i == parts - 1) && (partitions[i].size == 0))
442 			/* extend the last partition to maximuim */
443 			gpt_e[i].ending_lba = gpt_h->last_usable_lba;
444 		else
445 			gpt_e[i].ending_lba = cpu_to_le64(offset - 1);
446 
447 		/* partition type GUID */
448 		memcpy(gpt_e[i].partition_type_guid.b,
449 			&PARTITION_BASIC_DATA_GUID, 16);
450 
451 #ifdef CONFIG_PARTITION_UUIDS
452 		str_uuid = partitions[i].uuid;
453 		bin_uuid = gpt_e[i].unique_partition_guid.b;
454 
455 		if (uuid_str_to_bin(str_uuid, bin_uuid, UUID_STR_FORMAT_STD)) {
456 			printf("Partition no. %d: invalid guid: %s\n",
457 				i, str_uuid);
458 			return -1;
459 		}
460 #endif
461 
462 		/* partition attributes */
463 		memset(&gpt_e[i].attributes, 0,
464 		       sizeof(gpt_entry_attributes));
465 
466 		/* partition name */
467 		efiname_len = sizeof(gpt_e[i].partition_name)
468 			/ sizeof(efi_char16_t);
469 		dosname_len = sizeof(partitions[i].name);
470 
471 		memset(gpt_e[i].partition_name, 0,
472 		       sizeof(gpt_e[i].partition_name));
473 
474 		for (k = 0; k < min(dosname_len, efiname_len); k++)
475 			gpt_e[i].partition_name[k] =
476 				(efi_char16_t)(partitions[i].name[k]);
477 
478 		debug("%s: name: %s offset[%d]: 0x" LBAF
479 		      " size[%d]: 0x" LBAF "\n",
480 		      __func__, partitions[i].name, i,
481 		      offset, i, partitions[i].size);
482 	}
483 
484 	return 0;
485 }
486 
487 int gpt_fill_header(block_dev_desc_t *dev_desc, gpt_header *gpt_h,
488 		char *str_guid, int parts_count)
489 {
490 	gpt_h->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
491 	gpt_h->revision = cpu_to_le32(GPT_HEADER_REVISION_V1);
492 	gpt_h->header_size = cpu_to_le32(sizeof(gpt_header));
493 	gpt_h->my_lba = cpu_to_le64(1);
494 	gpt_h->alternate_lba = cpu_to_le64(dev_desc->lba - 1);
495 	gpt_h->first_usable_lba = cpu_to_le64(34);
496 	gpt_h->last_usable_lba = cpu_to_le64(dev_desc->lba - 34);
497 	gpt_h->partition_entry_lba = cpu_to_le64(2);
498 	gpt_h->num_partition_entries = cpu_to_le32(GPT_ENTRY_NUMBERS);
499 	gpt_h->sizeof_partition_entry = cpu_to_le32(sizeof(gpt_entry));
500 	gpt_h->header_crc32 = 0;
501 	gpt_h->partition_entry_array_crc32 = 0;
502 
503 	if (uuid_str_to_bin(str_guid, gpt_h->disk_guid.b, UUID_STR_FORMAT_GUID))
504 		return -1;
505 
506 	return 0;
507 }
508 
509 int gpt_restore(block_dev_desc_t *dev_desc, char *str_disk_guid,
510 		disk_partition_t *partitions, int parts_count)
511 {
512 	int ret;
513 
514 	gpt_header *gpt_h = calloc(1, PAD_TO_BLOCKSIZE(sizeof(gpt_header),
515 						       dev_desc));
516 	gpt_entry *gpt_e;
517 
518 	if (gpt_h == NULL) {
519 		printf("%s: calloc failed!\n", __func__);
520 		return -1;
521 	}
522 
523 	gpt_e = calloc(1, PAD_TO_BLOCKSIZE(GPT_ENTRY_NUMBERS
524 					       * sizeof(gpt_entry),
525 					       dev_desc));
526 	if (gpt_e == NULL) {
527 		printf("%s: calloc failed!\n", __func__);
528 		free(gpt_h);
529 		return -1;
530 	}
531 
532 	/* Generate Primary GPT header (LBA1) */
533 	ret = gpt_fill_header(dev_desc, gpt_h, str_disk_guid, parts_count);
534 	if (ret)
535 		goto err;
536 
537 	/* Generate partition entries */
538 	ret = gpt_fill_pte(gpt_h, gpt_e, partitions, parts_count);
539 	if (ret)
540 		goto err;
541 
542 	/* Write GPT partition table */
543 	ret = write_gpt_table(dev_desc, gpt_h, gpt_e);
544 
545 err:
546 	free(gpt_e);
547 	free(gpt_h);
548 	return ret;
549 }
550 
551 int is_valid_gpt_buf(block_dev_desc_t *dev_desc, void *buf)
552 {
553 	gpt_header *gpt_h;
554 	gpt_entry *gpt_e;
555 
556 	/* determine start of GPT Header in the buffer */
557 	gpt_h = buf + (GPT_PRIMARY_PARTITION_TABLE_LBA *
558 		       dev_desc->blksz);
559 	if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
560 				dev_desc->lba))
561 		return -1;
562 
563 	/* determine start of GPT Entries in the buffer */
564 	gpt_e = buf + (le64_to_cpu(gpt_h->partition_entry_lba) *
565 		       dev_desc->blksz);
566 	if (validate_gpt_entries(gpt_h, gpt_e))
567 		return -1;
568 
569 	return 0;
570 }
571 
572 int write_mbr_and_gpt_partitions(block_dev_desc_t *dev_desc, void *buf)
573 {
574 	gpt_header *gpt_h;
575 	gpt_entry *gpt_e;
576 	int gpt_e_blk_cnt;
577 	lbaint_t lba;
578 	int cnt;
579 
580 	if (is_valid_gpt_buf(dev_desc, buf))
581 		return -1;
582 
583 	/* determine start of GPT Header in the buffer */
584 	gpt_h = buf + (GPT_PRIMARY_PARTITION_TABLE_LBA *
585 		       dev_desc->blksz);
586 
587 	/* determine start of GPT Entries in the buffer */
588 	gpt_e = buf + (le64_to_cpu(gpt_h->partition_entry_lba) *
589 		       dev_desc->blksz);
590 	gpt_e_blk_cnt = BLOCK_CNT((le32_to_cpu(gpt_h->num_partition_entries) *
591 				   le32_to_cpu(gpt_h->sizeof_partition_entry)),
592 				  dev_desc);
593 
594 	/* write MBR */
595 	lba = 0;	/* MBR is always at 0 */
596 	cnt = 1;	/* MBR (1 block) */
597 	if (dev_desc->block_write(dev_desc->dev, lba, cnt, buf) != cnt) {
598 		printf("%s: failed writing '%s' (%d blks at 0x" LBAF ")\n",
599 		       __func__, "MBR", cnt, lba);
600 		return 1;
601 	}
602 
603 	/* write Primary GPT */
604 	lba = GPT_PRIMARY_PARTITION_TABLE_LBA;
605 	cnt = 1;	/* GPT Header (1 block) */
606 	if (dev_desc->block_write(dev_desc->dev, lba, cnt, gpt_h) != cnt) {
607 		printf("%s: failed writing '%s' (%d blks at 0x" LBAF ")\n",
608 		       __func__, "Primary GPT Header", cnt, lba);
609 		return 1;
610 	}
611 
612 	lba = le64_to_cpu(gpt_h->partition_entry_lba);
613 	cnt = gpt_e_blk_cnt;
614 	if (dev_desc->block_write(dev_desc->dev, lba, cnt, gpt_e) != cnt) {
615 		printf("%s: failed writing '%s' (%d blks at 0x" LBAF ")\n",
616 		       __func__, "Primary GPT Entries", cnt, lba);
617 		return 1;
618 	}
619 
620 	prepare_backup_gpt_header(gpt_h);
621 
622 	/* write Backup GPT */
623 	lba = le64_to_cpu(gpt_h->partition_entry_lba);
624 	cnt = gpt_e_blk_cnt;
625 	if (dev_desc->block_write(dev_desc->dev, lba, cnt, gpt_e) != cnt) {
626 		printf("%s: failed writing '%s' (%d blks at 0x" LBAF ")\n",
627 		       __func__, "Backup GPT Entries", cnt, lba);
628 		return 1;
629 	}
630 
631 	lba = le64_to_cpu(gpt_h->my_lba);
632 	cnt = 1;	/* GPT Header (1 block) */
633 	if (dev_desc->block_write(dev_desc->dev, lba, cnt, gpt_h) != cnt) {
634 		printf("%s: failed writing '%s' (%d blks at 0x" LBAF ")\n",
635 		       __func__, "Backup GPT Header", cnt, lba);
636 		return 1;
637 	}
638 
639 	return 0;
640 }
641 #endif
642 
643 /*
644  * Private functions
645  */
646 /*
647  * pmbr_part_valid(): Check for EFI partition signature
648  *
649  * Returns: 1 if EFI GPT partition type is found.
650  */
651 static int pmbr_part_valid(struct partition *part)
652 {
653 	if (part->sys_ind == EFI_PMBR_OSTYPE_EFI_GPT &&
654 		get_unaligned_le32(&part->start_sect) == 1UL) {
655 		return 1;
656 	}
657 
658 	return 0;
659 }
660 
661 /*
662  * is_pmbr_valid(): test Protective MBR for validity
663  *
664  * Returns: 1 if PMBR is valid, 0 otherwise.
665  * Validity depends on two things:
666  *  1) MSDOS signature is in the last two bytes of the MBR
667  *  2) One partition of type 0xEE is found, checked by pmbr_part_valid()
668  */
669 static int is_pmbr_valid(legacy_mbr * mbr)
670 {
671 	int i = 0;
672 
673 	if (!mbr || le16_to_cpu(mbr->signature) != MSDOS_MBR_SIGNATURE)
674 		return 0;
675 
676 	for (i = 0; i < 4; i++) {
677 		if (pmbr_part_valid(&mbr->partition_record[i])) {
678 			return 1;
679 		}
680 	}
681 	return 0;
682 }
683 
684 /**
685  * is_gpt_valid() - tests one GPT header and PTEs for validity
686  *
687  * lba is the logical block address of the GPT header to test
688  * gpt is a GPT header ptr, filled on return.
689  * ptes is a PTEs ptr, filled on return.
690  *
691  * Description: returns 1 if valid,  0 on error.
692  * If valid, returns pointers to PTEs.
693  */
694 static int is_gpt_valid(block_dev_desc_t *dev_desc, u64 lba,
695 			gpt_header *pgpt_head, gpt_entry **pgpt_pte)
696 {
697 	if (!dev_desc || !pgpt_head) {
698 		printf("%s: Invalid Argument(s)\n", __func__);
699 		return 0;
700 	}
701 
702 	/* Read GPT Header from device */
703 	if (dev_desc->block_read(dev_desc->dev, (lbaint_t)lba, 1, pgpt_head)
704 			!= 1) {
705 		printf("*** ERROR: Can't read GPT header ***\n");
706 		return 0;
707 	}
708 
709 	if (validate_gpt_header(pgpt_head, (lbaint_t)lba, dev_desc->lba))
710 		return 0;
711 
712 	/* Read and allocate Partition Table Entries */
713 	*pgpt_pte = alloc_read_gpt_entries(dev_desc, pgpt_head);
714 	if (*pgpt_pte == NULL) {
715 		printf("GPT: Failed to allocate memory for PTE\n");
716 		return 0;
717 	}
718 
719 	if (validate_gpt_entries(pgpt_head, *pgpt_pte)) {
720 		free(*pgpt_pte);
721 		return 0;
722 	}
723 
724 	/* We're done, all's well */
725 	return 1;
726 }
727 
728 /**
729  * alloc_read_gpt_entries(): reads partition entries from disk
730  * @dev_desc
731  * @gpt - GPT header
732  *
733  * Description: Returns ptes on success,  NULL on error.
734  * Allocates space for PTEs based on information found in @gpt.
735  * Notes: remember to free pte when you're done!
736  */
737 static gpt_entry *alloc_read_gpt_entries(block_dev_desc_t * dev_desc,
738 					 gpt_header * pgpt_head)
739 {
740 	size_t count = 0, blk_cnt;
741 	gpt_entry *pte = NULL;
742 
743 	if (!dev_desc || !pgpt_head) {
744 		printf("%s: Invalid Argument(s)\n", __func__);
745 		return NULL;
746 	}
747 
748 	count = le32_to_cpu(pgpt_head->num_partition_entries) *
749 		le32_to_cpu(pgpt_head->sizeof_partition_entry);
750 
751 	debug("%s: count = %u * %u = %zu\n", __func__,
752 	      (u32) le32_to_cpu(pgpt_head->num_partition_entries),
753 	      (u32) le32_to_cpu(pgpt_head->sizeof_partition_entry), count);
754 
755 	/* Allocate memory for PTE, remember to FREE */
756 	if (count != 0) {
757 		pte = memalign(ARCH_DMA_MINALIGN,
758 			       PAD_TO_BLOCKSIZE(count, dev_desc));
759 	}
760 
761 	if (count == 0 || pte == NULL) {
762 		printf("%s: ERROR: Can't allocate 0x%zX "
763 		       "bytes for GPT Entries\n",
764 			__func__, count);
765 		return NULL;
766 	}
767 
768 	/* Read GPT Entries from device */
769 	blk_cnt = BLOCK_CNT(count, dev_desc);
770 	if (dev_desc->block_read (dev_desc->dev,
771 		(lbaint_t)le64_to_cpu(pgpt_head->partition_entry_lba),
772 		(lbaint_t) (blk_cnt), pte)
773 		!= blk_cnt) {
774 
775 		printf("*** ERROR: Can't read GPT Entries ***\n");
776 		free(pte);
777 		return NULL;
778 	}
779 	return pte;
780 }
781 
782 /**
783  * is_pte_valid(): validates a single Partition Table Entry
784  * @gpt_entry - Pointer to a single Partition Table Entry
785  *
786  * Description: returns 1 if valid,  0 on error.
787  */
788 static int is_pte_valid(gpt_entry * pte)
789 {
790 	efi_guid_t unused_guid;
791 
792 	if (!pte) {
793 		printf("%s: Invalid Argument(s)\n", __func__);
794 		return 0;
795 	}
796 
797 	/* Only one validation for now:
798 	 * The GUID Partition Type != Unused Entry (ALL-ZERO)
799 	 */
800 	memset(unused_guid.b, 0, sizeof(unused_guid.b));
801 
802 	if (memcmp(pte->partition_type_guid.b, unused_guid.b,
803 		sizeof(unused_guid.b)) == 0) {
804 
805 		debug("%s: Found an unused PTE GUID at 0x%08X\n", __func__,
806 		      (unsigned int)(uintptr_t)pte);
807 
808 		return 0;
809 	} else {
810 		return 1;
811 	}
812 }
813 #endif
814