1 // SPDX-License-Identifier: GPL-2.0+
3 * cmd_gpt.c -- GPT (GUID Partition Table) handling command
6 * Lukasz Majewski <l.majewski@majess.pl>
8 * Copyright (C) 2012 Samsung Electronics
9 * author: Lukasz Majewski <l.majewski@samsung.com>
10 * author: Piotr Wilczek <p.wilczek@samsung.com>
18 #include <linux/ctype.h>
21 #include <linux/compat.h>
22 #include <linux/sizes.h>
25 static LIST_HEAD(disk_partitions);
28 * extract_env(): Expand env name from string format '&{env_name}'
29 * and return pointer to the env (if the env is set)
31 * @param str - pointer to string
32 * @param env - pointer to pointer to extracted env
34 * @return - zero on successful expand and env is set
36 static int extract_env(const char *str, char **env)
40 #ifdef CONFIG_RANDOM_UUID
41 char uuid_str[UUID_STR_LEN + 1];
44 if (!str || strlen(str) < 4)
47 if (!((strncmp(str, "${", 2) == 0) && (str[strlen(str) - 1] == '}')))
54 memset(s + strlen(s) - 1, '\0', 1);
55 memmove(s, s + 2, strlen(s) - 1);
59 #ifdef CONFIG_RANDOM_UUID
60 debug("%s unset. ", str);
61 gen_rand_uuid_str(uuid_str, UUID_STR_FORMAT_GUID);
66 debug("Set to random.\n");
69 debug("Can't get random UUID.\n");
72 debug("%s unset.\n", str);
75 debug("%s get from environment.\n", str);
86 * extract_val(): Extract value from a key=value pair list (comma separated).
87 * Only value for the given key is returend.
88 * Function allocates memory for the value, remember to free!
90 * @param str - pointer to string with key=values pairs
91 * @param key - pointer to the key to search for
93 * @return - pointer to allocated string with the value
95 static char *extract_val(const char *str, const char *key)
101 strcopy = strdup(str);
113 if (strcmp(k, key) == 0) {
125 * found_key(): Found key without value in parameter list (comma separated).
127 * @param str - pointer to string with key
128 * @param key - pointer to the key to search for
130 * @return - true on found key
132 static bool found_key(const char *str, const char *key)
138 strcopy = strdup(str);
147 if (strcmp(k, key) == 0) {
158 static int calc_parts_list_len(int numparts)
160 int partlistlen = UUID_STR_LEN + 1 + strlen("uuid_disk=");
164 /* per-partition additions; numparts starts at 1, so this should be correct */
165 partlistlen += numparts * (strlen("name=,") + PART_NAME_LEN + 1);
166 /* see part.h for definition of struct disk_partition */
167 partlistlen += numparts * (strlen("start=MiB,") + sizeof(lbaint_t) + 1);
168 partlistlen += numparts * (strlen("size=MiB,") + sizeof(lbaint_t) + 1);
169 partlistlen += numparts * (strlen("uuid=;") + UUID_STR_LEN + 1);
170 /* for the terminating null */
172 debug("Length of partitions_list is %d for %d partitions\n", partlistlen,
177 #ifdef CONFIG_CMD_GPT_RENAME
178 static void del_gpt_info(void)
180 struct list_head *pos = &disk_partitions;
181 struct disk_part *curr;
182 while (!list_empty(pos)) {
183 curr = list_entry(pos->next, struct disk_part, list);
189 static struct disk_part *allocate_disk_part(disk_partition_t *info, int partnum)
191 struct disk_part *newpart;
192 newpart = calloc(1, sizeof(struct disk_part));
194 return ERR_PTR(-ENOMEM);
196 newpart->gpt_part_info.start = info->start;
197 newpart->gpt_part_info.size = info->size;
198 newpart->gpt_part_info.blksz = info->blksz;
199 strncpy((char *)newpart->gpt_part_info.name, (const char *)info->name,
201 newpart->gpt_part_info.name[PART_NAME_LEN - 1] = '\0';
202 strncpy((char *)newpart->gpt_part_info.type, (const char *)info->type,
204 newpart->gpt_part_info.type[PART_TYPE_LEN - 1] = '\0';
205 newpart->gpt_part_info.bootable = info->bootable;
206 #ifdef CONFIG_PARTITION_UUIDS
207 strncpy(newpart->gpt_part_info.uuid, (const char *)info->uuid,
209 /* UUID_STR_LEN is correct, as uuid[]'s length is UUID_STR_LEN+1 chars */
210 newpart->gpt_part_info.uuid[UUID_STR_LEN] = '\0';
212 newpart->partnum = partnum;
217 static void prettyprint_part_size(char *sizestr, lbaint_t partsize,
220 unsigned long long partbytes, partmegabytes;
222 partbytes = partsize * blksize;
223 partmegabytes = lldiv(partbytes, SZ_1M);
224 snprintf(sizestr, 16, "%lluMiB", partmegabytes);
227 static void print_gpt_info(void)
229 struct list_head *pos;
230 struct disk_part *curr;
231 char partstartstr[16];
232 char partsizestr[16];
234 list_for_each(pos, &disk_partitions) {
235 curr = list_entry(pos, struct disk_part, list);
236 prettyprint_part_size(partstartstr, curr->gpt_part_info.start,
237 curr->gpt_part_info.blksz);
238 prettyprint_part_size(partsizestr, curr->gpt_part_info.size,
239 curr->gpt_part_info.blksz);
241 printf("Partition %d:\n", curr->partnum);
242 printf("Start %s, size %s\n", partstartstr, partsizestr);
243 printf("Block size %lu, name %s\n", curr->gpt_part_info.blksz,
244 curr->gpt_part_info.name);
245 printf("Type %s, bootable %d\n", curr->gpt_part_info.type,
246 curr->gpt_part_info.bootable);
247 #ifdef CONFIG_PARTITION_UUIDS
248 printf("UUID %s\n", curr->gpt_part_info.uuid);
255 * create the string that upstream 'gpt write' command will accept as an
258 * From doc/README.gpt, Format of partitions layout:
259 * "uuid_disk=...;name=u-boot,size=60MiB,uuid=...;
260 * name=kernel,size=60MiB,uuid=...;"
261 * The fields 'name' and 'size' are mandatory for every partition.
262 * The field 'start' is optional. The fields 'uuid' and 'uuid_disk'
263 * are optional if CONFIG_RANDOM_UUID is enabled.
265 static int create_gpt_partitions_list(int numparts, const char *guid,
266 char *partitions_list)
268 struct list_head *pos;
269 struct disk_part *curr;
270 char partstr[PART_NAME_LEN + 1];
272 if (!partitions_list)
275 strcpy(partitions_list, "uuid_disk=");
276 strncat(partitions_list, guid, UUID_STR_LEN + 1);
277 strcat(partitions_list, ";");
279 list_for_each(pos, &disk_partitions) {
280 curr = list_entry(pos, struct disk_part, list);
281 strcat(partitions_list, "name=");
282 strncat(partitions_list, (const char *)curr->gpt_part_info.name,
284 sprintf(partstr, ",start=0x%llx",
285 (unsigned long long)curr->gpt_part_info.start *
286 curr->gpt_part_info.blksz);
287 /* one extra byte for NULL */
288 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
289 sprintf(partstr, ",size=0x%llx",
290 (unsigned long long)curr->gpt_part_info.size *
291 curr->gpt_part_info.blksz);
292 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
294 strcat(partitions_list, ",uuid=");
295 strncat(partitions_list, curr->gpt_part_info.uuid,
297 strcat(partitions_list, ";");
303 * read partition info into disk_partitions list where
304 * it can be printed or modified
306 static int get_gpt_info(struct blk_desc *dev_desc)
308 /* start partition numbering at 1, as U-Boot does */
309 int valid_parts = 0, p, ret;
310 disk_partition_t info;
311 struct disk_part *new_disk_part;
314 * Always re-read partition info from device, in case
317 INIT_LIST_HEAD(&disk_partitions);
319 for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
320 ret = part_get_info(dev_desc, p, &info);
324 /* Add 1 here because counter is zero-based but p1 is
325 the first partition */
326 new_disk_part = allocate_disk_part(&info, valid_parts+1);
327 if (IS_ERR(new_disk_part))
330 list_add_tail(&new_disk_part->list, &disk_partitions);
333 if (valid_parts == 0) {
334 printf("** No valid partitions found **\n");
339 if (valid_parts >= 1)
344 /* a wrapper to test get_gpt_info */
345 static int do_get_gpt_info(struct blk_desc *dev_desc)
349 ret = get_gpt_info(dev_desc);
360 * set_gpt_info(): Fill partition information from string
361 * function allocates memory, remember to free!
363 * @param dev_desc - pointer block device descriptor
364 * @param str_part - pointer to string with partition information
365 * @param str_disk_guid - pointer to pointer to allocated string with disk guid
366 * @param partitions - pointer to pointer to allocated partitions array
367 * @param parts_count - number of partitions
369 * @return - zero on success, otherwise error
372 static int set_gpt_info(struct blk_desc *dev_desc,
373 const char *str_part,
374 char **str_disk_guid,
375 disk_partition_t **partitions,
382 disk_partition_t *parts;
384 uint64_t size_ll, start_ll;
386 int max_str_part = calc_parts_list_len(MAX_SEARCH_PARTITIONS);
388 debug("%s: lba num: 0x%x %d\n", __func__,
389 (unsigned int)dev_desc->lba, (unsigned int)dev_desc->lba);
391 if (str_part == NULL)
394 str = strdup(str_part);
398 /* extract disk guid */
400 val = extract_val(str, "uuid_disk");
402 #ifdef CONFIG_RANDOM_UUID
403 *str_disk_guid = malloc(UUID_STR_LEN + 1);
404 if (*str_disk_guid == NULL)
406 gen_rand_uuid_str(*str_disk_guid, UUID_STR_FORMAT_STD);
412 val = strsep(&val, ";");
413 if (extract_env(val, &p))
415 *str_disk_guid = strdup(p);
417 /* Move s to first partition */
421 printf("Error: is the partitions string NULL-terminated?\n");
424 if (strnlen(s, max_str_part) == 0)
427 i = strnlen(s, max_str_part) - 1;
431 /* calculate expected number of partitions */
439 /* allocate memory for partitions */
440 parts = calloc(sizeof(disk_partition_t), p_count);
444 /* retrieve partitions data from string */
445 for (i = 0; i < p_count; i++) {
446 tok = strsep(&s, ";");
452 val = extract_val(tok, "uuid");
454 /* 'uuid' is optional if random uuid's are enabled */
455 #ifdef CONFIG_RANDOM_UUID
456 gen_rand_uuid_str(parts[i].uuid, UUID_STR_FORMAT_STD);
462 if (extract_env(val, &p))
464 if (strnlen(p, max_str_part) >= sizeof(parts[i].uuid)) {
465 printf("Wrong uuid format for partition %d\n", i);
469 strncpy((char *)parts[i].uuid, p, max_str_part);
472 #ifdef CONFIG_PARTITION_TYPE_GUID
474 val = extract_val(tok, "type");
476 /* 'type' is optional */
477 if (extract_env(val, &p))
479 if (strnlen(p, max_str_part) >= sizeof(parts[i].type_guid)) {
480 printf("Wrong type guid format for partition %d\n",
485 strncpy((char *)parts[i].type_guid, p, max_str_part);
490 val = extract_val(tok, "name");
491 if (!val) { /* name is mandatory */
495 if (extract_env(val, &p))
497 if (strnlen(p, max_str_part) >= sizeof(parts[i].name)) {
501 strncpy((char *)parts[i].name, p, max_str_part);
505 val = extract_val(tok, "size");
506 if (!val) { /* 'size' is mandatory */
510 if (extract_env(val, &p))
512 if ((strcmp(p, "-") == 0)) {
513 /* Let part efi module to auto extend the size */
516 size_ll = ustrtoull(p, &p, 0);
517 parts[i].size = lldiv(size_ll, dev_desc->blksz);
523 val = extract_val(tok, "start");
524 if (val) { /* start address is optional */
525 if (extract_env(val, &p))
527 start_ll = ustrtoull(p, &p, 0);
528 parts[i].start = lldiv(start_ll, dev_desc->blksz);
532 offset += parts[i].size + parts[i].start;
535 if (found_key(tok, "bootable"))
536 parts[i].bootable = 1;
539 *parts_count = p_count;
546 free(*str_disk_guid);
552 static int gpt_default(struct blk_desc *blk_dev_desc, const char *str_part)
557 disk_partition_t *partitions = NULL;
559 /* fill partitions */
560 ret = set_gpt_info(blk_dev_desc, str_part,
561 &str_disk_guid, &partitions, &part_count);
564 printf("No partition list provided\n");
566 printf("Missing disk guid\n");
567 if ((ret == -3) || (ret == -4))
568 printf("Partition list incomplete\n");
572 /* save partitions layout to disk */
573 ret = gpt_restore(blk_dev_desc, str_disk_guid, partitions, part_count);
580 static int gpt_verify(struct blk_desc *blk_dev_desc, const char *str_part)
582 ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1,
583 blk_dev_desc->blksz);
584 disk_partition_t *partitions = NULL;
585 gpt_entry *gpt_pte = NULL;
590 /* fill partitions */
591 ret = set_gpt_info(blk_dev_desc, str_part,
592 &str_disk_guid, &partitions, &part_count);
595 printf("No partition list provided - only basic check\n");
596 ret = gpt_verify_headers(blk_dev_desc, gpt_head,
601 printf("Missing disk guid\n");
602 if ((ret == -3) || (ret == -4))
603 printf("Partition list incomplete\n");
607 /* Check partition layout with provided pattern */
608 ret = gpt_verify_partitions(blk_dev_desc, partitions, part_count,
617 static int do_disk_guid(struct blk_desc *dev_desc, char * const namestr)
620 char disk_guid[UUID_STR_LEN + 1];
622 ret = get_disk_guid(dev_desc, disk_guid);
624 return CMD_RET_FAILURE;
627 env_set(namestr, disk_guid);
629 printf("%s\n", disk_guid);
634 #ifdef CONFIG_CMD_GPT_RENAME
636 * There are 3 malloc() calls in set_gpt_info() and there is no info about which
639 static void set_gpt_cleanup(char **str_disk_guid,
640 disk_partition_t **partitions)
642 #ifdef CONFIG_RANDOM_UUID
650 static int do_rename_gpt_parts(struct blk_desc *dev_desc, char *subcomm,
651 char *name1, char *name2)
653 struct list_head *pos;
654 struct disk_part *curr;
655 disk_partition_t *new_partitions = NULL;
656 char disk_guid[UUID_STR_LEN + 1];
657 char *partitions_list, *str_disk_guid;
659 int partlistlen, ret, numparts = 0, partnum, i = 1, ctr1 = 0, ctr2 = 0;
661 if ((subcomm == NULL) || (name1 == NULL) || (name2 == NULL) ||
662 (strcmp(subcomm, "swap") && (strcmp(subcomm, "rename"))))
665 ret = get_disk_guid(dev_desc, disk_guid);
669 * Allocates disk_partitions, requiring matching call to del_gpt_info()
672 numparts = get_gpt_info(dev_desc);
674 return numparts ? numparts : -ENODEV;
676 partlistlen = calc_parts_list_len(numparts);
677 partitions_list = malloc(partlistlen);
678 if (!partitions_list) {
682 memset(partitions_list, '\0', partlistlen);
684 ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
686 free(partitions_list);
690 * Uncomment the following line to print a string that 'gpt write'
691 * or 'gpt verify' will accept as input.
693 debug("OLD partitions_list is %s with %u chars\n", partitions_list,
694 (unsigned)strlen(partitions_list));
696 /* set_gpt_info allocates new_partitions and str_disk_guid */
697 ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
698 &new_partitions, &part_count);
701 free(partitions_list);
703 set_gpt_cleanup(&str_disk_guid, &new_partitions);
708 if (!strcmp(subcomm, "swap")) {
709 if ((strlen(name1) > PART_NAME_LEN) || (strlen(name2) > PART_NAME_LEN)) {
710 printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
714 list_for_each(pos, &disk_partitions) {
715 curr = list_entry(pos, struct disk_part, list);
716 if (!strcmp((char *)curr->gpt_part_info.name, name1)) {
717 strcpy((char *)curr->gpt_part_info.name, name2);
719 } else if (!strcmp((char *)curr->gpt_part_info.name, name2)) {
720 strcpy((char *)curr->gpt_part_info.name, name1);
724 if ((ctr1 + ctr2 < 2) || (ctr1 != ctr2)) {
725 printf("Cannot swap partition names except in pairs.\n");
729 } else { /* rename */
730 if (strlen(name2) > PART_NAME_LEN) {
731 printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
735 partnum = (int)simple_strtol(name1, NULL, 10);
736 if ((partnum < 0) || (partnum > numparts)) {
737 printf("Illegal partition number %s\n", name1);
741 ret = part_get_info(dev_desc, partnum, new_partitions);
745 /* U-Boot partition numbering starts at 1 */
746 list_for_each(pos, &disk_partitions) {
747 curr = list_entry(pos, struct disk_part, list);
749 strcpy((char *)curr->gpt_part_info.name, name2);
756 ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
759 debug("NEW partitions_list is %s with %u chars\n", partitions_list,
760 (unsigned)strlen(partitions_list));
762 ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
763 &new_partitions, &part_count);
765 * Even though valid pointers are here passed into set_gpt_info(),
766 * it mallocs again, and there's no way to tell which failed.
770 free(partitions_list);
772 set_gpt_cleanup(&str_disk_guid, &new_partitions);
777 debug("Writing new partition table\n");
778 ret = gpt_restore(dev_desc, disk_guid, new_partitions, numparts);
780 printf("Writing new partition table failed\n");
784 debug("Reading back new partition table\n");
786 * Empty the existing disk_partitions list, as otherwise the memory in
787 * the original list is unreachable.
790 numparts = get_gpt_info(dev_desc);
792 ret = numparts ? numparts : -ENODEV;
795 printf("new partition table with %d partitions is:\n", numparts);
799 free(new_partitions);
801 free(partitions_list);
807 * do_gpt(): Perform GPT operations
809 * @param cmdtp - command name
814 * @return zero on success; otherwise error
816 static int do_gpt(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
818 int ret = CMD_RET_SUCCESS;
821 struct blk_desc *blk_dev_desc = NULL;
823 #ifndef CONFIG_CMD_GPT_RENAME
824 if (argc < 4 || argc > 5)
826 if (argc < 4 || argc > 6)
828 return CMD_RET_USAGE;
830 dev = (int)simple_strtoul(argv[3], &ep, 10);
831 if (!ep || ep[0] != '\0') {
832 printf("'%s' is not a number\n", argv[3]);
833 return CMD_RET_USAGE;
835 blk_dev_desc = blk_get_dev(argv[2], dev);
837 printf("%s: %s dev %d NOT available\n",
838 __func__, argv[2], dev);
839 return CMD_RET_FAILURE;
842 if ((strcmp(argv[1], "write") == 0) && (argc == 5)) {
843 printf("Writing GPT: ");
844 ret = gpt_default(blk_dev_desc, argv[4]);
845 } else if ((strcmp(argv[1], "verify") == 0)) {
846 ret = gpt_verify(blk_dev_desc, argv[4]);
847 printf("Verify GPT: ");
848 } else if (strcmp(argv[1], "guid") == 0) {
849 ret = do_disk_guid(blk_dev_desc, argv[4]);
850 #ifdef CONFIG_CMD_GPT_RENAME
851 } else if (strcmp(argv[1], "read") == 0) {
852 ret = do_get_gpt_info(blk_dev_desc);
853 } else if ((strcmp(argv[1], "swap") == 0) ||
854 (strcmp(argv[1], "rename") == 0)) {
855 ret = do_rename_gpt_parts(blk_dev_desc, argv[1], argv[4], argv[5]);
858 return CMD_RET_USAGE;
863 return CMD_RET_FAILURE;
866 printf("success!\n");
867 return CMD_RET_SUCCESS;
870 U_BOOT_CMD(gpt, CONFIG_SYS_MAXARGS, 1, do_gpt,
871 "GUID Partition Table",
872 "<command> <interface> <dev> <partitions_list>\n"
873 " - GUID partition table restoration and validity check\n"
874 " Restore or verify GPT information on a device connected\n"
877 " gpt write mmc 0 $partitions\n"
878 " gpt verify mmc 0 $partitions\n"
879 " gpt guid <interface> <dev>\n"
880 " - print disk GUID\n"
881 " gpt guid <interface> <dev> <varname>\n"
882 " - set environment variable to disk GUID\n"
885 " gpt guid mmc 0 varname\n"
886 #ifdef CONFIG_CMD_GPT_RENAME
887 "gpt partition renaming commands:\n"
888 " gpt read <interface> <dev>\n"
889 " - read GPT into a data structure for manipulation\n"
890 " gpt swap <interface> <dev> <name1> <name2>\n"
891 " - change all partitions named name1 to name2\n"
893 " gpt rename <interface> <dev> <part> <name>\n"
894 " - rename the specified partition\n"
896 " gpt swap mmc 0 foo bar\n"
897 " gpt rename mmc 0 3 foo\n"