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>
19 #include <linux/ctype.h>
22 #include <linux/compat.h>
23 #include <linux/err.h>
24 #include <linux/sizes.h>
27 static LIST_HEAD(disk_partitions);
30 * extract_env(): Expand env name from string format '&{env_name}'
31 * and return pointer to the env (if the env is set)
33 * @param str - pointer to string
34 * @param env - pointer to pointer to extracted env
36 * @return - zero on successful expand and env is set
38 static int extract_env(const char *str, char **env)
42 #ifdef CONFIG_RANDOM_UUID
43 char uuid_str[UUID_STR_LEN + 1];
46 if (!str || strlen(str) < 4)
49 if (!((strncmp(str, "${", 2) == 0) && (str[strlen(str) - 1] == '}')))
56 memset(s + strlen(s) - 1, '\0', 1);
57 memmove(s, s + 2, strlen(s) - 1);
61 #ifdef CONFIG_RANDOM_UUID
62 debug("%s unset. ", str);
63 gen_rand_uuid_str(uuid_str, UUID_STR_FORMAT_GUID);
68 debug("Set to random.\n");
71 debug("Can't get random UUID.\n");
74 debug("%s unset.\n", str);
77 debug("%s get from environment.\n", str);
88 * extract_val(): Extract value from a key=value pair list (comma separated).
89 * Only value for the given key is returend.
90 * Function allocates memory for the value, remember to free!
92 * @param str - pointer to string with key=values pairs
93 * @param key - pointer to the key to search for
95 * @return - pointer to allocated string with the value
97 static char *extract_val(const char *str, const char *key)
103 strcopy = strdup(str);
115 if (strcmp(k, key) == 0) {
127 * found_key(): Found key without value in parameter list (comma separated).
129 * @param str - pointer to string with key
130 * @param key - pointer to the key to search for
132 * @return - true on found key
134 static bool found_key(const char *str, const char *key)
140 strcopy = strdup(str);
149 if (strcmp(k, key) == 0) {
160 static int calc_parts_list_len(int numparts)
162 int partlistlen = UUID_STR_LEN + 1 + strlen("uuid_disk=");
166 /* per-partition additions; numparts starts at 1, so this should be correct */
167 partlistlen += numparts * (strlen("name=,") + PART_NAME_LEN + 1);
168 /* see part.h for definition of struct disk_partition */
169 partlistlen += numparts * (strlen("start=MiB,") + sizeof(lbaint_t) + 1);
170 partlistlen += numparts * (strlen("size=MiB,") + sizeof(lbaint_t) + 1);
171 partlistlen += numparts * (strlen("uuid=;") + UUID_STR_LEN + 1);
172 /* for the terminating null */
174 debug("Length of partitions_list is %d for %d partitions\n", partlistlen,
179 #ifdef CONFIG_CMD_GPT_RENAME
180 static void del_gpt_info(void)
182 struct list_head *pos = &disk_partitions;
183 struct disk_part *curr;
184 while (!list_empty(pos)) {
185 curr = list_entry(pos->next, struct disk_part, list);
191 static struct disk_part *allocate_disk_part(disk_partition_t *info, int partnum)
193 struct disk_part *newpart;
194 newpart = calloc(1, sizeof(struct disk_part));
196 return ERR_PTR(-ENOMEM);
198 newpart->gpt_part_info.start = info->start;
199 newpart->gpt_part_info.size = info->size;
200 newpart->gpt_part_info.blksz = info->blksz;
201 strncpy((char *)newpart->gpt_part_info.name, (const char *)info->name,
203 newpart->gpt_part_info.name[PART_NAME_LEN - 1] = '\0';
204 strncpy((char *)newpart->gpt_part_info.type, (const char *)info->type,
206 newpart->gpt_part_info.type[PART_TYPE_LEN - 1] = '\0';
207 newpart->gpt_part_info.bootable = info->bootable;
208 #ifdef CONFIG_PARTITION_UUIDS
209 strncpy(newpart->gpt_part_info.uuid, (const char *)info->uuid,
211 /* UUID_STR_LEN is correct, as uuid[]'s length is UUID_STR_LEN+1 chars */
212 newpart->gpt_part_info.uuid[UUID_STR_LEN] = '\0';
214 newpart->partnum = partnum;
219 static void prettyprint_part_size(char *sizestr, lbaint_t partsize,
222 unsigned long long partbytes, partmegabytes;
224 partbytes = partsize * blksize;
225 partmegabytes = lldiv(partbytes, SZ_1M);
226 snprintf(sizestr, 16, "%lluMiB", partmegabytes);
229 static void print_gpt_info(void)
231 struct list_head *pos;
232 struct disk_part *curr;
233 char partstartstr[16];
234 char partsizestr[16];
236 list_for_each(pos, &disk_partitions) {
237 curr = list_entry(pos, struct disk_part, list);
238 prettyprint_part_size(partstartstr, curr->gpt_part_info.start,
239 curr->gpt_part_info.blksz);
240 prettyprint_part_size(partsizestr, curr->gpt_part_info.size,
241 curr->gpt_part_info.blksz);
243 printf("Partition %d:\n", curr->partnum);
244 printf("Start %s, size %s\n", partstartstr, partsizestr);
245 printf("Block size %lu, name %s\n", curr->gpt_part_info.blksz,
246 curr->gpt_part_info.name);
247 printf("Type %s, bootable %d\n", curr->gpt_part_info.type,
248 curr->gpt_part_info.bootable);
249 #ifdef CONFIG_PARTITION_UUIDS
250 printf("UUID %s\n", curr->gpt_part_info.uuid);
257 * create the string that upstream 'gpt write' command will accept as an
260 * From doc/README.gpt, Format of partitions layout:
261 * "uuid_disk=...;name=u-boot,size=60MiB,uuid=...;
262 * name=kernel,size=60MiB,uuid=...;"
263 * The fields 'name' and 'size' are mandatory for every partition.
264 * The field 'start' is optional. The fields 'uuid' and 'uuid_disk'
265 * are optional if CONFIG_RANDOM_UUID is enabled.
267 static int create_gpt_partitions_list(int numparts, const char *guid,
268 char *partitions_list)
270 struct list_head *pos;
271 struct disk_part *curr;
272 char partstr[PART_NAME_LEN + 1];
274 if (!partitions_list)
277 strcpy(partitions_list, "uuid_disk=");
278 strncat(partitions_list, guid, UUID_STR_LEN + 1);
279 strcat(partitions_list, ";");
281 list_for_each(pos, &disk_partitions) {
282 curr = list_entry(pos, struct disk_part, list);
283 strcat(partitions_list, "name=");
284 strncat(partitions_list, (const char *)curr->gpt_part_info.name,
286 sprintf(partstr, ",start=0x%llx",
287 (unsigned long long)curr->gpt_part_info.start *
288 curr->gpt_part_info.blksz);
289 /* one extra byte for NULL */
290 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
291 sprintf(partstr, ",size=0x%llx",
292 (unsigned long long)curr->gpt_part_info.size *
293 curr->gpt_part_info.blksz);
294 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
296 strcat(partitions_list, ",uuid=");
297 strncat(partitions_list, curr->gpt_part_info.uuid,
299 strcat(partitions_list, ";");
305 * read partition info into disk_partitions list where
306 * it can be printed or modified
308 static int get_gpt_info(struct blk_desc *dev_desc)
310 /* start partition numbering at 1, as U-Boot does */
311 int valid_parts = 0, p, ret;
312 disk_partition_t info;
313 struct disk_part *new_disk_part;
316 * Always re-read partition info from device, in case
319 INIT_LIST_HEAD(&disk_partitions);
321 for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
322 ret = part_get_info(dev_desc, p, &info);
326 /* Add 1 here because counter is zero-based but p1 is
327 the first partition */
328 new_disk_part = allocate_disk_part(&info, valid_parts+1);
329 if (IS_ERR(new_disk_part))
332 list_add_tail(&new_disk_part->list, &disk_partitions);
335 if (valid_parts == 0) {
336 printf("** No valid partitions found **\n");
341 if (valid_parts >= 1)
346 /* a wrapper to test get_gpt_info */
347 static int do_get_gpt_info(struct blk_desc *dev_desc)
351 ret = get_gpt_info(dev_desc);
362 * set_gpt_info(): Fill partition information from string
363 * function allocates memory, remember to free!
365 * @param dev_desc - pointer block device descriptor
366 * @param str_part - pointer to string with partition information
367 * @param str_disk_guid - pointer to pointer to allocated string with disk guid
368 * @param partitions - pointer to pointer to allocated partitions array
369 * @param parts_count - number of partitions
371 * @return - zero on success, otherwise error
374 static int set_gpt_info(struct blk_desc *dev_desc,
375 const char *str_part,
376 char **str_disk_guid,
377 disk_partition_t **partitions,
384 disk_partition_t *parts;
386 uint64_t size_ll, start_ll;
388 int max_str_part = calc_parts_list_len(MAX_SEARCH_PARTITIONS);
390 debug("%s: lba num: 0x%x %d\n", __func__,
391 (unsigned int)dev_desc->lba, (unsigned int)dev_desc->lba);
393 if (str_part == NULL)
396 str = strdup(str_part);
400 /* extract disk guid */
402 val = extract_val(str, "uuid_disk");
404 #ifdef CONFIG_RANDOM_UUID
405 *str_disk_guid = malloc(UUID_STR_LEN + 1);
406 if (*str_disk_guid == NULL)
408 gen_rand_uuid_str(*str_disk_guid, UUID_STR_FORMAT_STD);
414 val = strsep(&val, ";");
415 if (extract_env(val, &p))
417 *str_disk_guid = strdup(p);
419 /* Move s to first partition */
423 printf("Error: is the partitions string NULL-terminated?\n");
426 if (strnlen(s, max_str_part) == 0)
429 i = strnlen(s, max_str_part) - 1;
433 /* calculate expected number of partitions */
441 /* allocate memory for partitions */
442 parts = calloc(sizeof(disk_partition_t), p_count);
446 /* retrieve partitions data from string */
447 for (i = 0; i < p_count; i++) {
448 tok = strsep(&s, ";");
454 val = extract_val(tok, "uuid");
456 /* 'uuid' is optional if random uuid's are enabled */
457 #ifdef CONFIG_RANDOM_UUID
458 gen_rand_uuid_str(parts[i].uuid, UUID_STR_FORMAT_STD);
464 if (extract_env(val, &p))
466 if (strnlen(p, max_str_part) >= sizeof(parts[i].uuid)) {
467 printf("Wrong uuid format for partition %d\n", i);
471 strncpy((char *)parts[i].uuid, p, max_str_part);
474 #ifdef CONFIG_PARTITION_TYPE_GUID
476 val = extract_val(tok, "type");
478 /* 'type' is optional */
479 if (extract_env(val, &p))
481 if (strnlen(p, max_str_part) >= sizeof(parts[i].type_guid)) {
482 printf("Wrong type guid format for partition %d\n",
487 strncpy((char *)parts[i].type_guid, p, max_str_part);
492 val = extract_val(tok, "name");
493 if (!val) { /* name is mandatory */
497 if (extract_env(val, &p))
499 if (strnlen(p, max_str_part) >= sizeof(parts[i].name)) {
503 strncpy((char *)parts[i].name, p, max_str_part);
507 val = extract_val(tok, "size");
508 if (!val) { /* 'size' is mandatory */
512 if (extract_env(val, &p))
514 if ((strcmp(p, "-") == 0)) {
515 /* Let part efi module to auto extend the size */
518 size_ll = ustrtoull(p, &p, 0);
519 parts[i].size = lldiv(size_ll, dev_desc->blksz);
525 val = extract_val(tok, "start");
526 if (val) { /* start address is optional */
527 if (extract_env(val, &p))
529 start_ll = ustrtoull(p, &p, 0);
530 parts[i].start = lldiv(start_ll, dev_desc->blksz);
534 offset += parts[i].size + parts[i].start;
537 if (found_key(tok, "bootable"))
538 parts[i].bootable = 1;
541 *parts_count = p_count;
548 free(*str_disk_guid);
554 static int gpt_default(struct blk_desc *blk_dev_desc, const char *str_part)
559 disk_partition_t *partitions = NULL;
561 /* fill partitions */
562 ret = set_gpt_info(blk_dev_desc, str_part,
563 &str_disk_guid, &partitions, &part_count);
566 printf("No partition list provided\n");
568 printf("Missing disk guid\n");
569 if ((ret == -3) || (ret == -4))
570 printf("Partition list incomplete\n");
574 /* save partitions layout to disk */
575 ret = gpt_restore(blk_dev_desc, str_disk_guid, partitions, part_count);
582 static int gpt_verify(struct blk_desc *blk_dev_desc, const char *str_part)
584 ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1,
585 blk_dev_desc->blksz);
586 disk_partition_t *partitions = NULL;
587 gpt_entry *gpt_pte = NULL;
592 /* fill partitions */
593 ret = set_gpt_info(blk_dev_desc, str_part,
594 &str_disk_guid, &partitions, &part_count);
597 printf("No partition list provided - only basic check\n");
598 ret = gpt_verify_headers(blk_dev_desc, gpt_head,
603 printf("Missing disk guid\n");
604 if ((ret == -3) || (ret == -4))
605 printf("Partition list incomplete\n");
609 /* Check partition layout with provided pattern */
610 ret = gpt_verify_partitions(blk_dev_desc, partitions, part_count,
619 static int do_disk_guid(struct blk_desc *dev_desc, char * const namestr)
622 char disk_guid[UUID_STR_LEN + 1];
624 ret = get_disk_guid(dev_desc, disk_guid);
626 return CMD_RET_FAILURE;
629 env_set(namestr, disk_guid);
631 printf("%s\n", disk_guid);
636 #ifdef CONFIG_CMD_GPT_RENAME
637 static int do_rename_gpt_parts(struct blk_desc *dev_desc, char *subcomm,
638 char *name1, char *name2)
640 struct list_head *pos;
641 struct disk_part *curr;
642 disk_partition_t *new_partitions = NULL;
643 char disk_guid[UUID_STR_LEN + 1];
644 char *partitions_list, *str_disk_guid = NULL;
646 int partlistlen, ret, numparts = 0, partnum, i = 1, ctr1 = 0, ctr2 = 0;
648 if ((subcomm == NULL) || (name1 == NULL) || (name2 == NULL) ||
649 (strcmp(subcomm, "swap") && (strcmp(subcomm, "rename"))))
652 ret = get_disk_guid(dev_desc, disk_guid);
656 * Allocates disk_partitions, requiring matching call to del_gpt_info()
659 numparts = get_gpt_info(dev_desc);
661 return numparts ? numparts : -ENODEV;
663 partlistlen = calc_parts_list_len(numparts);
664 partitions_list = malloc(partlistlen);
665 if (!partitions_list) {
669 memset(partitions_list, '\0', partlistlen);
671 ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
673 free(partitions_list);
677 * Uncomment the following line to print a string that 'gpt write'
678 * or 'gpt verify' will accept as input.
680 debug("OLD partitions_list is %s with %u chars\n", partitions_list,
681 (unsigned)strlen(partitions_list));
683 /* set_gpt_info allocates new_partitions and str_disk_guid */
684 ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
685 &new_partitions, &part_count);
689 if (!strcmp(subcomm, "swap")) {
690 if ((strlen(name1) > PART_NAME_LEN) || (strlen(name2) > PART_NAME_LEN)) {
691 printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
695 list_for_each(pos, &disk_partitions) {
696 curr = list_entry(pos, struct disk_part, list);
697 if (!strcmp((char *)curr->gpt_part_info.name, name1)) {
698 strcpy((char *)curr->gpt_part_info.name, name2);
700 } else if (!strcmp((char *)curr->gpt_part_info.name, name2)) {
701 strcpy((char *)curr->gpt_part_info.name, name1);
705 if ((ctr1 + ctr2 < 2) || (ctr1 != ctr2)) {
706 printf("Cannot swap partition names except in pairs.\n");
710 } else { /* rename */
711 if (strlen(name2) > PART_NAME_LEN) {
712 printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
716 partnum = (int)simple_strtol(name1, NULL, 10);
717 if ((partnum < 0) || (partnum > numparts)) {
718 printf("Illegal partition number %s\n", name1);
722 ret = part_get_info(dev_desc, partnum, new_partitions);
726 /* U-Boot partition numbering starts at 1 */
727 list_for_each(pos, &disk_partitions) {
728 curr = list_entry(pos, struct disk_part, list);
730 strcpy((char *)curr->gpt_part_info.name, name2);
737 ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
740 debug("NEW partitions_list is %s with %u chars\n", partitions_list,
741 (unsigned)strlen(partitions_list));
743 ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
744 &new_partitions, &part_count);
746 * Even though valid pointers are here passed into set_gpt_info(),
747 * it mallocs again, and there's no way to tell which failed.
752 debug("Writing new partition table\n");
753 ret = gpt_restore(dev_desc, disk_guid, new_partitions, numparts);
755 printf("Writing new partition table failed\n");
759 debug("Reading back new partition table\n");
761 * Empty the existing disk_partitions list, as otherwise the memory in
762 * the original list is unreachable.
765 numparts = get_gpt_info(dev_desc);
767 ret = numparts ? numparts : -ENODEV;
770 printf("new partition table with %d partitions is:\n", numparts);
774 #ifdef CONFIG_RANDOM_UUID
779 free(new_partitions);
780 free(partitions_list);
786 * do_gpt(): Perform GPT operations
788 * @param cmdtp - command name
793 * @return zero on success; otherwise error
795 static int do_gpt(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
797 int ret = CMD_RET_SUCCESS;
800 struct blk_desc *blk_dev_desc = NULL;
802 #ifndef CONFIG_CMD_GPT_RENAME
803 if (argc < 4 || argc > 5)
805 if (argc < 4 || argc > 6)
807 return CMD_RET_USAGE;
809 dev = (int)simple_strtoul(argv[3], &ep, 10);
810 if (!ep || ep[0] != '\0') {
811 printf("'%s' is not a number\n", argv[3]);
812 return CMD_RET_USAGE;
814 blk_dev_desc = blk_get_dev(argv[2], dev);
816 printf("%s: %s dev %d NOT available\n",
817 __func__, argv[2], dev);
818 return CMD_RET_FAILURE;
821 if ((strcmp(argv[1], "write") == 0) && (argc == 5)) {
822 printf("Writing GPT: ");
823 ret = gpt_default(blk_dev_desc, argv[4]);
824 } else if ((strcmp(argv[1], "verify") == 0)) {
825 ret = gpt_verify(blk_dev_desc, argv[4]);
826 printf("Verify GPT: ");
827 } else if (strcmp(argv[1], "guid") == 0) {
828 ret = do_disk_guid(blk_dev_desc, argv[4]);
829 #ifdef CONFIG_CMD_GPT_RENAME
830 } else if (strcmp(argv[1], "read") == 0) {
831 ret = do_get_gpt_info(blk_dev_desc);
832 } else if ((strcmp(argv[1], "swap") == 0) ||
833 (strcmp(argv[1], "rename") == 0)) {
834 ret = do_rename_gpt_parts(blk_dev_desc, argv[1], argv[4], argv[5]);
837 return CMD_RET_USAGE;
842 return CMD_RET_FAILURE;
845 printf("success!\n");
846 return CMD_RET_SUCCESS;
849 U_BOOT_CMD(gpt, CONFIG_SYS_MAXARGS, 1, do_gpt,
850 "GUID Partition Table",
851 "<command> <interface> <dev> <partitions_list>\n"
852 " - GUID partition table restoration and validity check\n"
853 " Restore or verify GPT information on a device connected\n"
856 " gpt write mmc 0 $partitions\n"
857 " gpt verify mmc 0 $partitions\n"
858 " gpt guid <interface> <dev>\n"
859 " - print disk GUID\n"
860 " gpt guid <interface> <dev> <varname>\n"
861 " - set environment variable to disk GUID\n"
864 " gpt guid mmc 0 varname\n"
865 #ifdef CONFIG_CMD_GPT_RENAME
866 "gpt partition renaming commands:\n"
867 " gpt read <interface> <dev>\n"
868 " - read GPT into a data structure for manipulation\n"
869 " gpt swap <interface> <dev> <name1> <name2>\n"
870 " - change all partitions named name1 to name2\n"
872 " gpt rename <interface> <dev> <part> <name>\n"
873 " - rename the specified partition\n"
875 " gpt swap mmc 0 foo bar\n"
876 " gpt rename mmc 0 3 foo\n"