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