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>
23 #include <linux/ctype.h>
26 #include <linux/compat.h>
27 #include <linux/err.h>
28 #include <linux/sizes.h>
31 static LIST_HEAD(disk_partitions);
34 * extract_env(): Expand env name from string format '&{env_name}'
35 * and return pointer to the env (if the env is set)
37 * @param str - pointer to string
38 * @param env - pointer to pointer to extracted env
40 * @return - zero on successful expand and env is set
42 static int extract_env(const char *str, char **env)
46 #ifdef CONFIG_RANDOM_UUID
47 char uuid_str[UUID_STR_LEN + 1];
50 if (!str || strlen(str) < 4)
53 if (!((strncmp(str, "${", 2) == 0) && (str[strlen(str) - 1] == '}')))
60 memset(s + strlen(s) - 1, '\0', 1);
61 memmove(s, s + 2, strlen(s) - 1);
65 #ifdef CONFIG_RANDOM_UUID
66 debug("%s unset. ", str);
67 gen_rand_uuid_str(uuid_str, UUID_STR_FORMAT_GUID);
72 debug("Set to random.\n");
75 debug("Can't get random UUID.\n");
78 debug("%s unset.\n", str);
81 debug("%s get from environment.\n", str);
92 * extract_val(): Extract value from a key=value pair list (comma separated).
93 * Only value for the given key is returend.
94 * Function allocates memory for the value, remember to free!
96 * @param str - pointer to string with key=values pairs
97 * @param key - pointer to the key to search for
99 * @return - pointer to allocated string with the value
101 static char *extract_val(const char *str, const char *key)
107 strcopy = strdup(str);
119 if (strcmp(k, key) == 0) {
131 * found_key(): Found key without value in parameter list (comma separated).
133 * @param str - pointer to string with key
134 * @param key - pointer to the key to search for
136 * @return - true on found key
138 static bool found_key(const char *str, const char *key)
144 strcopy = strdup(str);
153 if (strcmp(k, key) == 0) {
164 static int calc_parts_list_len(int numparts)
166 int partlistlen = UUID_STR_LEN + 1 + strlen("uuid_disk=");
170 /* per-partition additions; numparts starts at 1, so this should be correct */
171 partlistlen += numparts * (strlen("name=,") + PART_NAME_LEN + 1);
172 /* see part.h for definition of struct disk_partition */
173 partlistlen += numparts * (strlen("start=MiB,") + sizeof(lbaint_t) + 1);
174 partlistlen += numparts * (strlen("size=MiB,") + sizeof(lbaint_t) + 1);
175 partlistlen += numparts * (strlen("uuid=;") + UUID_STR_LEN + 1);
176 /* for the terminating null */
178 debug("Length of partitions_list is %d for %d partitions\n", partlistlen,
183 #ifdef CONFIG_CMD_GPT_RENAME
184 static void del_gpt_info(void)
186 struct list_head *pos = &disk_partitions;
187 struct disk_part *curr;
188 while (!list_empty(pos)) {
189 curr = list_entry(pos->next, struct disk_part, list);
195 static struct disk_part *allocate_disk_part(struct disk_partition *info,
198 struct disk_part *newpart;
199 newpart = calloc(1, sizeof(struct disk_part));
201 return ERR_PTR(-ENOMEM);
203 newpart->gpt_part_info.start = info->start;
204 newpart->gpt_part_info.size = info->size;
205 newpart->gpt_part_info.blksz = info->blksz;
206 strncpy((char *)newpart->gpt_part_info.name, (const char *)info->name,
208 newpart->gpt_part_info.name[PART_NAME_LEN - 1] = '\0';
209 strncpy((char *)newpart->gpt_part_info.type, (const char *)info->type,
211 newpart->gpt_part_info.type[PART_TYPE_LEN - 1] = '\0';
212 newpart->gpt_part_info.bootable = info->bootable;
213 #ifdef CONFIG_PARTITION_UUIDS
214 strncpy(newpart->gpt_part_info.uuid, (const char *)info->uuid,
216 /* UUID_STR_LEN is correct, as uuid[]'s length is UUID_STR_LEN+1 chars */
217 newpart->gpt_part_info.uuid[UUID_STR_LEN] = '\0';
219 newpart->partnum = partnum;
224 static void prettyprint_part_size(char *sizestr, lbaint_t partsize,
227 unsigned long long partbytes, partmegabytes;
229 partbytes = partsize * blksize;
230 partmegabytes = lldiv(partbytes, SZ_1M);
231 snprintf(sizestr, 16, "%lluMiB", partmegabytes);
234 static void print_gpt_info(void)
236 struct list_head *pos;
237 struct disk_part *curr;
238 char partstartstr[16];
239 char partsizestr[16];
241 list_for_each(pos, &disk_partitions) {
242 curr = list_entry(pos, struct disk_part, list);
243 prettyprint_part_size(partstartstr, curr->gpt_part_info.start,
244 curr->gpt_part_info.blksz);
245 prettyprint_part_size(partsizestr, curr->gpt_part_info.size,
246 curr->gpt_part_info.blksz);
248 printf("Partition %d:\n", curr->partnum);
249 printf("Start %s, size %s\n", partstartstr, partsizestr);
250 printf("Block size %lu, name %s\n", curr->gpt_part_info.blksz,
251 curr->gpt_part_info.name);
252 printf("Type %s, bootable %d\n", curr->gpt_part_info.type,
253 curr->gpt_part_info.bootable & PART_BOOTABLE);
254 #ifdef CONFIG_PARTITION_UUIDS
255 printf("UUID %s\n", curr->gpt_part_info.uuid);
262 * create the string that upstream 'gpt write' command will accept as an
265 * From doc/README.gpt, Format of partitions layout:
266 * "uuid_disk=...;name=u-boot,size=60MiB,uuid=...;
267 * name=kernel,size=60MiB,uuid=...;"
268 * The fields 'name' and 'size' are mandatory for every partition.
269 * The field 'start' is optional. The fields 'uuid' and 'uuid_disk'
270 * are optional if CONFIG_RANDOM_UUID is enabled.
272 static int create_gpt_partitions_list(int numparts, const char *guid,
273 char *partitions_list)
275 struct list_head *pos;
276 struct disk_part *curr;
277 char partstr[PART_NAME_LEN + 1];
279 if (!partitions_list)
282 strcpy(partitions_list, "uuid_disk=");
283 strncat(partitions_list, guid, UUID_STR_LEN + 1);
284 strcat(partitions_list, ";");
286 list_for_each(pos, &disk_partitions) {
287 curr = list_entry(pos, struct disk_part, list);
288 strcat(partitions_list, "name=");
289 strncat(partitions_list, (const char *)curr->gpt_part_info.name,
291 sprintf(partstr, ",start=0x%llx",
292 (unsigned long long)curr->gpt_part_info.start *
293 curr->gpt_part_info.blksz);
294 /* one extra byte for NULL */
295 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
296 sprintf(partstr, ",size=0x%llx",
297 (unsigned long long)curr->gpt_part_info.size *
298 curr->gpt_part_info.blksz);
299 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
301 strcat(partitions_list, ",uuid=");
302 strncat(partitions_list, curr->gpt_part_info.uuid,
304 strcat(partitions_list, ";");
310 * read partition info into disk_partitions list where
311 * it can be printed or modified
313 static int get_gpt_info(struct blk_desc *dev_desc)
315 /* start partition numbering at 1, as U-Boot does */
316 int valid_parts = 0, p, ret;
317 struct disk_partition info;
318 struct disk_part *new_disk_part;
321 * Always re-read partition info from device, in case
324 INIT_LIST_HEAD(&disk_partitions);
326 for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
327 ret = part_get_info(dev_desc, p, &info);
331 /* Add 1 here because counter is zero-based but p1 is
332 the first partition */
333 new_disk_part = allocate_disk_part(&info, valid_parts+1);
334 if (IS_ERR(new_disk_part))
337 list_add_tail(&new_disk_part->list, &disk_partitions);
340 if (valid_parts == 0) {
341 printf("** No valid partitions found **\n");
346 if (valid_parts >= 1)
351 /* a wrapper to test get_gpt_info */
352 static int do_get_gpt_info(struct blk_desc *dev_desc)
356 ret = get_gpt_info(dev_desc);
367 * set_gpt_info(): Fill partition information from string
368 * function allocates memory, remember to free!
370 * @param dev_desc - pointer block device descriptor
371 * @param str_part - pointer to string with partition information
372 * @param str_disk_guid - pointer to pointer to allocated string with disk guid
373 * @param partitions - pointer to pointer to allocated partitions array
374 * @param parts_count - number of partitions
376 * @return - zero on success, otherwise error
379 static int set_gpt_info(struct blk_desc *dev_desc,
380 const char *str_part,
381 char **str_disk_guid,
382 struct disk_partition **partitions,
389 struct disk_partition *parts;
391 uint64_t size_ll, start_ll;
393 int max_str_part = calc_parts_list_len(MAX_SEARCH_PARTITIONS);
395 debug("%s: lba num: 0x%x %d\n", __func__,
396 (unsigned int)dev_desc->lba, (unsigned int)dev_desc->lba);
398 if (str_part == NULL)
401 str = strdup(str_part);
405 /* extract disk guid */
407 val = extract_val(str, "uuid_disk");
409 #ifdef CONFIG_RANDOM_UUID
410 *str_disk_guid = malloc(UUID_STR_LEN + 1);
411 if (*str_disk_guid == NULL)
413 gen_rand_uuid_str(*str_disk_guid, UUID_STR_FORMAT_STD);
419 val = strsep(&val, ";");
420 if (extract_env(val, &p))
422 *str_disk_guid = strdup(p);
424 /* Move s to first partition */
428 printf("Error: is the partitions string NULL-terminated?\n");
431 if (strnlen(s, max_str_part) == 0)
434 i = strnlen(s, max_str_part) - 1;
438 /* calculate expected number of partitions */
446 /* allocate memory for partitions */
447 parts = calloc(sizeof(struct disk_partition), p_count);
451 /* retrieve partitions data from string */
452 for (i = 0; i < p_count; i++) {
453 tok = strsep(&s, ";");
459 val = extract_val(tok, "uuid");
461 /* 'uuid' is optional if random uuid's are enabled */
462 #ifdef CONFIG_RANDOM_UUID
463 gen_rand_uuid_str(parts[i].uuid, UUID_STR_FORMAT_STD);
469 if (extract_env(val, &p))
471 if (strnlen(p, max_str_part) >= sizeof(parts[i].uuid)) {
472 printf("Wrong uuid format for partition %d\n", i);
476 strncpy((char *)parts[i].uuid, p, max_str_part);
479 #ifdef CONFIG_PARTITION_TYPE_GUID
481 val = extract_val(tok, "type");
483 /* 'type' is optional */
484 if (extract_env(val, &p))
486 if (strnlen(p, max_str_part) >= sizeof(parts[i].type_guid)) {
487 printf("Wrong type guid format for partition %d\n",
492 strncpy((char *)parts[i].type_guid, p, max_str_part);
497 val = extract_val(tok, "name");
498 if (!val) { /* name is mandatory */
502 if (extract_env(val, &p))
504 if (strnlen(p, max_str_part) >= sizeof(parts[i].name)) {
508 strncpy((char *)parts[i].name, p, max_str_part);
512 val = extract_val(tok, "size");
513 if (!val) { /* 'size' is mandatory */
517 if (extract_env(val, &p))
519 if ((strcmp(p, "-") == 0)) {
520 /* Let part efi module to auto extend the size */
523 size_ll = ustrtoull(p, &p, 0);
524 parts[i].size = lldiv(size_ll, dev_desc->blksz);
530 val = extract_val(tok, "start");
531 if (val) { /* start address is optional */
532 if (extract_env(val, &p))
534 start_ll = ustrtoull(p, &p, 0);
535 parts[i].start = lldiv(start_ll, dev_desc->blksz);
539 offset += parts[i].size + parts[i].start;
542 if (found_key(tok, "bootable"))
543 parts[i].bootable = PART_BOOTABLE;
546 *parts_count = p_count;
553 free(*str_disk_guid);
559 static int gpt_default(struct blk_desc *blk_dev_desc, const char *str_part)
564 struct disk_partition *partitions = NULL;
566 /* fill partitions */
567 ret = set_gpt_info(blk_dev_desc, str_part,
568 &str_disk_guid, &partitions, &part_count);
571 printf("No partition list provided\n");
573 printf("Missing disk guid\n");
574 if ((ret == -3) || (ret == -4))
575 printf("Partition list incomplete\n");
579 /* save partitions layout to disk */
580 ret = gpt_restore(blk_dev_desc, str_disk_guid, partitions, part_count);
587 static int gpt_verify(struct blk_desc *blk_dev_desc, const char *str_part)
589 ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1,
590 blk_dev_desc->blksz);
591 struct disk_partition *partitions = NULL;
592 gpt_entry *gpt_pte = NULL;
597 /* fill partitions */
598 ret = set_gpt_info(blk_dev_desc, str_part,
599 &str_disk_guid, &partitions, &part_count);
602 printf("No partition list provided - only basic check\n");
603 ret = gpt_verify_headers(blk_dev_desc, gpt_head,
608 printf("Missing disk guid\n");
609 if ((ret == -3) || (ret == -4))
610 printf("Partition list incomplete\n");
614 /* Check partition layout with provided pattern */
615 ret = gpt_verify_partitions(blk_dev_desc, partitions, part_count,
624 static int do_disk_guid(struct blk_desc *dev_desc, char * const namestr)
627 char disk_guid[UUID_STR_LEN + 1];
629 ret = get_disk_guid(dev_desc, disk_guid);
631 return CMD_RET_FAILURE;
634 env_set(namestr, disk_guid);
636 printf("%s\n", disk_guid);
641 #ifdef CONFIG_CMD_GPT_RENAME
642 static int do_rename_gpt_parts(struct blk_desc *dev_desc, char *subcomm,
643 char *name1, char *name2)
645 struct list_head *pos;
646 struct disk_part *curr;
647 struct disk_partition *new_partitions = NULL;
648 char disk_guid[UUID_STR_LEN + 1];
649 char *partitions_list, *str_disk_guid = NULL;
651 int partlistlen, ret, numparts = 0, partnum, i = 1, ctr1 = 0, ctr2 = 0;
653 if ((subcomm == NULL) || (name1 == NULL) || (name2 == NULL) ||
654 (strcmp(subcomm, "swap") && (strcmp(subcomm, "rename"))))
657 ret = get_disk_guid(dev_desc, disk_guid);
661 * Allocates disk_partitions, requiring matching call to del_gpt_info()
664 numparts = get_gpt_info(dev_desc);
666 return numparts ? numparts : -ENODEV;
668 partlistlen = calc_parts_list_len(numparts);
669 partitions_list = malloc(partlistlen);
670 if (!partitions_list) {
674 memset(partitions_list, '\0', partlistlen);
676 ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
678 free(partitions_list);
682 * Uncomment the following line to print a string that 'gpt write'
683 * or 'gpt verify' will accept as input.
685 debug("OLD partitions_list is %s with %u chars\n", partitions_list,
686 (unsigned)strlen(partitions_list));
688 /* set_gpt_info allocates new_partitions and str_disk_guid */
689 ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
690 &new_partitions, &part_count);
694 if (!strcmp(subcomm, "swap")) {
695 if ((strlen(name1) > PART_NAME_LEN) || (strlen(name2) > PART_NAME_LEN)) {
696 printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
700 list_for_each(pos, &disk_partitions) {
701 curr = list_entry(pos, struct disk_part, list);
702 if (!strcmp((char *)curr->gpt_part_info.name, name1)) {
703 strcpy((char *)curr->gpt_part_info.name, name2);
705 } else if (!strcmp((char *)curr->gpt_part_info.name, name2)) {
706 strcpy((char *)curr->gpt_part_info.name, name1);
710 if ((ctr1 + ctr2 < 2) || (ctr1 != ctr2)) {
711 printf("Cannot swap partition names except in pairs.\n");
715 } else { /* rename */
716 if (strlen(name2) > PART_NAME_LEN) {
717 printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
721 partnum = (int)simple_strtol(name1, NULL, 10);
722 if ((partnum < 0) || (partnum > numparts)) {
723 printf("Illegal partition number %s\n", name1);
727 ret = part_get_info(dev_desc, partnum, new_partitions);
731 /* U-Boot partition numbering starts at 1 */
732 list_for_each(pos, &disk_partitions) {
733 curr = list_entry(pos, struct disk_part, list);
735 strcpy((char *)curr->gpt_part_info.name, name2);
742 ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
745 debug("NEW partitions_list is %s with %u chars\n", partitions_list,
746 (unsigned)strlen(partitions_list));
748 ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
749 &new_partitions, &part_count);
751 * Even though valid pointers are here passed into set_gpt_info(),
752 * it mallocs again, and there's no way to tell which failed.
757 debug("Writing new partition table\n");
758 ret = gpt_restore(dev_desc, disk_guid, new_partitions, numparts);
760 printf("Writing new partition table failed\n");
764 debug("Reading back new partition table\n");
766 * Empty the existing disk_partitions list, as otherwise the memory in
767 * the original list is unreachable.
770 numparts = get_gpt_info(dev_desc);
772 ret = numparts ? numparts : -ENODEV;
775 printf("new partition table with %d partitions is:\n", numparts);
779 #ifdef CONFIG_RANDOM_UUID
782 free(new_partitions);
783 free(partitions_list);
789 * do_gpt(): Perform GPT operations
791 * @param cmdtp - command name
796 * @return zero on success; otherwise error
798 static int do_gpt(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
800 int ret = CMD_RET_SUCCESS;
803 struct blk_desc *blk_dev_desc = NULL;
805 #ifndef CONFIG_CMD_GPT_RENAME
806 if (argc < 4 || argc > 5)
808 if (argc < 4 || argc > 6)
810 return CMD_RET_USAGE;
812 dev = (int)simple_strtoul(argv[3], &ep, 10);
813 if (!ep || ep[0] != '\0') {
814 printf("'%s' is not a number\n", argv[3]);
815 return CMD_RET_USAGE;
817 blk_dev_desc = blk_get_dev(argv[2], dev);
819 printf("%s: %s dev %d NOT available\n",
820 __func__, argv[2], dev);
821 return CMD_RET_FAILURE;
824 if ((strcmp(argv[1], "write") == 0) && (argc == 5)) {
825 printf("Writing GPT: ");
826 ret = gpt_default(blk_dev_desc, argv[4]);
827 } else if ((strcmp(argv[1], "verify") == 0)) {
828 ret = gpt_verify(blk_dev_desc, argv[4]);
829 printf("Verify GPT: ");
830 } else if (strcmp(argv[1], "guid") == 0) {
831 ret = do_disk_guid(blk_dev_desc, argv[4]);
832 #ifdef CONFIG_CMD_GPT_RENAME
833 } else if (strcmp(argv[1], "read") == 0) {
834 ret = do_get_gpt_info(blk_dev_desc);
835 } else if ((strcmp(argv[1], "swap") == 0) ||
836 (strcmp(argv[1], "rename") == 0)) {
837 ret = do_rename_gpt_parts(blk_dev_desc, argv[1], argv[4], argv[5]);
840 return CMD_RET_USAGE;
845 return CMD_RET_FAILURE;
848 printf("success!\n");
849 return CMD_RET_SUCCESS;
852 U_BOOT_CMD(gpt, CONFIG_SYS_MAXARGS, 1, do_gpt,
853 "GUID Partition Table",
854 "<command> <interface> <dev> <partitions_list>\n"
855 " - GUID partition table restoration and validity check\n"
856 " Restore or verify GPT information on a device connected\n"
859 " gpt write mmc 0 $partitions\n"
860 " gpt verify mmc 0 $partitions\n"
861 " gpt guid <interface> <dev>\n"
862 " - print disk GUID\n"
863 " gpt guid <interface> <dev> <varname>\n"
864 " - set environment variable to disk GUID\n"
867 " gpt guid mmc 0 varname\n"
868 #ifdef CONFIG_CMD_GPT_RENAME
869 "gpt partition renaming commands:\n"
870 " gpt read <interface> <dev>\n"
871 " - read GPT into a data structure for manipulation\n"
872 " gpt swap <interface> <dev> <name1> <name2>\n"
873 " - change all partitions named name1 to name2\n"
875 " gpt rename <interface> <dev> <part> <name>\n"
876 " - rename the specified partition\n"
878 " gpt swap mmc 0 foo bar\n"
879 " gpt rename mmc 0 3 foo\n"