common: Drop uuid.h from common header
[oweals/u-boot.git] / cmd / gpt.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * cmd_gpt.c -- GPT (GUID Partition Table) handling command
4  *
5  * Copyright (C) 2015
6  * Lukasz Majewski <l.majewski@majess.pl>
7  *
8  * Copyright (C) 2012 Samsung Electronics
9  * author: Lukasz Majewski <l.majewski@samsung.com>
10  * author: Piotr Wilczek <p.wilczek@samsung.com>
11  */
12
13 #include <common.h>
14 #include <env.h>
15 #include <malloc.h>
16 #include <command.h>
17 #include <part_efi.h>
18 #include <exports.h>
19 #include <uuid.h>
20 #include <linux/ctype.h>
21 #include <div64.h>
22 #include <memalign.h>
23 #include <linux/compat.h>
24 #include <linux/err.h>
25 #include <linux/sizes.h>
26 #include <stdlib.h>
27
28 static LIST_HEAD(disk_partitions);
29
30 /**
31  * extract_env(): Expand env name from string format '&{env_name}'
32  *                and return pointer to the env (if the env is set)
33  *
34  * @param str - pointer to string
35  * @param env - pointer to pointer to extracted env
36  *
37  * @return - zero on successful expand and env is set
38  */
39 static int extract_env(const char *str, char **env)
40 {
41         int ret = -1;
42         char *e, *s;
43 #ifdef CONFIG_RANDOM_UUID
44         char uuid_str[UUID_STR_LEN + 1];
45 #endif
46
47         if (!str || strlen(str) < 4)
48                 return -1;
49
50         if (!((strncmp(str, "${", 2) == 0) && (str[strlen(str) - 1] == '}')))
51                 return -1;
52
53         s = strdup(str);
54         if (s == NULL)
55                 return -1;
56
57         memset(s + strlen(s) - 1, '\0', 1);
58         memmove(s, s + 2, strlen(s) - 1);
59
60         e = env_get(s);
61         if (e == NULL) {
62 #ifdef CONFIG_RANDOM_UUID
63                 debug("%s unset. ", str);
64                 gen_rand_uuid_str(uuid_str, UUID_STR_FORMAT_GUID);
65                 env_set(s, uuid_str);
66
67                 e = env_get(s);
68                 if (e) {
69                         debug("Set to random.\n");
70                         ret = 0;
71                 } else {
72                         debug("Can't get random UUID.\n");
73                 }
74 #else
75                 debug("%s unset.\n", str);
76 #endif
77         } else {
78                 debug("%s get from environment.\n", str);
79                 ret = 0;
80         }
81
82         *env = e;
83         free(s);
84
85         return ret;
86 }
87
88 /**
89  * extract_val(): Extract value from a key=value pair list (comma separated).
90  *                Only value for the given key is returend.
91  *                Function allocates memory for the value, remember to free!
92  *
93  * @param str - pointer to string with key=values pairs
94  * @param key - pointer to the key to search for
95  *
96  * @return - pointer to allocated string with the value
97  */
98 static char *extract_val(const char *str, const char *key)
99 {
100         char *v, *k;
101         char *s, *strcopy;
102         char *new = NULL;
103
104         strcopy = strdup(str);
105         if (strcopy == NULL)
106                 return NULL;
107
108         s = strcopy;
109         while (s) {
110                 v = strsep(&s, ",");
111                 if (!v)
112                         break;
113                 k = strsep(&v, "=");
114                 if (!k)
115                         break;
116                 if  (strcmp(k, key) == 0) {
117                         new = strdup(v);
118                         break;
119                 }
120         }
121
122         free(strcopy);
123
124         return new;
125 }
126
127 /**
128  * found_key(): Found key without value in parameter list (comma separated).
129  *
130  * @param str - pointer to string with key
131  * @param key - pointer to the key to search for
132  *
133  * @return - true on found key
134  */
135 static bool found_key(const char *str, const char *key)
136 {
137         char *k;
138         char *s, *strcopy;
139         bool result = false;
140
141         strcopy = strdup(str);
142         if (!strcopy)
143                 return NULL;
144
145         s = strcopy;
146         while (s) {
147                 k = strsep(&s, ",");
148                 if (!k)
149                         break;
150                 if  (strcmp(k, key) == 0) {
151                         result = true;
152                         break;
153                 }
154         }
155
156         free(strcopy);
157
158         return result;
159 }
160
161 static int calc_parts_list_len(int numparts)
162 {
163         int partlistlen = UUID_STR_LEN + 1 + strlen("uuid_disk=");
164         /* for the comma */
165         partlistlen++;
166
167         /* per-partition additions; numparts starts at 1, so this should be correct */
168         partlistlen += numparts * (strlen("name=,") + PART_NAME_LEN + 1);
169         /* see part.h for definition of struct disk_partition */
170         partlistlen += numparts * (strlen("start=MiB,") + sizeof(lbaint_t) + 1);
171         partlistlen += numparts * (strlen("size=MiB,") + sizeof(lbaint_t) + 1);
172         partlistlen += numparts * (strlen("uuid=;") + UUID_STR_LEN + 1);
173         /* for the terminating null */
174         partlistlen++;
175         debug("Length of partitions_list is %d for %d partitions\n", partlistlen,
176               numparts);
177         return partlistlen;
178 }
179
180 #ifdef CONFIG_CMD_GPT_RENAME
181 static void del_gpt_info(void)
182 {
183         struct list_head *pos = &disk_partitions;
184         struct disk_part *curr;
185         while (!list_empty(pos)) {
186                 curr = list_entry(pos->next, struct disk_part, list);
187                 list_del(pos->next);
188                 free(curr);
189         }
190 }
191
192 static struct disk_part *allocate_disk_part(disk_partition_t *info, int partnum)
193 {
194         struct disk_part *newpart;
195         newpart = calloc(1, sizeof(struct disk_part));
196         if (!newpart)
197                 return ERR_PTR(-ENOMEM);
198
199         newpart->gpt_part_info.start = info->start;
200         newpart->gpt_part_info.size = info->size;
201         newpart->gpt_part_info.blksz = info->blksz;
202         strncpy((char *)newpart->gpt_part_info.name, (const char *)info->name,
203                 PART_NAME_LEN);
204         newpart->gpt_part_info.name[PART_NAME_LEN - 1] = '\0';
205         strncpy((char *)newpart->gpt_part_info.type, (const char *)info->type,
206                 PART_TYPE_LEN);
207         newpart->gpt_part_info.type[PART_TYPE_LEN - 1] = '\0';
208         newpart->gpt_part_info.bootable = info->bootable;
209 #ifdef CONFIG_PARTITION_UUIDS
210         strncpy(newpart->gpt_part_info.uuid, (const char *)info->uuid,
211                 UUID_STR_LEN);
212         /* UUID_STR_LEN is correct, as uuid[]'s length is UUID_STR_LEN+1 chars */
213         newpart->gpt_part_info.uuid[UUID_STR_LEN] = '\0';
214 #endif
215         newpart->partnum = partnum;
216
217         return newpart;
218 }
219
220 static void prettyprint_part_size(char *sizestr, lbaint_t partsize,
221                                   lbaint_t blksize)
222 {
223         unsigned long long partbytes, partmegabytes;
224
225         partbytes = partsize * blksize;
226         partmegabytes = lldiv(partbytes, SZ_1M);
227         snprintf(sizestr, 16, "%lluMiB", partmegabytes);
228 }
229
230 static void print_gpt_info(void)
231 {
232         struct list_head *pos;
233         struct disk_part *curr;
234         char partstartstr[16];
235         char partsizestr[16];
236
237         list_for_each(pos, &disk_partitions) {
238                 curr = list_entry(pos, struct disk_part, list);
239                 prettyprint_part_size(partstartstr, curr->gpt_part_info.start,
240                                       curr->gpt_part_info.blksz);
241                 prettyprint_part_size(partsizestr, curr->gpt_part_info.size,
242                                       curr->gpt_part_info.blksz);
243
244                 printf("Partition %d:\n", curr->partnum);
245                 printf("Start %s, size %s\n", partstartstr, partsizestr);
246                 printf("Block size %lu, name %s\n", curr->gpt_part_info.blksz,
247                        curr->gpt_part_info.name);
248                 printf("Type %s, bootable %d\n", curr->gpt_part_info.type,
249                        curr->gpt_part_info.bootable & PART_BOOTABLE);
250 #ifdef CONFIG_PARTITION_UUIDS
251                 printf("UUID %s\n", curr->gpt_part_info.uuid);
252 #endif
253                 printf("\n");
254         }
255 }
256
257 /*
258  * create the string that upstream 'gpt write' command will accept as an
259  * argument
260  *
261  * From doc/README.gpt, Format of partitions layout:
262  *    "uuid_disk=...;name=u-boot,size=60MiB,uuid=...;
263  *      name=kernel,size=60MiB,uuid=...;"
264  * The fields 'name' and 'size' are mandatory for every partition.
265  * The field 'start' is optional. The fields 'uuid' and 'uuid_disk'
266  * are optional if CONFIG_RANDOM_UUID is enabled.
267  */
268 static int create_gpt_partitions_list(int numparts, const char *guid,
269                                       char *partitions_list)
270 {
271         struct list_head *pos;
272         struct disk_part *curr;
273         char partstr[PART_NAME_LEN + 1];
274
275         if (!partitions_list)
276                 return -EINVAL;
277
278         strcpy(partitions_list, "uuid_disk=");
279         strncat(partitions_list, guid, UUID_STR_LEN + 1);
280         strcat(partitions_list, ";");
281
282         list_for_each(pos, &disk_partitions) {
283                 curr = list_entry(pos, struct disk_part, list);
284                 strcat(partitions_list, "name=");
285                 strncat(partitions_list, (const char *)curr->gpt_part_info.name,
286                         PART_NAME_LEN + 1);
287                 sprintf(partstr, ",start=0x%llx",
288                         (unsigned long long)curr->gpt_part_info.start *
289                                             curr->gpt_part_info.blksz);
290                 /* one extra byte for NULL */
291                 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
292                 sprintf(partstr, ",size=0x%llx",
293                         (unsigned long long)curr->gpt_part_info.size *
294                                             curr->gpt_part_info.blksz);
295                 strncat(partitions_list, partstr, PART_NAME_LEN + 1);
296
297                 strcat(partitions_list, ",uuid=");
298                 strncat(partitions_list, curr->gpt_part_info.uuid,
299                         UUID_STR_LEN + 1);
300                 strcat(partitions_list, ";");
301         }
302         return 0;
303 }
304
305 /*
306  * read partition info into disk_partitions list where
307  * it can be printed or modified
308  */
309 static int get_gpt_info(struct blk_desc *dev_desc)
310 {
311         /* start partition numbering at 1, as U-Boot does */
312         int valid_parts = 0, p, ret;
313         disk_partition_t info;
314         struct disk_part *new_disk_part;
315
316         /*
317          * Always re-read partition info from device, in case
318          * it has changed
319          */
320         INIT_LIST_HEAD(&disk_partitions);
321
322         for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
323                 ret = part_get_info(dev_desc, p, &info);
324                 if (ret)
325                         continue;
326
327                 /* Add 1 here because counter is zero-based but p1 is
328                    the first partition */
329                 new_disk_part = allocate_disk_part(&info, valid_parts+1);
330                 if (IS_ERR(new_disk_part))
331                         goto out;
332
333                 list_add_tail(&new_disk_part->list, &disk_partitions);
334                 valid_parts++;
335         }
336         if (valid_parts == 0) {
337                 printf("** No valid partitions found **\n");
338                 goto out;
339         }
340         return valid_parts;
341  out:
342         if (valid_parts >= 1)
343                 del_gpt_info();
344         return -ENODEV;
345 }
346
347 /* a wrapper to test get_gpt_info */
348 static int do_get_gpt_info(struct blk_desc *dev_desc)
349 {
350         int ret;
351
352         ret = get_gpt_info(dev_desc);
353         if (ret > 0) {
354                 print_gpt_info();
355                 del_gpt_info();
356                 return 0;
357         }
358         return ret;
359 }
360 #endif
361
362 /**
363  * set_gpt_info(): Fill partition information from string
364  *              function allocates memory, remember to free!
365  *
366  * @param dev_desc - pointer block device descriptor
367  * @param str_part - pointer to string with partition information
368  * @param str_disk_guid - pointer to pointer to allocated string with disk guid
369  * @param partitions - pointer to pointer to allocated partitions array
370  * @param parts_count - number of partitions
371  *
372  * @return - zero on success, otherwise error
373  *
374  */
375 static int set_gpt_info(struct blk_desc *dev_desc,
376                         const char *str_part,
377                         char **str_disk_guid,
378                         disk_partition_t **partitions,
379                         u8 *parts_count)
380 {
381         char *tok, *str, *s;
382         int i;
383         char *val, *p;
384         int p_count;
385         disk_partition_t *parts;
386         int errno = 0;
387         uint64_t size_ll, start_ll;
388         lbaint_t offset = 0;
389         int max_str_part = calc_parts_list_len(MAX_SEARCH_PARTITIONS);
390
391         debug("%s:  lba num: 0x%x %d\n", __func__,
392               (unsigned int)dev_desc->lba, (unsigned int)dev_desc->lba);
393
394         if (str_part == NULL)
395                 return -1;
396
397         str = strdup(str_part);
398         if (str == NULL)
399                 return -ENOMEM;
400
401         /* extract disk guid */
402         s = str;
403         val = extract_val(str, "uuid_disk");
404         if (!val) {
405 #ifdef CONFIG_RANDOM_UUID
406                 *str_disk_guid = malloc(UUID_STR_LEN + 1);
407                 if (*str_disk_guid == NULL)
408                         return -ENOMEM;
409                 gen_rand_uuid_str(*str_disk_guid, UUID_STR_FORMAT_STD);
410 #else
411                 free(str);
412                 return -2;
413 #endif
414         } else {
415                 val = strsep(&val, ";");
416                 if (extract_env(val, &p))
417                         p = val;
418                 *str_disk_guid = strdup(p);
419                 free(val);
420                 /* Move s to first partition */
421                 strsep(&s, ";");
422         }
423         if (s == NULL) {
424                 printf("Error: is the partitions string NULL-terminated?\n");
425                 return -EINVAL;
426         }
427         if (strnlen(s, max_str_part) == 0)
428                 return -3;
429
430         i = strnlen(s, max_str_part) - 1;
431         if (s[i] == ';')
432                 s[i] = '\0';
433
434         /* calculate expected number of partitions */
435         p_count = 1;
436         p = s;
437         while (*p) {
438                 if (*p++ == ';')
439                         p_count++;
440         }
441
442         /* allocate memory for partitions */
443         parts = calloc(sizeof(disk_partition_t), p_count);
444         if (parts == NULL)
445                 return -ENOMEM;
446
447         /* retrieve partitions data from string */
448         for (i = 0; i < p_count; i++) {
449                 tok = strsep(&s, ";");
450
451                 if (tok == NULL)
452                         break;
453
454                 /* uuid */
455                 val = extract_val(tok, "uuid");
456                 if (!val) {
457                         /* 'uuid' is optional if random uuid's are enabled */
458 #ifdef CONFIG_RANDOM_UUID
459                         gen_rand_uuid_str(parts[i].uuid, UUID_STR_FORMAT_STD);
460 #else
461                         errno = -4;
462                         goto err;
463 #endif
464                 } else {
465                         if (extract_env(val, &p))
466                                 p = val;
467                         if (strnlen(p, max_str_part) >= sizeof(parts[i].uuid)) {
468                                 printf("Wrong uuid format for partition %d\n", i);
469                                 errno = -4;
470                                 goto err;
471                         }
472                         strncpy((char *)parts[i].uuid, p, max_str_part);
473                         free(val);
474                 }
475 #ifdef CONFIG_PARTITION_TYPE_GUID
476                 /* guid */
477                 val = extract_val(tok, "type");
478                 if (val) {
479                         /* 'type' is optional */
480                         if (extract_env(val, &p))
481                                 p = val;
482                         if (strnlen(p, max_str_part) >= sizeof(parts[i].type_guid)) {
483                                 printf("Wrong type guid format for partition %d\n",
484                                        i);
485                                 errno = -4;
486                                 goto err;
487                         }
488                         strncpy((char *)parts[i].type_guid, p, max_str_part);
489                         free(val);
490                 }
491 #endif
492                 /* name */
493                 val = extract_val(tok, "name");
494                 if (!val) { /* name is mandatory */
495                         errno = -4;
496                         goto err;
497                 }
498                 if (extract_env(val, &p))
499                         p = val;
500                 if (strnlen(p, max_str_part) >= sizeof(parts[i].name)) {
501                         errno = -4;
502                         goto err;
503                 }
504                 strncpy((char *)parts[i].name, p, max_str_part);
505                 free(val);
506
507                 /* size */
508                 val = extract_val(tok, "size");
509                 if (!val) { /* 'size' is mandatory */
510                         errno = -4;
511                         goto err;
512                 }
513                 if (extract_env(val, &p))
514                         p = val;
515                 if ((strcmp(p, "-") == 0)) {
516                         /* Let part efi module to auto extend the size */
517                         parts[i].size = 0;
518                 } else {
519                         size_ll = ustrtoull(p, &p, 0);
520                         parts[i].size = lldiv(size_ll, dev_desc->blksz);
521                 }
522
523                 free(val);
524
525                 /* start address */
526                 val = extract_val(tok, "start");
527                 if (val) { /* start address is optional */
528                         if (extract_env(val, &p))
529                                 p = val;
530                         start_ll = ustrtoull(p, &p, 0);
531                         parts[i].start = lldiv(start_ll, dev_desc->blksz);
532                         free(val);
533                 }
534
535                 offset += parts[i].size + parts[i].start;
536
537                 /* bootable */
538                 if (found_key(tok, "bootable"))
539                         parts[i].bootable = PART_BOOTABLE;
540         }
541
542         *parts_count = p_count;
543         *partitions = parts;
544         free(str);
545
546         return 0;
547 err:
548         free(str);
549         free(*str_disk_guid);
550         free(parts);
551
552         return errno;
553 }
554
555 static int gpt_default(struct blk_desc *blk_dev_desc, const char *str_part)
556 {
557         int ret;
558         char *str_disk_guid;
559         u8 part_count = 0;
560         disk_partition_t *partitions = NULL;
561
562         /* fill partitions */
563         ret = set_gpt_info(blk_dev_desc, str_part,
564                         &str_disk_guid, &partitions, &part_count);
565         if (ret) {
566                 if (ret == -1)
567                         printf("No partition list provided\n");
568                 if (ret == -2)
569                         printf("Missing disk guid\n");
570                 if ((ret == -3) || (ret == -4))
571                         printf("Partition list incomplete\n");
572                 return -1;
573         }
574
575         /* save partitions layout to disk */
576         ret = gpt_restore(blk_dev_desc, str_disk_guid, partitions, part_count);
577         free(str_disk_guid);
578         free(partitions);
579
580         return ret;
581 }
582
583 static int gpt_verify(struct blk_desc *blk_dev_desc, const char *str_part)
584 {
585         ALLOC_CACHE_ALIGN_BUFFER_PAD(gpt_header, gpt_head, 1,
586                                      blk_dev_desc->blksz);
587         disk_partition_t *partitions = NULL;
588         gpt_entry *gpt_pte = NULL;
589         char *str_disk_guid;
590         u8 part_count = 0;
591         int ret = 0;
592
593         /* fill partitions */
594         ret = set_gpt_info(blk_dev_desc, str_part,
595                         &str_disk_guid, &partitions, &part_count);
596         if (ret) {
597                 if (ret == -1) {
598                         printf("No partition list provided - only basic check\n");
599                         ret = gpt_verify_headers(blk_dev_desc, gpt_head,
600                                                  &gpt_pte);
601                         goto out;
602                 }
603                 if (ret == -2)
604                         printf("Missing disk guid\n");
605                 if ((ret == -3) || (ret == -4))
606                         printf("Partition list incomplete\n");
607                 return -1;
608         }
609
610         /* Check partition layout with provided pattern */
611         ret = gpt_verify_partitions(blk_dev_desc, partitions, part_count,
612                                     gpt_head, &gpt_pte);
613         free(str_disk_guid);
614         free(partitions);
615  out:
616         free(gpt_pte);
617         return ret;
618 }
619
620 static int do_disk_guid(struct blk_desc *dev_desc, char * const namestr)
621 {
622         int ret;
623         char disk_guid[UUID_STR_LEN + 1];
624
625         ret = get_disk_guid(dev_desc, disk_guid);
626         if (ret < 0)
627                 return CMD_RET_FAILURE;
628
629         if (namestr)
630                 env_set(namestr, disk_guid);
631         else
632                 printf("%s\n", disk_guid);
633
634         return ret;
635 }
636
637 #ifdef CONFIG_CMD_GPT_RENAME
638 static int do_rename_gpt_parts(struct blk_desc *dev_desc, char *subcomm,
639                                char *name1, char *name2)
640 {
641         struct list_head *pos;
642         struct disk_part *curr;
643         disk_partition_t *new_partitions = NULL;
644         char disk_guid[UUID_STR_LEN + 1];
645         char *partitions_list, *str_disk_guid = NULL;
646         u8 part_count = 0;
647         int partlistlen, ret, numparts = 0, partnum, i = 1, ctr1 = 0, ctr2 = 0;
648
649         if ((subcomm == NULL) || (name1 == NULL) || (name2 == NULL) ||
650             (strcmp(subcomm, "swap") && (strcmp(subcomm, "rename"))))
651                 return -EINVAL;
652
653         ret = get_disk_guid(dev_desc, disk_guid);
654         if (ret < 0)
655                 return ret;
656         /*
657          * Allocates disk_partitions, requiring matching call to del_gpt_info()
658          * if successful.
659          */
660         numparts = get_gpt_info(dev_desc);
661         if (numparts <=  0)
662                 return numparts ? numparts : -ENODEV;
663
664         partlistlen = calc_parts_list_len(numparts);
665         partitions_list = malloc(partlistlen);
666         if (!partitions_list) {
667                 del_gpt_info();
668                 return -ENOMEM;
669         }
670         memset(partitions_list, '\0', partlistlen);
671
672         ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
673         if (ret < 0) {
674                 free(partitions_list);
675                 return ret;
676         }
677         /*
678          * Uncomment the following line to print a string that 'gpt write'
679          * or 'gpt verify' will accept as input.
680          */
681         debug("OLD partitions_list is %s with %u chars\n", partitions_list,
682               (unsigned)strlen(partitions_list));
683
684         /* set_gpt_info allocates new_partitions and str_disk_guid */
685         ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
686                            &new_partitions, &part_count);
687         if (ret < 0)
688                 goto out;
689
690         if (!strcmp(subcomm, "swap")) {
691                 if ((strlen(name1) > PART_NAME_LEN) || (strlen(name2) > PART_NAME_LEN)) {
692                         printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
693                         ret = -EINVAL;
694                         goto out;
695                 }
696                 list_for_each(pos, &disk_partitions) {
697                         curr = list_entry(pos, struct disk_part, list);
698                         if (!strcmp((char *)curr->gpt_part_info.name, name1)) {
699                                 strcpy((char *)curr->gpt_part_info.name, name2);
700                                 ctr1++;
701                         } else if (!strcmp((char *)curr->gpt_part_info.name, name2)) {
702                                 strcpy((char *)curr->gpt_part_info.name, name1);
703                                 ctr2++;
704                         }
705                 }
706                 if ((ctr1 + ctr2 < 2) || (ctr1 != ctr2)) {
707                         printf("Cannot swap partition names except in pairs.\n");
708                         ret = -EINVAL;
709                         goto out;
710                 }
711         } else { /* rename */
712                 if (strlen(name2) > PART_NAME_LEN) {
713                         printf("Names longer than %d characters are truncated.\n", PART_NAME_LEN);
714                         ret = -EINVAL;
715                         goto out;
716                 }
717                 partnum = (int)simple_strtol(name1, NULL, 10);
718                 if ((partnum < 0) || (partnum > numparts)) {
719                         printf("Illegal partition number %s\n", name1);
720                         ret = -EINVAL;
721                         goto out;
722                 }
723                 ret = part_get_info(dev_desc, partnum, new_partitions);
724                 if (ret < 0)
725                         goto out;
726
727                 /* U-Boot partition numbering starts at 1 */
728                 list_for_each(pos, &disk_partitions) {
729                         curr = list_entry(pos, struct disk_part, list);
730                         if (i == partnum) {
731                                 strcpy((char *)curr->gpt_part_info.name, name2);
732                                 break;
733                         }
734                         i++;
735                 }
736         }
737
738         ret = create_gpt_partitions_list(numparts, disk_guid, partitions_list);
739         if (ret < 0)
740                 goto out;
741         debug("NEW partitions_list is %s with %u chars\n", partitions_list,
742               (unsigned)strlen(partitions_list));
743
744         ret = set_gpt_info(dev_desc, partitions_list, &str_disk_guid,
745                            &new_partitions, &part_count);
746         /*
747          * Even though valid pointers are here passed into set_gpt_info(),
748          * it mallocs again, and there's no way to tell which failed.
749          */
750         if (ret < 0)
751                 goto out;
752
753         debug("Writing new partition table\n");
754         ret = gpt_restore(dev_desc, disk_guid, new_partitions, numparts);
755         if (ret < 0) {
756                 printf("Writing new partition table failed\n");
757                 goto out;
758         }
759
760         debug("Reading back new partition table\n");
761         /*
762          * Empty the existing disk_partitions list, as otherwise the memory in
763          * the original list is unreachable.
764          */
765         del_gpt_info();
766         numparts = get_gpt_info(dev_desc);
767         if (numparts <=  0) {
768                 ret = numparts ? numparts : -ENODEV;
769                 goto out;
770         }
771         printf("new partition table with %d partitions is:\n", numparts);
772         print_gpt_info();
773  out:
774         del_gpt_info();
775 #ifdef CONFIG_RANDOM_UUID
776         free(str_disk_guid);
777 #endif
778         free(new_partitions);
779         free(partitions_list);
780         return ret;
781 }
782 #endif
783
784 /**
785  * do_gpt(): Perform GPT operations
786  *
787  * @param cmdtp - command name
788  * @param flag
789  * @param argc
790  * @param argv
791  *
792  * @return zero on success; otherwise error
793  */
794 static int do_gpt(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
795 {
796         int ret = CMD_RET_SUCCESS;
797         int dev = 0;
798         char *ep;
799         struct blk_desc *blk_dev_desc = NULL;
800
801 #ifndef CONFIG_CMD_GPT_RENAME
802         if (argc < 4 || argc > 5)
803 #else
804         if (argc < 4 || argc > 6)
805 #endif
806                 return CMD_RET_USAGE;
807
808         dev = (int)simple_strtoul(argv[3], &ep, 10);
809         if (!ep || ep[0] != '\0') {
810                 printf("'%s' is not a number\n", argv[3]);
811                 return CMD_RET_USAGE;
812         }
813         blk_dev_desc = blk_get_dev(argv[2], dev);
814         if (!blk_dev_desc) {
815                 printf("%s: %s dev %d NOT available\n",
816                        __func__, argv[2], dev);
817                 return CMD_RET_FAILURE;
818         }
819
820         if ((strcmp(argv[1], "write") == 0) && (argc == 5)) {
821                 printf("Writing GPT: ");
822                 ret = gpt_default(blk_dev_desc, argv[4]);
823         } else if ((strcmp(argv[1], "verify") == 0)) {
824                 ret = gpt_verify(blk_dev_desc, argv[4]);
825                 printf("Verify GPT: ");
826         } else if (strcmp(argv[1], "guid") == 0) {
827                 ret = do_disk_guid(blk_dev_desc, argv[4]);
828 #ifdef CONFIG_CMD_GPT_RENAME
829         } else if (strcmp(argv[1], "read") == 0) {
830                 ret = do_get_gpt_info(blk_dev_desc);
831         } else if ((strcmp(argv[1], "swap") == 0) ||
832                    (strcmp(argv[1], "rename") == 0)) {
833                 ret = do_rename_gpt_parts(blk_dev_desc, argv[1], argv[4], argv[5]);
834 #endif
835         } else {
836                 return CMD_RET_USAGE;
837         }
838
839         if (ret) {
840                 printf("error!\n");
841                 return CMD_RET_FAILURE;
842         }
843
844         printf("success!\n");
845         return CMD_RET_SUCCESS;
846 }
847
848 U_BOOT_CMD(gpt, CONFIG_SYS_MAXARGS, 1, do_gpt,
849         "GUID Partition Table",
850         "<command> <interface> <dev> <partitions_list>\n"
851         " - GUID partition table restoration and validity check\n"
852         " Restore or verify GPT information on a device connected\n"
853         " to interface\n"
854         " Example usage:\n"
855         " gpt write mmc 0 $partitions\n"
856         " gpt verify mmc 0 $partitions\n"
857         " gpt guid <interface> <dev>\n"
858         "    - print disk GUID\n"
859         " gpt guid <interface> <dev> <varname>\n"
860         "    - set environment variable to disk GUID\n"
861         " Example usage:\n"
862         " gpt guid mmc 0\n"
863         " gpt guid mmc 0 varname\n"
864 #ifdef CONFIG_CMD_GPT_RENAME
865         "gpt partition renaming commands:\n"
866         " gpt read <interface> <dev>\n"
867         "    - read GPT into a data structure for manipulation\n"
868         " gpt swap <interface> <dev> <name1> <name2>\n"
869         "    - change all partitions named name1 to name2\n"
870         "      and vice-versa\n"
871         " gpt rename <interface> <dev> <part> <name>\n"
872         "    - rename the specified partition\n"
873         " Example usage:\n"
874         " gpt swap mmc 0 foo bar\n"
875         " gpt rename mmc 0 3 foo\n"
876 #endif
877 );