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