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