rockchip: Remove ARCH= references from documentation
[oweals/u-boot.git] / cmd / mtdparts.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2002
4  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5  *
6  * (C) Copyright 2002
7  * Robert Schwebel, Pengutronix, <r.schwebel@pengutronix.de>
8  *
9  * (C) Copyright 2003
10  * Kai-Uwe Bloem, Auerswald GmbH & Co KG, <linux-development@auerswald.de>
11  *
12  * (C) Copyright 2005
13  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
14  *
15  *   Added support for reading flash partition table from environment.
16  *   Parsing routines are based on driver/mtd/cmdline.c from the linux 2.4
17  *   kernel tree.
18  *
19  * (C) Copyright 2008
20  * Harald Welte, OpenMoko, Inc., Harald Welte <laforge@openmoko.org>
21  *
22  *   $Id: cmdlinepart.c,v 1.17 2004/11/26 11:18:47 lavinen Exp $
23  *   Copyright 2002 SYSGO Real-Time Solutions GmbH
24  */
25
26 /*
27  * Three environment variables are used by the parsing routines:
28  *
29  * 'partition' - keeps current partition identifier
30  *
31  * partition  := <part-id>
32  * <part-id>  := <dev-id>,part_num
33  *
34  *
35  * 'mtdids' - linux kernel mtd device id <-> u-boot device id mapping
36  *
37  * mtdids=<idmap>[,<idmap>,...]
38  *
39  * <idmap>    := <dev-id>=<mtd-id>
40  * <dev-id>   := 'nand'|'nor'|'onenand'|'spi-nand'<dev-num>
41  * <dev-num>  := mtd device number, 0...
42  * <mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)
43  *
44  *
45  * 'mtdparts' - partition list
46  *
47  * mtdparts=[mtdparts=]<mtd-def>[;<mtd-def>...]
48  *
49  * <mtd-def>  := <mtd-id>:<part-def>[,<part-def>...]
50  * <mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)
51  * <part-def> := <size>[@<offset>][<name>][<ro-flag>]
52  * <size>     := standard linux memsize OR '-' to denote all remaining space
53  * <offset>   := partition start offset within the device
54  * <name>     := '(' NAME ')'
55  * <ro-flag>  := when set to 'ro' makes partition read-only (not used, passed to kernel)
56  *
57  * Notes:
58  * - each <mtd-id> used in mtdparts must albo exist in 'mtddis' mapping
59  * - if the above variables are not set defaults for a given target are used
60  *
61  * Examples:
62  *
63  * 1 NOR Flash, with 1 single writable partition:
64  * mtdids=nor0=edb7312-nor
65  * mtdparts=[mtdparts=]edb7312-nor:-
66  *
67  * 1 NOR Flash with 2 partitions, 1 NAND with one
68  * mtdids=nor0=edb7312-nor,nand0=edb7312-nand
69  * mtdparts=[mtdparts=]edb7312-nor:256k(ARMboot)ro,-(root);edb7312-nand:-(home)
70  *
71  */
72
73 #include <common.h>
74 #include <command.h>
75 #include <env.h>
76 #include <log.h>
77 #include <malloc.h>
78 #include <jffs2/load_kernel.h>
79 #include <linux/list.h>
80 #include <linux/ctype.h>
81 #include <linux/err.h>
82 #include <linux/mtd/mtd.h>
83
84 #if defined(CONFIG_CMD_NAND)
85 #include <linux/mtd/rawnand.h>
86 #include <nand.h>
87 #endif
88
89 #if defined(CONFIG_CMD_ONENAND)
90 #include <linux/mtd/onenand.h>
91 #include <onenand_uboot.h>
92 #endif
93
94 DECLARE_GLOBAL_DATA_PTR;
95
96 /* special size referring to all the remaining space in a partition */
97 #define SIZE_REMAINING          (~0llu)
98
99 /* special offset value, it is used when not provided by user
100  *
101  * this value is used temporarily during parsing, later such offests
102  * are recalculated */
103 #define OFFSET_NOT_SPECIFIED    (~0llu)
104
105 /* minimum partition size */
106 #define MIN_PART_SIZE           4096
107
108 /* this flag needs to be set in part_info struct mask_flags
109  * field for read-only partitions */
110 #define MTD_WRITEABLE_CMD               1
111
112 /* default values for mtdids and mtdparts variables */
113 #if !defined(MTDIDS_DEFAULT)
114 #ifdef CONFIG_MTDIDS_DEFAULT
115 #define MTDIDS_DEFAULT CONFIG_MTDIDS_DEFAULT
116 #else
117 #define MTDIDS_DEFAULT NULL
118 #endif
119 #endif
120 #if !defined(MTDPARTS_DEFAULT)
121 #ifdef CONFIG_MTDPARTS_DEFAULT
122 #define MTDPARTS_DEFAULT CONFIG_MTDPARTS_DEFAULT
123 #else
124 #define MTDPARTS_DEFAULT NULL
125 #endif
126 #endif
127 #if defined(CONFIG_SYS_MTDPARTS_RUNTIME)
128 extern void board_mtdparts_default(const char **mtdids, const char **mtdparts);
129 #endif
130 static const char *mtdids_default = MTDIDS_DEFAULT;
131 static const char *mtdparts_default = MTDPARTS_DEFAULT;
132
133 /* copies of last seen 'mtdids', 'mtdparts' and 'partition' env variables */
134 #define MTDIDS_MAXLEN           128
135 #define MTDPARTS_MAXLEN         512
136 #define PARTITION_MAXLEN        16
137 static char last_ids[MTDIDS_MAXLEN + 1];
138 static char last_parts[MTDPARTS_MAXLEN + 1];
139 static char last_partition[PARTITION_MAXLEN + 1];
140
141 /* low level jffs2 cache cleaning routine */
142 extern void jffs2_free_cache(struct part_info *part);
143
144 /* mtdids mapping list, filled by parse_ids() */
145 static struct list_head mtdids;
146
147 /* device/partition list, parse_cmdline() parses into here */
148 static struct list_head devices;
149
150 /* current active device and partition number */
151 struct mtd_device *current_mtd_dev = NULL;
152 u8 current_mtd_partnum = 0;
153
154 u8 use_defaults;
155
156 static struct part_info* mtd_part_info(struct mtd_device *dev, unsigned int part_num);
157
158 /* command line only routines */
159 static struct mtdids* id_find_by_mtd_id(const char *mtd_id, unsigned int mtd_id_len);
160 static int device_del(struct mtd_device *dev);
161
162 /**
163  * Parses a string into a number.  The number stored at ptr is
164  * potentially suffixed with K (for kilobytes, or 1024 bytes),
165  * M (for megabytes, or 1048576 bytes), or G (for gigabytes, or
166  * 1073741824).  If the number is suffixed with K, M, or G, then
167  * the return value is the number multiplied by one kilobyte, one
168  * megabyte, or one gigabyte, respectively.
169  *
170  * @param ptr where parse begins
171  * @param retptr output pointer to next char after parse completes (output)
172  * @return resulting unsigned int
173  */
174 static u64 memsize_parse (const char *const ptr, const char **retptr)
175 {
176         u64 ret = simple_strtoull(ptr, (char **)retptr, 0);
177
178         switch (**retptr) {
179                 case 'G':
180                 case 'g':
181                         ret <<= 10;
182                         /* Fallthrough */
183                 case 'M':
184                 case 'm':
185                         ret <<= 10;
186                         /* Fallthrough */
187                 case 'K':
188                 case 'k':
189                         ret <<= 10;
190                         (*retptr)++;
191                         /* Fallthrough */
192                 default:
193                         break;
194         }
195
196         return ret;
197 }
198
199 /**
200  * Format string describing supplied size. This routine does the opposite job
201  * to memsize_parse(). Size in bytes is converted to string and if possible
202  * shortened by using k (kilobytes), m (megabytes) or g (gigabytes) suffix.
203  *
204  * Note, that this routine does not check for buffer overflow, it's the caller
205  * who must assure enough space.
206  *
207  * @param buf output buffer
208  * @param size size to be converted to string
209  */
210 static void memsize_format(char *buf, u64 size)
211 {
212 #define SIZE_GB ((u32)1024*1024*1024)
213 #define SIZE_MB ((u32)1024*1024)
214 #define SIZE_KB ((u32)1024)
215
216         if ((size % SIZE_GB) == 0)
217                 sprintf(buf, "%llug", size/SIZE_GB);
218         else if ((size % SIZE_MB) == 0)
219                 sprintf(buf, "%llum", size/SIZE_MB);
220         else if (size % SIZE_KB == 0)
221                 sprintf(buf, "%lluk", size/SIZE_KB);
222         else
223                 sprintf(buf, "%llu", size);
224 }
225
226 /**
227  * This routine does global indexing of all partitions. Resulting index for
228  * current partition is saved in 'mtddevnum'. Current partition name in
229  * 'mtddevname'.
230  */
231 static void index_partitions(void)
232 {
233         u16 mtddevnum;
234         struct part_info *part;
235         struct list_head *dentry;
236         struct mtd_device *dev;
237
238         debug("--- index partitions ---\n");
239
240         if (current_mtd_dev) {
241                 mtddevnum = 0;
242                 list_for_each(dentry, &devices) {
243                         dev = list_entry(dentry, struct mtd_device, link);
244                         if (dev == current_mtd_dev) {
245                                 mtddevnum += current_mtd_partnum;
246                                 env_set_ulong("mtddevnum", mtddevnum);
247                                 debug("=> mtddevnum %d,\n", mtddevnum);
248                                 break;
249                         }
250                         mtddevnum += dev->num_parts;
251                 }
252
253                 part = mtd_part_info(current_mtd_dev, current_mtd_partnum);
254                 if (part) {
255                         env_set("mtddevname", part->name);
256
257                         debug("=> mtddevname %s\n", part->name);
258                 } else {
259                         env_set("mtddevname", NULL);
260
261                         debug("=> mtddevname NULL\n");
262                 }
263         } else {
264                 env_set("mtddevnum", NULL);
265                 env_set("mtddevname", NULL);
266
267                 debug("=> mtddevnum NULL\n=> mtddevname NULL\n");
268         }
269 }
270
271 /**
272  * Save current device and partition in environment variable 'partition'.
273  */
274 static void current_save(void)
275 {
276         char buf[16];
277
278         debug("--- current_save ---\n");
279
280         if (current_mtd_dev) {
281                 sprintf(buf, "%s%d,%d", MTD_DEV_TYPE(current_mtd_dev->id->type),
282                                         current_mtd_dev->id->num, current_mtd_partnum);
283
284                 env_set("partition", buf);
285                 strncpy(last_partition, buf, 16);
286
287                 debug("=> partition %s\n", buf);
288         } else {
289                 env_set("partition", NULL);
290                 last_partition[0] = '\0';
291
292                 debug("=> partition NULL\n");
293         }
294         index_partitions();
295 }
296
297
298 /**
299  * Produce a mtd_info given a type and num.
300  *
301  * @param type mtd type
302  * @param num mtd number
303  * @param mtd a pointer to an mtd_info instance (output)
304  * @return 0 if device is valid, 1 otherwise
305  */
306 static int get_mtd_info(u8 type, u8 num, struct mtd_info **mtd)
307 {
308         char mtd_dev[16];
309
310         sprintf(mtd_dev, "%s%d", MTD_DEV_TYPE(type), num);
311         *mtd = get_mtd_device_nm(mtd_dev);
312         if (IS_ERR(*mtd)) {
313                 printf("Device %s not found!\n", mtd_dev);
314                 return 1;
315         }
316         put_mtd_device(*mtd);
317
318         return 0;
319 }
320
321 /**
322  * Performs sanity check for supplied flash partition.
323  * Table of existing MTD flash devices is searched and partition device
324  * is located. Alignment with the granularity of nand erasesize is verified.
325  *
326  * @param id of the parent device
327  * @param part partition to validate
328  * @return 0 if partition is valid, 1 otherwise
329  */
330 static int part_validate_eraseblock(struct mtdids *id, struct part_info *part)
331 {
332         struct mtd_info *mtd = NULL;
333         int i, j;
334         ulong start;
335         u64 offset, size;
336
337         if (get_mtd_info(id->type, id->num, &mtd))
338                 return 1;
339
340         part->sector_size = mtd->erasesize;
341
342         if (!mtd->numeraseregions) {
343                 /*
344                  * Only one eraseregion (NAND, SPI-NAND, OneNAND or uniform NOR),
345                  * checking for alignment is easy here
346                  */
347                 offset = part->offset;
348                 if (do_div(offset, mtd->erasesize)) {
349                         printf("%s%d: partition (%s) start offset"
350                                "alignment incorrect\n",
351                                MTD_DEV_TYPE(id->type), id->num, part->name);
352                         return 1;
353                 }
354
355                 size = part->size;
356                 if (do_div(size, mtd->erasesize)) {
357                         printf("%s%d: partition (%s) size alignment incorrect\n",
358                                MTD_DEV_TYPE(id->type), id->num, part->name);
359                         return 1;
360                 }
361         } else {
362                 /*
363                  * Multiple eraseregions (non-uniform NOR),
364                  * checking for alignment is more complex here
365                  */
366
367                 /* Check start alignment */
368                 for (i = 0; i < mtd->numeraseregions; i++) {
369                         start = mtd->eraseregions[i].offset;
370                         for (j = 0; j < mtd->eraseregions[i].numblocks; j++) {
371                                 if (part->offset == start)
372                                         goto start_ok;
373                                 start += mtd->eraseregions[i].erasesize;
374                         }
375                 }
376
377                 printf("%s%d: partition (%s) start offset alignment incorrect\n",
378                        MTD_DEV_TYPE(id->type), id->num, part->name);
379                 return 1;
380
381         start_ok:
382
383                 /* Check end/size alignment */
384                 for (i = 0; i < mtd->numeraseregions; i++) {
385                         start = mtd->eraseregions[i].offset;
386                         for (j = 0; j < mtd->eraseregions[i].numblocks; j++) {
387                                 if ((part->offset + part->size) == start)
388                                         goto end_ok;
389                                 start += mtd->eraseregions[i].erasesize;
390                         }
391                 }
392                 /* Check last sector alignment */
393                 if ((part->offset + part->size) == start)
394                         goto end_ok;
395
396                 printf("%s%d: partition (%s) size alignment incorrect\n",
397                        MTD_DEV_TYPE(id->type), id->num, part->name);
398                 return 1;
399
400         end_ok:
401                 return 0;
402         }
403
404         return 0;
405 }
406
407
408 /**
409  * Performs sanity check for supplied partition. Offset and size are
410  * verified to be within valid range. Partition type is checked and
411  * part_validate_eraseblock() is called with the argument of part.
412  *
413  * @param id of the parent device
414  * @param part partition to validate
415  * @return 0 if partition is valid, 1 otherwise
416  */
417 static int part_validate(struct mtdids *id, struct part_info *part)
418 {
419         if (part->size == SIZE_REMAINING)
420                 part->size = id->size - part->offset;
421
422         if (part->offset > id->size) {
423                 printf("%s: offset %08llx beyond flash size %08llx\n",
424                                 id->mtd_id, part->offset, id->size);
425                 return 1;
426         }
427
428         if ((part->offset + part->size) <= part->offset) {
429                 printf("%s%d: partition (%s) size too big\n",
430                                 MTD_DEV_TYPE(id->type), id->num, part->name);
431                 return 1;
432         }
433
434         if (part->offset + part->size > id->size) {
435                 printf("%s: partitioning exceeds flash size\n", id->mtd_id);
436                 return 1;
437         }
438
439         /*
440          * Now we need to check if the partition starts and ends on
441          * sector (eraseblock) regions
442          */
443         return part_validate_eraseblock(id, part);
444 }
445
446 /**
447  * Delete selected partition from the partition list of the specified device.
448  *
449  * @param dev device to delete partition from
450  * @param part partition to delete
451  * @return 0 on success, 1 otherwise
452  */
453 static int part_del(struct mtd_device *dev, struct part_info *part)
454 {
455         u8 current_save_needed = 0;
456
457         /* if there is only one partition, remove whole device */
458         if (dev->num_parts == 1)
459                 return device_del(dev);
460
461         /* otherwise just delete this partition */
462
463         if (dev == current_mtd_dev) {
464                 /* we are modyfing partitions for the current device,
465                  * update current */
466                 struct part_info *curr_pi;
467                 curr_pi = mtd_part_info(current_mtd_dev, current_mtd_partnum);
468
469                 if (curr_pi) {
470                         if (curr_pi == part) {
471                                 printf("current partition deleted, resetting current to 0\n");
472                                 current_mtd_partnum = 0;
473                         } else if (part->offset <= curr_pi->offset) {
474                                 current_mtd_partnum--;
475                         }
476                         current_save_needed = 1;
477                 }
478         }
479
480         list_del(&part->link);
481         free(part);
482         dev->num_parts--;
483
484         if (current_save_needed > 0)
485                 current_save();
486         else
487                 index_partitions();
488
489         return 0;
490 }
491
492 /**
493  * Delete all partitions from parts head list, free memory.
494  *
495  * @param head list of partitions to delete
496  */
497 static void part_delall(struct list_head *head)
498 {
499         struct list_head *entry, *n;
500         struct part_info *part_tmp;
501
502         /* clean tmp_list and free allocated memory */
503         list_for_each_safe(entry, n, head) {
504                 part_tmp = list_entry(entry, struct part_info, link);
505
506                 list_del(entry);
507                 free(part_tmp);
508         }
509 }
510
511 /**
512  * Add new partition to the supplied partition list. Make sure partitions are
513  * sorted by offset in ascending order.
514  *
515  * @param head list this partition is to be added to
516  * @param new partition to be added
517  */
518 static int part_sort_add(struct mtd_device *dev, struct part_info *part)
519 {
520         struct list_head *entry;
521         struct part_info *new_pi, *curr_pi;
522
523         /* link partition to parrent dev */
524         part->dev = dev;
525
526         if (list_empty(&dev->parts)) {
527                 debug("part_sort_add: list empty\n");
528                 list_add(&part->link, &dev->parts);
529                 dev->num_parts++;
530                 index_partitions();
531                 return 0;
532         }
533
534         new_pi = list_entry(&part->link, struct part_info, link);
535
536         /* get current partition info if we are updating current device */
537         curr_pi = NULL;
538         if (dev == current_mtd_dev)
539                 curr_pi = mtd_part_info(current_mtd_dev, current_mtd_partnum);
540
541         list_for_each(entry, &dev->parts) {
542                 struct part_info *pi;
543
544                 pi = list_entry(entry, struct part_info, link);
545
546                 /* be compliant with kernel cmdline, allow only one partition at offset zero */
547                 if ((new_pi->offset == pi->offset) && (pi->offset == 0)) {
548                         printf("cannot add second partition at offset 0\n");
549                         return 1;
550                 }
551
552                 if (new_pi->offset <= pi->offset) {
553                         list_add_tail(&part->link, entry);
554                         dev->num_parts++;
555
556                         if (curr_pi && (pi->offset <= curr_pi->offset)) {
557                                 /* we are modyfing partitions for the current
558                                  * device, update current */
559                                 current_mtd_partnum++;
560                                 current_save();
561                         } else {
562                                 index_partitions();
563                         }
564                         return 0;
565                 }
566         }
567
568         list_add_tail(&part->link, &dev->parts);
569         dev->num_parts++;
570         index_partitions();
571         return 0;
572 }
573
574 /**
575  * Add provided partition to the partition list of a given device.
576  *
577  * @param dev device to which partition is added
578  * @param part partition to be added
579  * @return 0 on success, 1 otherwise
580  */
581 static int part_add(struct mtd_device *dev, struct part_info *part)
582 {
583         /* verify alignment and size */
584         if (part_validate(dev->id, part) != 0)
585                 return 1;
586
587         /* partition is ok, add it to the list */
588         if (part_sort_add(dev, part) != 0)
589                 return 1;
590
591         return 0;
592 }
593
594 /**
595  * Parse one partition definition, allocate memory and return pointer to this
596  * location in retpart.
597  *
598  * @param partdef pointer to the partition definition string i.e. <part-def>
599  * @param ret output pointer to next char after parse completes (output)
600  * @param retpart pointer to the allocated partition (output)
601  * @return 0 on success, 1 otherwise
602  */
603 static int part_parse(const char *const partdef, const char **ret, struct part_info **retpart)
604 {
605         struct part_info *part;
606         u64 size;
607         u64 offset;
608         const char *name;
609         int name_len;
610         unsigned int mask_flags;
611         const char *p;
612
613         p = partdef;
614         *retpart = NULL;
615         *ret = NULL;
616
617         /* fetch the partition size */
618         if (*p == '-') {
619                 /* assign all remaining space to this partition */
620                 debug("'-': remaining size assigned\n");
621                 size = SIZE_REMAINING;
622                 p++;
623         } else {
624                 size = memsize_parse(p, &p);
625                 if (size < MIN_PART_SIZE) {
626                         printf("partition size too small (%llx)\n", size);
627                         return 1;
628                 }
629         }
630
631         /* check for offset */
632         offset = OFFSET_NOT_SPECIFIED;
633         if (*p == '@') {
634                 p++;
635                 offset = memsize_parse(p, &p);
636         }
637
638         /* now look for the name */
639         if (*p == '(') {
640                 name = ++p;
641                 if ((p = strchr(name, ')')) == NULL) {
642                         printf("no closing ) found in partition name\n");
643                         return 1;
644                 }
645                 name_len = p - name + 1;
646                 if ((name_len - 1) == 0) {
647                         printf("empty partition name\n");
648                         return 1;
649                 }
650                 p++;
651         } else {
652                 /* 0x00000000@0x00000000 */
653                 name_len = 22;
654                 name = NULL;
655         }
656
657         /* test for options */
658         mask_flags = 0;
659         if (strncmp(p, "ro", 2) == 0) {
660                 mask_flags |= MTD_WRITEABLE_CMD;
661                 p += 2;
662         }
663
664         /* check for next partition definition */
665         if (*p == ',') {
666                 if (size == SIZE_REMAINING) {
667                         *ret = NULL;
668                         printf("no partitions allowed after a fill-up partition\n");
669                         return 1;
670                 }
671                 *ret = ++p;
672         } else if ((*p == ';') || (*p == '\0')) {
673                 *ret = p;
674         } else {
675                 printf("unexpected character '%c' at the end of partition\n", *p);
676                 *ret = NULL;
677                 return 1;
678         }
679
680         /*  allocate memory */
681         part = (struct part_info *)malloc(sizeof(struct part_info) + name_len);
682         if (!part) {
683                 printf("out of memory\n");
684                 return 1;
685         }
686         memset(part, 0, sizeof(struct part_info) + name_len);
687         part->size = size;
688         part->offset = offset;
689         part->mask_flags = mask_flags;
690         part->name = (char *)(part + 1);
691
692         if (name) {
693                 /* copy user provided name */
694                 strncpy(part->name, name, name_len - 1);
695                 part->auto_name = 0;
696         } else {
697                 /* auto generated name in form of size@offset */
698                 snprintf(part->name, name_len, "0x%08llx@0x%08llx", size, offset);
699                 part->auto_name = 1;
700         }
701
702         part->name[name_len - 1] = '\0';
703         INIT_LIST_HEAD(&part->link);
704
705         debug("+ partition: name %-22s size 0x%08llx offset 0x%08llx mask flags %d\n",
706                         part->name, part->size,
707                         part->offset, part->mask_flags);
708
709         *retpart = part;
710         return 0;
711 }
712
713 /**
714  * Check device number to be within valid range for given device type.
715  *
716  * @param type mtd type
717  * @param num mtd number
718  * @param size a pointer to the size of the mtd device (output)
719  * @return 0 if device is valid, 1 otherwise
720  */
721 static int mtd_device_validate(u8 type, u8 num, u64 *size)
722 {
723         struct mtd_info *mtd = NULL;
724
725         if (get_mtd_info(type, num, &mtd))
726                 return 1;
727
728         *size = mtd->size;
729
730         return 0;
731 }
732
733 /**
734  * Delete all mtd devices from a supplied devices list, free memory allocated for
735  * each device and delete all device partitions.
736  *
737  * @return 0 on success, 1 otherwise
738  */
739 static int device_delall(struct list_head *head)
740 {
741         struct list_head *entry, *n;
742         struct mtd_device *dev_tmp;
743
744         /* clean devices list */
745         list_for_each_safe(entry, n, head) {
746                 dev_tmp = list_entry(entry, struct mtd_device, link);
747                 list_del(entry);
748                 part_delall(&dev_tmp->parts);
749                 free(dev_tmp);
750         }
751         INIT_LIST_HEAD(&devices);
752
753         return 0;
754 }
755
756 /**
757  * If provided device exists it's partitions are deleted, device is removed
758  * from device list and device memory is freed.
759  *
760  * @param dev device to be deleted
761  * @return 0 on success, 1 otherwise
762  */
763 static int device_del(struct mtd_device *dev)
764 {
765         part_delall(&dev->parts);
766         list_del(&dev->link);
767         free(dev);
768
769         if (dev == current_mtd_dev) {
770                 /* we just deleted current device */
771                 if (list_empty(&devices)) {
772                         current_mtd_dev = NULL;
773                 } else {
774                         /* reset first partition from first dev from the
775                          * devices list as current */
776                         current_mtd_dev = list_entry(devices.next, struct mtd_device, link);
777                         current_mtd_partnum = 0;
778                 }
779                 current_save();
780                 return 0;
781         }
782
783         index_partitions();
784         return 0;
785 }
786
787 /**
788  * Search global device list and return pointer to the device of type and num
789  * specified.
790  *
791  * @param type device type
792  * @param num device number
793  * @return NULL if requested device does not exist
794  */
795 struct mtd_device *device_find(u8 type, u8 num)
796 {
797         struct list_head *entry;
798         struct mtd_device *dev_tmp;
799
800         list_for_each(entry, &devices) {
801                 dev_tmp = list_entry(entry, struct mtd_device, link);
802
803                 if ((dev_tmp->id->type == type) && (dev_tmp->id->num == num))
804                         return dev_tmp;
805         }
806
807         return NULL;
808 }
809
810 /**
811  * Add specified device to the global device list.
812  *
813  * @param dev device to be added
814  */
815 static void device_add(struct mtd_device *dev)
816 {
817         u8 current_save_needed = 0;
818
819         if (list_empty(&devices)) {
820                 current_mtd_dev = dev;
821                 current_mtd_partnum = 0;
822                 current_save_needed = 1;
823         }
824
825         list_add_tail(&dev->link, &devices);
826
827         if (current_save_needed > 0)
828                 current_save();
829         else
830                 index_partitions();
831 }
832
833 /**
834  * Parse device type, name and mtd-id. If syntax is ok allocate memory and
835  * return pointer to the device structure.
836  *
837  * @param mtd_dev pointer to the device definition string i.e. <mtd-dev>
838  * @param ret output pointer to next char after parse completes (output)
839  * @param retdev pointer to the allocated device (output)
840  * @return 0 on success, 1 otherwise
841  */
842 static int device_parse(const char *const mtd_dev, const char **ret, struct mtd_device **retdev)
843 {
844         struct mtd_device *dev;
845         struct part_info *part;
846         struct mtdids *id;
847         const char *mtd_id;
848         unsigned int mtd_id_len;
849         const char *p;
850         const char *pend;
851         LIST_HEAD(tmp_list);
852         struct list_head *entry, *n;
853         u16 num_parts;
854         u64 offset;
855         int err = 1;
856
857         debug("===device_parse===\n");
858
859         assert(retdev);
860         *retdev = NULL;
861
862         if (ret)
863                 *ret = NULL;
864
865         /* fetch <mtd-id> */
866         mtd_id = p = mtd_dev;
867         if (!(p = strchr(mtd_id, ':'))) {
868                 printf("no <mtd-id> identifier\n");
869                 return 1;
870         }
871         mtd_id_len = p - mtd_id + 1;
872         p++;
873
874         /* verify if we have a valid device specified */
875         if ((id = id_find_by_mtd_id(mtd_id, mtd_id_len - 1)) == NULL) {
876                 printf("invalid mtd device '%.*s'\n", mtd_id_len - 1, mtd_id);
877                 return 1;
878         }
879
880         pend = strchr(p, ';');
881         debug("dev type = %d (%s), dev num = %d, mtd-id = %s\n",
882                         id->type, MTD_DEV_TYPE(id->type),
883                         id->num, id->mtd_id);
884         debug("parsing partitions %.*s\n", (int)(pend ? pend - p : strlen(p)), p);
885
886         /* parse partitions */
887         num_parts = 0;
888
889         offset = 0;
890         if ((dev = device_find(id->type, id->num)) != NULL) {
891                 /* if device already exists start at the end of the last partition */
892                 part = list_entry(dev->parts.prev, struct part_info, link);
893                 offset = part->offset + part->size;
894         }
895
896         while (p && (*p != '\0') && (*p != ';')) {
897                 err = 1;
898                 if ((part_parse(p, &p, &part) != 0) || (!part))
899                         break;
900
901                 /* calculate offset when not specified */
902                 if (part->offset == OFFSET_NOT_SPECIFIED)
903                         part->offset = offset;
904                 else
905                         offset = part->offset;
906
907                 /* verify alignment and size */
908                 if (part_validate(id, part) != 0)
909                         break;
910
911                 offset += part->size;
912
913                 /* partition is ok, add it to the list */
914                 list_add_tail(&part->link, &tmp_list);
915                 num_parts++;
916                 err = 0;
917         }
918         if (err == 1) {
919                 part_delall(&tmp_list);
920                 return 1;
921         }
922
923         debug("\ntotal partitions: %d\n", num_parts);
924
925         /* check for next device presence */
926         if (p) {
927                 if (*p == ';') {
928                         if (ret)
929                                 *ret = ++p;
930                 } else if (*p == '\0') {
931                         if (ret)
932                                 *ret = p;
933                 } else {
934                         printf("unexpected character '%c' at the end of device\n", *p);
935                         if (ret)
936                                 *ret = NULL;
937                         return 1;
938                 }
939         }
940
941         /* allocate memory for mtd_device structure */
942         if ((dev = (struct mtd_device *)malloc(sizeof(struct mtd_device))) == NULL) {
943                 printf("out of memory\n");
944                 return 1;
945         }
946         memset(dev, 0, sizeof(struct mtd_device));
947         dev->id = id;
948         dev->num_parts = 0; /* part_sort_add increments num_parts */
949         INIT_LIST_HEAD(&dev->parts);
950         INIT_LIST_HEAD(&dev->link);
951
952         /* move partitions from tmp_list to dev->parts */
953         list_for_each_safe(entry, n, &tmp_list) {
954                 part = list_entry(entry, struct part_info, link);
955                 list_del(entry);
956                 if (part_sort_add(dev, part) != 0) {
957                         device_del(dev);
958                         return 1;
959                 }
960         }
961
962         *retdev = dev;
963
964         debug("===\n\n");
965         return 0;
966 }
967
968 /**
969  * Initialize global device list.
970  *
971  * @return 0 on success, 1 otherwise
972  */
973 static int mtd_devices_init(void)
974 {
975         last_parts[0] = '\0';
976         current_mtd_dev = NULL;
977         current_save();
978
979         return device_delall(&devices);
980 }
981
982 /*
983  * Search global mtdids list and find id of requested type and number.
984  *
985  * @return pointer to the id if it exists, NULL otherwise
986  */
987 static struct mtdids* id_find(u8 type, u8 num)
988 {
989         struct list_head *entry;
990         struct mtdids *id;
991
992         list_for_each(entry, &mtdids) {
993                 id = list_entry(entry, struct mtdids, link);
994
995                 if ((id->type == type) && (id->num == num))
996                         return id;
997         }
998
999         return NULL;
1000 }
1001
1002 /**
1003  * Search global mtdids list and find id of a requested mtd_id.
1004  *
1005  * Note: first argument is not null terminated.
1006  *
1007  * @param mtd_id string containing requested mtd_id
1008  * @param mtd_id_len length of supplied mtd_id
1009  * @return pointer to the id if it exists, NULL otherwise
1010  */
1011 static struct mtdids* id_find_by_mtd_id(const char *mtd_id, unsigned int mtd_id_len)
1012 {
1013         struct list_head *entry;
1014         struct mtdids *id;
1015
1016         debug("--- id_find_by_mtd_id: '%.*s' (len = %d)\n",
1017                         mtd_id_len, mtd_id, mtd_id_len);
1018
1019         list_for_each(entry, &mtdids) {
1020                 id = list_entry(entry, struct mtdids, link);
1021
1022                 debug("entry: '%s' (len = %zu)\n",
1023                                 id->mtd_id, strlen(id->mtd_id));
1024
1025                 if (mtd_id_len != strlen(id->mtd_id))
1026                         continue;
1027                 if (strncmp(id->mtd_id, mtd_id, mtd_id_len) == 0)
1028                         return id;
1029         }
1030
1031         return NULL;
1032 }
1033
1034 /**
1035  * Parse device id string <dev-id> := 'nand'|'nor'|'onenand'|'spi-nand'<dev-num>,
1036  * return device type and number.
1037  *
1038  * @param id string describing device id
1039  * @param ret_id output pointer to next char after parse completes (output)
1040  * @param dev_type parsed device type (output)
1041  * @param dev_num parsed device number (output)
1042  * @return 0 on success, 1 otherwise
1043  */
1044 int mtd_id_parse(const char *id, const char **ret_id, u8 *dev_type,
1045                  u8 *dev_num)
1046 {
1047         const char *p = id;
1048
1049         *dev_type = 0;
1050         if (strncmp(p, "nand", 4) == 0) {
1051                 *dev_type = MTD_DEV_TYPE_NAND;
1052                 p += 4;
1053         } else if (strncmp(p, "nor", 3) == 0) {
1054                 *dev_type = MTD_DEV_TYPE_NOR;
1055                 p += 3;
1056         } else if (strncmp(p, "onenand", 7) == 0) {
1057                 *dev_type = MTD_DEV_TYPE_ONENAND;
1058                 p += 7;
1059         } else if (strncmp(p, "spi-nand", 8) == 0) {
1060                 *dev_type = MTD_DEV_TYPE_SPINAND;
1061                 p += 8;
1062         } else {
1063                 printf("incorrect device type in %s\n", id);
1064                 return 1;
1065         }
1066
1067         if (!isdigit(*p)) {
1068                 printf("incorrect device number in %s\n", id);
1069                 return 1;
1070         }
1071
1072         *dev_num = simple_strtoul(p, (char **)&p, 0);
1073         if (ret_id)
1074                 *ret_id = p;
1075         return 0;
1076 }
1077
1078 /**
1079  * Process all devices and generate corresponding mtdparts string describing
1080  * all partitions on all devices.
1081  *
1082  * @param buf output buffer holding generated mtdparts string (output)
1083  * @param buflen buffer size
1084  * @return 0 on success, 1 otherwise
1085  */
1086 static int generate_mtdparts(char *buf, u32 buflen)
1087 {
1088         struct list_head *pentry, *dentry;
1089         struct mtd_device *dev;
1090         struct part_info *part, *prev_part;
1091         char *p = buf;
1092         char tmpbuf[32];
1093         u64 size, offset;
1094         u32 len, part_cnt;
1095         u32 maxlen = buflen - 1;
1096
1097         debug("--- generate_mtdparts ---\n");
1098
1099         if (list_empty(&devices)) {
1100                 buf[0] = '\0';
1101                 return 0;
1102         }
1103
1104         list_for_each(dentry, &devices) {
1105                 dev = list_entry(dentry, struct mtd_device, link);
1106
1107                 /* copy mtd_id */
1108                 len = strlen(dev->id->mtd_id) + 1;
1109                 if (len > maxlen)
1110                         goto cleanup;
1111                 memcpy(p, dev->id->mtd_id, len - 1);
1112                 p += len - 1;
1113                 *(p++) = ':';
1114                 maxlen -= len;
1115
1116                 /* format partitions */
1117                 prev_part = NULL;
1118                 part_cnt = 0;
1119                 list_for_each(pentry, &dev->parts) {
1120                         part = list_entry(pentry, struct part_info, link);
1121                         size = part->size;
1122                         offset = part->offset;
1123                         part_cnt++;
1124
1125                         /* partition size */
1126                         memsize_format(tmpbuf, size);
1127                         len = strlen(tmpbuf);
1128                         if (len > maxlen)
1129                                 goto cleanup;
1130                         memcpy(p, tmpbuf, len);
1131                         p += len;
1132                         maxlen -= len;
1133
1134
1135                         /* add offset only when there is a gap between
1136                          * partitions */
1137                         if ((!prev_part && (offset != 0)) ||
1138                                         (prev_part && ((prev_part->offset + prev_part->size) != part->offset))) {
1139
1140                                 memsize_format(tmpbuf, offset);
1141                                 len = strlen(tmpbuf) + 1;
1142                                 if (len > maxlen)
1143                                         goto cleanup;
1144                                 *(p++) = '@';
1145                                 memcpy(p, tmpbuf, len - 1);
1146                                 p += len - 1;
1147                                 maxlen -= len;
1148                         }
1149
1150                         /* copy name only if user supplied */
1151                         if(!part->auto_name) {
1152                                 len = strlen(part->name) + 2;
1153                                 if (len > maxlen)
1154                                         goto cleanup;
1155
1156                                 *(p++) = '(';
1157                                 memcpy(p, part->name, len - 2);
1158                                 p += len - 2;
1159                                 *(p++) = ')';
1160                                 maxlen -= len;
1161                         }
1162
1163                         /* ro mask flag */
1164                         if (part->mask_flags && MTD_WRITEABLE_CMD) {
1165                                 len = 2;
1166                                 if (len > maxlen)
1167                                         goto cleanup;
1168                                 *(p++) = 'r';
1169                                 *(p++) = 'o';
1170                                 maxlen -= 2;
1171                         }
1172
1173                         /* print ',' separator if there are other partitions
1174                          * following */
1175                         if (dev->num_parts > part_cnt) {
1176                                 if (1 > maxlen)
1177                                         goto cleanup;
1178                                 *(p++) = ',';
1179                                 maxlen--;
1180                         }
1181                         prev_part = part;
1182                 }
1183                 /* print ';' separator if there are other devices following */
1184                 if (dentry->next != &devices) {
1185                         if (1 > maxlen)
1186                                 goto cleanup;
1187                         *(p++) = ';';
1188                         maxlen--;
1189                 }
1190         }
1191
1192         /* we still have at least one char left, as we decremented maxlen at
1193          * the begining */
1194         *p = '\0';
1195
1196         return 0;
1197
1198 cleanup:
1199         last_parts[0] = '\0';
1200         return 1;
1201 }
1202
1203 /**
1204  * Call generate_mtdparts to process all devices and generate corresponding
1205  * mtdparts string, save it in mtdparts environment variable.
1206  *
1207  * @param buf output buffer holding generated mtdparts string (output)
1208  * @param buflen buffer size
1209  * @return 0 on success, 1 otherwise
1210  */
1211 static int generate_mtdparts_save(char *buf, u32 buflen)
1212 {
1213         int ret;
1214
1215         ret = generate_mtdparts(buf, buflen);
1216
1217         if ((buf[0] != '\0') && (ret == 0))
1218                 env_set("mtdparts", buf);
1219         else
1220                 env_set("mtdparts", NULL);
1221
1222         return ret;
1223 }
1224
1225 #if defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES)
1226 /**
1227  * Get the net size (w/o bad blocks) of the given partition.
1228  *
1229  * @param mtd the mtd info
1230  * @param part the partition
1231  * @return the calculated net size of this partition
1232  */
1233 static uint64_t net_part_size(struct mtd_info *mtd, struct part_info *part)
1234 {
1235         uint64_t i, net_size = 0;
1236
1237         if (!mtd->_block_isbad)
1238                 return part->size;
1239
1240         for (i = 0; i < part->size; i += mtd->erasesize) {
1241                 if (!mtd->_block_isbad(mtd, part->offset + i))
1242                         net_size += mtd->erasesize;
1243         }
1244
1245         return net_size;
1246 }
1247 #endif
1248
1249 static void print_partition_table(void)
1250 {
1251         struct list_head *dentry, *pentry;
1252         struct part_info *part;
1253         struct mtd_device *dev;
1254         int part_num;
1255
1256         list_for_each(dentry, &devices) {
1257                 dev = list_entry(dentry, struct mtd_device, link);
1258                 /* list partitions for given device */
1259                 part_num = 0;
1260 #if defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES)
1261                 struct mtd_info *mtd;
1262
1263                 if (get_mtd_info(dev->id->type, dev->id->num, &mtd))
1264                         return;
1265
1266                 printf("\ndevice %s%d <%s>, # parts = %d\n",
1267                                 MTD_DEV_TYPE(dev->id->type), dev->id->num,
1268                                 dev->id->mtd_id, dev->num_parts);
1269                 printf(" #: name\t\tsize\t\tnet size\toffset\t\tmask_flags\n");
1270
1271                 list_for_each(pentry, &dev->parts) {
1272                         u32 net_size;
1273                         char *size_note;
1274
1275                         part = list_entry(pentry, struct part_info, link);
1276                         net_size = net_part_size(mtd, part);
1277                         size_note = part->size == net_size ? " " : " (!)";
1278                         printf("%2d: %-20s0x%08llx\t0x%08x%s\t0x%08llx\t%d\n",
1279                                         part_num, part->name, part->size,
1280                                         net_size, size_note, part->offset,
1281                                         part->mask_flags);
1282 #else /* !defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES) */
1283                 printf("\ndevice %s%d <%s>, # parts = %d\n",
1284                                 MTD_DEV_TYPE(dev->id->type), dev->id->num,
1285                                 dev->id->mtd_id, dev->num_parts);
1286                 printf(" #: name\t\tsize\t\toffset\t\tmask_flags\n");
1287
1288                 list_for_each(pentry, &dev->parts) {
1289                         part = list_entry(pentry, struct part_info, link);
1290                         printf("%2d: %-20s0x%08llx\t0x%08llx\t%d\n",
1291                                         part_num, part->name, part->size,
1292                                         part->offset, part->mask_flags);
1293 #endif /* defined(CONFIG_CMD_MTDPARTS_SHOW_NET_SIZES) */
1294                         part_num++;
1295                 }
1296         }
1297
1298         if (list_empty(&devices))
1299                 printf("no partitions defined\n");
1300 }
1301
1302 /**
1303  * Format and print out a partition list for each device from global device
1304  * list.
1305  */
1306 static void list_partitions(void)
1307 {
1308         struct part_info *part;
1309
1310         debug("\n---list_partitions---\n");
1311         print_partition_table();
1312
1313         /* current_mtd_dev is not NULL only when we have non empty device list */
1314         if (current_mtd_dev) {
1315                 part = mtd_part_info(current_mtd_dev, current_mtd_partnum);
1316                 if (part) {
1317                         printf("\nactive partition: %s%d,%d - (%s) 0x%08llx @ 0x%08llx\n",
1318                                         MTD_DEV_TYPE(current_mtd_dev->id->type),
1319                                         current_mtd_dev->id->num, current_mtd_partnum,
1320                                         part->name, part->size, part->offset);
1321                 } else {
1322                         printf("could not get current partition info\n\n");
1323                 }
1324         }
1325
1326         printf("\ndefaults:\n");
1327         printf("mtdids  : %s\n",
1328                 mtdids_default ? mtdids_default : "none");
1329         /*
1330          * Using printf() here results in printbuffer overflow
1331          * if default mtdparts string is greater than console
1332          * printbuffer. Use puts() to prevent system crashes.
1333          */
1334         puts("mtdparts: ");
1335         puts(mtdparts_default ? mtdparts_default : "none");
1336         puts("\n");
1337 }
1338
1339 /**
1340  * Given partition identifier in form of <dev_type><dev_num>,<part_num> find
1341  * corresponding device and verify partition number.
1342  *
1343  * @param id string describing device and partition or partition name
1344  * @param dev pointer to the requested device (output)
1345  * @param part_num verified partition number (output)
1346  * @param part pointer to requested partition (output)
1347  * @return 0 on success, 1 otherwise
1348  */
1349 int find_dev_and_part(const char *id, struct mtd_device **dev,
1350                 u8 *part_num, struct part_info **part)
1351 {
1352         struct list_head *dentry, *pentry;
1353         u8 type, dnum, pnum;
1354         const char *p;
1355
1356         debug("--- find_dev_and_part ---\nid = %s\n", id);
1357
1358         list_for_each(dentry, &devices) {
1359                 *part_num = 0;
1360                 *dev = list_entry(dentry, struct mtd_device, link);
1361                 list_for_each(pentry, &(*dev)->parts) {
1362                         *part = list_entry(pentry, struct part_info, link);
1363                         if (strcmp((*part)->name, id) == 0)
1364                                 return 0;
1365                         (*part_num)++;
1366                 }
1367         }
1368
1369         p = id;
1370         *dev = NULL;
1371         *part = NULL;
1372         *part_num = 0;
1373
1374         if (mtd_id_parse(p, &p, &type, &dnum) != 0)
1375                 return 1;
1376
1377         if ((*p++ != ',') || (*p == '\0')) {
1378                 printf("no partition number specified\n");
1379                 return 1;
1380         }
1381         pnum = simple_strtoul(p, (char **)&p, 0);
1382         if (*p != '\0') {
1383                 printf("unexpected trailing character '%c'\n", *p);
1384                 return 1;
1385         }
1386
1387         if ((*dev = device_find(type, dnum)) == NULL) {
1388                 printf("no such device %s%d\n", MTD_DEV_TYPE(type), dnum);
1389                 return 1;
1390         }
1391
1392         if ((*part = mtd_part_info(*dev, pnum)) == NULL) {
1393                 printf("no such partition\n");
1394                 *dev = NULL;
1395                 return 1;
1396         }
1397
1398         *part_num = pnum;
1399
1400         return 0;
1401 }
1402
1403 /**
1404  * Find and delete partition. For partition id format see find_dev_and_part().
1405  *
1406  * @param id string describing device and partition
1407  * @return 0 on success, 1 otherwise
1408  */
1409 static int delete_partition(const char *id)
1410 {
1411         u8 pnum;
1412         struct mtd_device *dev;
1413         struct part_info *part;
1414
1415         if (find_dev_and_part(id, &dev, &pnum, &part) == 0) {
1416
1417                 debug("delete_partition: device = %s%d, partition %d = (%s) 0x%08llx@0x%08llx\n",
1418                                 MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum,
1419                                 part->name, part->size, part->offset);
1420
1421                 if (part_del(dev, part) != 0)
1422                         return 1;
1423
1424                 if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
1425                         printf("generated mtdparts too long, resetting to null\n");
1426                         return 1;
1427                 }
1428                 return 0;
1429         }
1430
1431         printf("partition %s not found\n", id);
1432         return 1;
1433 }
1434
1435 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
1436 /**
1437  * Increase the size of the given partition so that it's net size is at least
1438  * as large as the size member and such that the next partition would start on a
1439  * good block if it were adjacent to this partition.
1440  *
1441  * @param mtd the mtd device
1442  * @param part the partition
1443  * @param next_offset pointer to the offset of the next partition after this
1444  *                    partition's size has been modified (output)
1445  */
1446 static void spread_partition(struct mtd_info *mtd, struct part_info *part,
1447                              uint64_t *next_offset)
1448 {
1449         uint64_t net_size, padding_size = 0;
1450         int truncated;
1451
1452         mtd_get_len_incl_bad(mtd, part->offset, part->size, &net_size,
1453                              &truncated);
1454
1455         /*
1456          * Absorb bad blocks immediately following this
1457          * partition also into the partition, such that
1458          * the next partition starts with a good block.
1459          */
1460         if (!truncated) {
1461                 mtd_get_len_incl_bad(mtd, part->offset + net_size,
1462                                      mtd->erasesize, &padding_size, &truncated);
1463                 if (truncated)
1464                         padding_size = 0;
1465                 else
1466                         padding_size -= mtd->erasesize;
1467         }
1468
1469         if (truncated) {
1470                 printf("truncated partition %s to %lld bytes\n", part->name,
1471                        (uint64_t) net_size + padding_size);
1472         }
1473
1474         part->size = net_size + padding_size;
1475         *next_offset = part->offset + part->size;
1476 }
1477
1478 /**
1479  * Adjust all of the partition sizes, such that all partitions are at least
1480  * as big as their mtdparts environment variable sizes and they each start
1481  * on a good block.
1482  *
1483  * @return 0 on success, 1 otherwise
1484  */
1485 static int spread_partitions(void)
1486 {
1487         struct list_head *dentry, *pentry;
1488         struct mtd_device *dev;
1489         struct part_info *part;
1490         struct mtd_info *mtd;
1491         int part_num;
1492         uint64_t cur_offs;
1493
1494         list_for_each(dentry, &devices) {
1495                 dev = list_entry(dentry, struct mtd_device, link);
1496
1497                 if (get_mtd_info(dev->id->type, dev->id->num, &mtd))
1498                         return 1;
1499
1500                 part_num = 0;
1501                 cur_offs = 0;
1502                 list_for_each(pentry, &dev->parts) {
1503                         part = list_entry(pentry, struct part_info, link);
1504
1505                         debug("spread_partitions: device = %s%d, partition %d ="
1506                                 " (%s) 0x%08llx@0x%08llx\n",
1507                                 MTD_DEV_TYPE(dev->id->type), dev->id->num,
1508                                 part_num, part->name, part->size,
1509                                 part->offset);
1510
1511                         if (cur_offs > part->offset)
1512                                 part->offset = cur_offs;
1513
1514                         spread_partition(mtd, part, &cur_offs);
1515
1516                         part_num++;
1517                 }
1518         }
1519
1520         index_partitions();
1521
1522         if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
1523                 printf("generated mtdparts too long, resetting to null\n");
1524                 return 1;
1525         }
1526         return 0;
1527 }
1528 #endif /* CONFIG_CMD_MTDPARTS_SPREAD */
1529
1530 /**
1531  * The mtdparts variable tends to be long. If we need to access it
1532  * before the env is relocated, then we need to use our own stack
1533  * buffer.  gd->env_buf will be too small.
1534  *
1535  * @param buf temporary buffer pointer MTDPARTS_MAXLEN long
1536  * @return mtdparts variable string, NULL if not found
1537  */
1538 static const char *env_get_mtdparts(char *buf)
1539 {
1540         if (gd->flags & GD_FLG_ENV_READY)
1541                 return env_get("mtdparts");
1542         if (env_get_f("mtdparts", buf, MTDPARTS_MAXLEN) != -1)
1543                 return buf;
1544         return NULL;
1545 }
1546
1547 /**
1548  * Accept character string describing mtd partitions and call device_parse()
1549  * for each entry. Add created devices to the global devices list.
1550  *
1551  * @param mtdparts string specifing mtd partitions
1552  * @return 0 on success, 1 otherwise
1553  */
1554 static int parse_mtdparts(const char *const mtdparts)
1555 {
1556         const char *p;
1557         struct mtd_device *dev;
1558         int err = 1;
1559         char tmp_parts[MTDPARTS_MAXLEN];
1560
1561         debug("\n---parse_mtdparts---\nmtdparts = %s\n\n", mtdparts);
1562
1563         /* delete all devices and partitions */
1564         if (mtd_devices_init() != 0) {
1565                 printf("could not initialise device list\n");
1566                 return err;
1567         }
1568
1569         /* re-read 'mtdparts' variable, mtd_devices_init may be updating env */
1570         p = env_get_mtdparts(tmp_parts);
1571         if (!p)
1572                 p = mtdparts;
1573
1574         /* Skip the useless prefix, if any */
1575         if (strncmp(p, "mtdparts=", 9) == 0)
1576                 p += 9;
1577
1578         while (*p != '\0') {
1579                 err = 1;
1580                 if ((device_parse(p, &p, &dev) != 0) || (!dev))
1581                         break;
1582
1583                 debug("+ device: %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
1584                                 dev->id->num, dev->id->mtd_id);
1585
1586                 /* check if parsed device is already on the list */
1587                 if (device_find(dev->id->type, dev->id->num) != NULL) {
1588                         printf("device %s%d redefined, please correct mtdparts variable\n",
1589                                         MTD_DEV_TYPE(dev->id->type), dev->id->num);
1590                         break;
1591                 }
1592
1593                 list_add_tail(&dev->link, &devices);
1594                 err = 0;
1595         }
1596         if (err == 1) {
1597                 free(dev);
1598                 device_delall(&devices);
1599         }
1600
1601         return err;
1602 }
1603
1604 /**
1605  * Parse provided string describing mtdids mapping (see file header for mtdids
1606  * variable format). Allocate memory for each entry and add all found entries
1607  * to the global mtdids list.
1608  *
1609  * @param ids mapping string
1610  * @return 0 on success, 1 otherwise
1611  */
1612 static int parse_mtdids(const char *const ids)
1613 {
1614         const char *p = ids;
1615         const char *mtd_id;
1616         int mtd_id_len;
1617         struct mtdids *id;
1618         struct list_head *entry, *n;
1619         struct mtdids *id_tmp;
1620         u8 type, num;
1621         u64 size;
1622         int ret = 1;
1623
1624         debug("\n---parse_mtdids---\nmtdids = %s\n\n", ids);
1625
1626         /* clean global mtdids list */
1627         list_for_each_safe(entry, n, &mtdids) {
1628                 id_tmp = list_entry(entry, struct mtdids, link);
1629                 debug("mtdids del: %d %d\n", id_tmp->type, id_tmp->num);
1630                 list_del(entry);
1631                 free(id_tmp);
1632         }
1633         last_ids[0] = '\0';
1634         INIT_LIST_HEAD(&mtdids);
1635
1636         while(p && (*p != '\0')) {
1637
1638                 ret = 1;
1639                 /* parse 'nor'|'nand'|'onenand'|'spi-nand'<dev-num> */
1640                 if (mtd_id_parse(p, &p, &type, &num) != 0)
1641                         break;
1642
1643                 if (*p != '=') {
1644                         printf("mtdids: incorrect <dev-num>\n");
1645                         break;
1646                 }
1647                 p++;
1648
1649                 /* check if requested device exists */
1650                 if (mtd_device_validate(type, num, &size) != 0)
1651                         return 1;
1652
1653                 /* locate <mtd-id> */
1654                 mtd_id = p;
1655                 if ((p = strchr(mtd_id, ',')) != NULL) {
1656                         mtd_id_len = p - mtd_id + 1;
1657                         p++;
1658                 } else {
1659                         mtd_id_len = strlen(mtd_id) + 1;
1660                 }
1661                 if (mtd_id_len == 0) {
1662                         printf("mtdids: no <mtd-id> identifier\n");
1663                         break;
1664                 }
1665
1666                 /* check if this id is already on the list */
1667                 int double_entry = 0;
1668                 list_for_each(entry, &mtdids) {
1669                         id_tmp = list_entry(entry, struct mtdids, link);
1670                         if ((id_tmp->type == type) && (id_tmp->num == num)) {
1671                                 double_entry = 1;
1672                                 break;
1673                         }
1674                 }
1675                 if (double_entry) {
1676                         printf("device id %s%d redefined, please correct mtdids variable\n",
1677                                         MTD_DEV_TYPE(type), num);
1678                         break;
1679                 }
1680
1681                 /* allocate mtdids structure */
1682                 if (!(id = (struct mtdids *)malloc(sizeof(struct mtdids) + mtd_id_len))) {
1683                         printf("out of memory\n");
1684                         break;
1685                 }
1686                 memset(id, 0, sizeof(struct mtdids) + mtd_id_len);
1687                 id->num = num;
1688                 id->type = type;
1689                 id->size = size;
1690                 id->mtd_id = (char *)(id + 1);
1691                 strncpy(id->mtd_id, mtd_id, mtd_id_len - 1);
1692                 id->mtd_id[mtd_id_len - 1] = '\0';
1693                 INIT_LIST_HEAD(&id->link);
1694
1695                 debug("+ id %s%d\t%16lld bytes\t%s\n",
1696                                 MTD_DEV_TYPE(id->type), id->num,
1697                                 id->size, id->mtd_id);
1698
1699                 list_add_tail(&id->link, &mtdids);
1700                 ret = 0;
1701         }
1702         if (ret == 1) {
1703                 /* clean mtdids list and free allocated memory */
1704                 list_for_each_safe(entry, n, &mtdids) {
1705                         id_tmp = list_entry(entry, struct mtdids, link);
1706                         list_del(entry);
1707                         free(id_tmp);
1708                 }
1709                 return 1;
1710         }
1711
1712         return 0;
1713 }
1714
1715
1716 /**
1717  * Parse and initialize global mtdids mapping and create global
1718  * device/partition list.
1719  *
1720  * @return 0 on success, 1 otherwise
1721  */
1722 int mtdparts_init(void)
1723 {
1724         static int initialized = 0;
1725         const char *ids, *parts;
1726         const char *current_partition;
1727         int ids_changed;
1728         char tmp_ep[PARTITION_MAXLEN + 1];
1729         char tmp_parts[MTDPARTS_MAXLEN];
1730
1731         debug("\n---mtdparts_init---\n");
1732         if (!initialized) {
1733                 INIT_LIST_HEAD(&mtdids);
1734                 INIT_LIST_HEAD(&devices);
1735                 memset(last_ids, 0, sizeof(last_ids));
1736                 memset(last_parts, 0, sizeof(last_parts));
1737                 memset(last_partition, 0, sizeof(last_partition));
1738 #if defined(CONFIG_SYS_MTDPARTS_RUNTIME)
1739                 board_mtdparts_default(&mtdids_default, &mtdparts_default);
1740 #endif
1741                 use_defaults = 1;
1742                 initialized = 1;
1743         }
1744
1745         /* get variables */
1746         ids = env_get("mtdids");
1747         parts = env_get_mtdparts(tmp_parts);
1748         current_partition = env_get("partition");
1749
1750         /* save it for later parsing, cannot rely on current partition pointer
1751          * as 'partition' variable may be updated during init */
1752         memset(tmp_parts, 0, sizeof(tmp_parts));
1753         memset(tmp_ep, 0, sizeof(tmp_ep));
1754         if (current_partition)
1755                 strncpy(tmp_ep, current_partition, PARTITION_MAXLEN);
1756
1757         debug("last_ids  : %s\n", last_ids);
1758         debug("env_ids   : %s\n", ids);
1759         debug("last_parts: %s\n", last_parts);
1760         debug("env_parts : %s\n\n", parts);
1761
1762         debug("last_partition : %s\n", last_partition);
1763         debug("env_partition  : %s\n", current_partition);
1764
1765         /* if mtdids variable is empty try to use defaults */
1766         if (!ids) {
1767                 if (mtdids_default) {
1768                         debug("mtdids variable not defined, using default\n");
1769                         ids = mtdids_default;
1770                         env_set("mtdids", (char *)ids);
1771                 } else {
1772                         printf("mtdids not defined, no default present\n");
1773                         return 1;
1774                 }
1775         }
1776         if (strlen(ids) > MTDIDS_MAXLEN - 1) {
1777                 printf("mtdids too long (> %d)\n", MTDIDS_MAXLEN);
1778                 return 1;
1779         }
1780
1781         /* use defaults when mtdparts variable is not defined
1782          * once mtdparts is saved environment, drop use_defaults flag */
1783         if (!parts) {
1784                 if (mtdparts_default && use_defaults) {
1785                         parts = mtdparts_default;
1786                         if (env_set("mtdparts", (char *)parts) == 0)
1787                                 use_defaults = 0;
1788                 } else
1789                         printf("mtdparts variable not set, see 'help mtdparts'\n");
1790         }
1791
1792         if (parts && (strlen(parts) > MTDPARTS_MAXLEN - 1)) {
1793                 printf("mtdparts too long (> %d)\n", MTDPARTS_MAXLEN);
1794                 return 1;
1795         }
1796
1797         /* check if we have already parsed those mtdids */
1798         if ((last_ids[0] != '\0') && (strcmp(last_ids, ids) == 0)) {
1799                 ids_changed = 0;
1800         } else {
1801                 ids_changed = 1;
1802
1803                 if (parse_mtdids(ids) != 0) {
1804                         mtd_devices_init();
1805                         return 1;
1806                 }
1807
1808                 /* ok it's good, save new ids */
1809                 strncpy(last_ids, ids, MTDIDS_MAXLEN);
1810         }
1811
1812         /* parse partitions if either mtdparts or mtdids were updated */
1813         if (parts && ((last_parts[0] == '\0') || ((strcmp(last_parts, parts) != 0)) || ids_changed)) {
1814                 if (parse_mtdparts(parts) != 0)
1815                         return 1;
1816
1817                 if (list_empty(&devices)) {
1818                         printf("mtdparts_init: no valid partitions\n");
1819                         return 1;
1820                 }
1821
1822                 /* ok it's good, save new parts */
1823                 strncpy(last_parts, parts, MTDPARTS_MAXLEN);
1824
1825                 /* reset first partition from first dev from the list as current */
1826                 current_mtd_dev = list_entry(devices.next, struct mtd_device, link);
1827                 current_mtd_partnum = 0;
1828                 current_save();
1829
1830                 debug("mtdparts_init: current_mtd_dev  = %s%d, current_mtd_partnum = %d\n",
1831                                 MTD_DEV_TYPE(current_mtd_dev->id->type),
1832                                 current_mtd_dev->id->num, current_mtd_partnum);
1833         }
1834
1835         /* mtdparts variable was reset to NULL, delete all devices/partitions */
1836         if (!parts && (last_parts[0] != '\0'))
1837                 return mtd_devices_init();
1838
1839         /* do not process current partition if mtdparts variable is null */
1840         if (!parts)
1841                 return 0;
1842
1843         /* is current partition set in environment? if so, use it */
1844         if ((tmp_ep[0] != '\0') && (strcmp(tmp_ep, last_partition) != 0)) {
1845                 struct part_info *p;
1846                 struct mtd_device *cdev;
1847                 u8 pnum;
1848
1849                 debug("--- getting current partition: %s\n", tmp_ep);
1850
1851                 if (find_dev_and_part(tmp_ep, &cdev, &pnum, &p) == 0) {
1852                         current_mtd_dev = cdev;
1853                         current_mtd_partnum = pnum;
1854                         current_save();
1855                 }
1856         } else if (env_get("partition") == NULL) {
1857                 debug("no partition variable set, setting...\n");
1858                 current_save();
1859         }
1860
1861         return 0;
1862 }
1863
1864 /**
1865  * Return pointer to the partition of a requested number from a requested
1866  * device.
1867  *
1868  * @param dev device that is to be searched for a partition
1869  * @param part_num requested partition number
1870  * @return pointer to the part_info, NULL otherwise
1871  */
1872 static struct part_info* mtd_part_info(struct mtd_device *dev, unsigned int part_num)
1873 {
1874         struct list_head *entry;
1875         struct part_info *part;
1876         int num;
1877
1878         if (!dev)
1879                 return NULL;
1880
1881         debug("\n--- mtd_part_info: partition number %d for device %s%d (%s)\n",
1882                         part_num, MTD_DEV_TYPE(dev->id->type),
1883                         dev->id->num, dev->id->mtd_id);
1884
1885         if (part_num >= dev->num_parts) {
1886                 printf("invalid partition number %d for device %s%d (%s)\n",
1887                                 part_num, MTD_DEV_TYPE(dev->id->type),
1888                                 dev->id->num, dev->id->mtd_id);
1889                 return NULL;
1890         }
1891
1892         /* locate partition number, return it */
1893         num = 0;
1894         list_for_each(entry, &dev->parts) {
1895                 part = list_entry(entry, struct part_info, link);
1896
1897                 if (part_num == num++) {
1898                         return part;
1899                 }
1900         }
1901
1902         return NULL;
1903 }
1904
1905 /***************************************************/
1906 /* U-Boot commands                                 */
1907 /***************************************************/
1908 /* command line only */
1909 /**
1910  * Routine implementing u-boot chpart command. Sets new current partition based
1911  * on the user supplied partition id. For partition id format see find_dev_and_part().
1912  *
1913  * @param cmdtp command internal data
1914  * @param flag command flag
1915  * @param argc number of arguments supplied to the command
1916  * @param argv arguments list
1917  * @return 0 on success, 1 otherwise
1918  */
1919 static int do_chpart(struct cmd_tbl *cmdtp, int flag, int argc,
1920                      char *const argv[])
1921 {
1922 /* command line only */
1923         struct mtd_device *dev;
1924         struct part_info *part;
1925         u8 pnum;
1926
1927         if (mtdparts_init() !=0)
1928                 return 1;
1929
1930         if (argc < 2) {
1931                 printf("no partition id specified\n");
1932                 return 1;
1933         }
1934
1935         if (find_dev_and_part(argv[1], &dev, &pnum, &part) != 0)
1936                 return 1;
1937
1938         current_mtd_dev = dev;
1939         current_mtd_partnum = pnum;
1940         current_save();
1941
1942         printf("partition changed to %s%d,%d\n",
1943                         MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum);
1944
1945         return 0;
1946 }
1947
1948 /**
1949  * Routine implementing u-boot mtdparts command. Initialize/update default global
1950  * partition list and process user partition request (list, add, del).
1951  *
1952  * @param cmdtp command internal data
1953  * @param flag command flag
1954  * @param argc number of arguments supplied to the command
1955  * @param argv arguments list
1956  * @return 0 on success, 1 otherwise
1957  */
1958 static int do_mtdparts(struct cmd_tbl *cmdtp, int flag, int argc,
1959                        char *const argv[])
1960 {
1961         if (argc == 2) {
1962                 if (strcmp(argv[1], "default") == 0) {
1963                         env_set("mtdids", NULL);
1964                         env_set("mtdparts", NULL);
1965                         env_set("partition", NULL);
1966                         use_defaults = 1;
1967
1968                         mtdparts_init();
1969                         return 0;
1970                 } else if (strcmp(argv[1], "delall") == 0) {
1971                         /* this may be the first run, initialize lists if needed */
1972                         mtdparts_init();
1973
1974                         env_set("mtdparts", NULL);
1975
1976                         /* mtd_devices_init() calls current_save() */
1977                         return mtd_devices_init();
1978                 }
1979         }
1980
1981         /* make sure we are in sync with env variables */
1982         if (mtdparts_init() != 0)
1983                 return 1;
1984
1985         if (argc == 1) {
1986                 list_partitions();
1987                 return 0;
1988         }
1989
1990         /* mtdparts add <mtd-dev> <size>[@<offset>] <name> [ro] */
1991         if (((argc == 5) || (argc == 6)) && (strncmp(argv[1], "add", 3) == 0)) {
1992 #define PART_ADD_DESC_MAXLEN 64
1993                 char tmpbuf[PART_ADD_DESC_MAXLEN];
1994 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
1995                 struct mtd_info *mtd;
1996                 uint64_t next_offset;
1997 #endif
1998                 u8 type, num, len;
1999                 struct mtd_device *dev;
2000                 struct mtd_device *dev_tmp;
2001                 struct mtdids *id;
2002                 struct part_info *p;
2003
2004                 if (mtd_id_parse(argv[2], NULL, &type, &num) != 0)
2005                         return 1;
2006
2007                 if ((id = id_find(type, num)) == NULL) {
2008                         printf("no such device %s defined in mtdids variable\n", argv[2]);
2009                         return 1;
2010                 }
2011
2012                 len = strlen(id->mtd_id) + 1;   /* 'mtd_id:' */
2013                 len += strlen(argv[3]);         /* size@offset */
2014                 len += strlen(argv[4]) + 2;     /* '(' name ')' */
2015                 if (argv[5] && (strlen(argv[5]) == 2))
2016                         len += 2;               /* 'ro' */
2017
2018                 if (len >= PART_ADD_DESC_MAXLEN) {
2019                         printf("too long partition description\n");
2020                         return 1;
2021                 }
2022                 sprintf(tmpbuf, "%s:%s(%s)%s",
2023                                 id->mtd_id, argv[3], argv[4], argv[5] ? argv[5] : "");
2024                 debug("add tmpbuf: %s\n", tmpbuf);
2025
2026                 if ((device_parse(tmpbuf, NULL, &dev) != 0) || (!dev))
2027                         return 1;
2028
2029                 debug("+ %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
2030                                 dev->id->num, dev->id->mtd_id);
2031
2032                 p = list_entry(dev->parts.next, struct part_info, link);
2033
2034 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
2035                 if (get_mtd_info(dev->id->type, dev->id->num, &mtd))
2036                         return 1;
2037
2038                 if (!strcmp(&argv[1][3], ".spread")) {
2039                         spread_partition(mtd, p, &next_offset);
2040                         debug("increased %s to %llu bytes\n", p->name, p->size);
2041                 }
2042 #endif
2043
2044                 dev_tmp = device_find(dev->id->type, dev->id->num);
2045                 if (dev_tmp == NULL) {
2046                         device_add(dev);
2047                 } else if (part_add(dev_tmp, p) != 0) {
2048                         /* merge new partition with existing ones*/
2049                         device_del(dev);
2050                         return 1;
2051                 }
2052
2053                 if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
2054                         printf("generated mtdparts too long, resetting to null\n");
2055                         return 1;
2056                 }
2057
2058                 return 0;
2059         }
2060
2061         /* mtdparts del part-id */
2062         if ((argc == 3) && (strcmp(argv[1], "del") == 0)) {
2063                 debug("del: part-id = %s\n", argv[2]);
2064
2065                 return delete_partition(argv[2]);
2066         }
2067
2068 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
2069         if ((argc == 2) && (strcmp(argv[1], "spread") == 0))
2070                 return spread_partitions();
2071 #endif /* CONFIG_CMD_MTDPARTS_SPREAD */
2072
2073         return CMD_RET_USAGE;
2074 }
2075
2076 /***************************************************/
2077 U_BOOT_CMD(
2078         chpart, 2,      0,      do_chpart,
2079         "change active partition",
2080         "part-id\n"
2081         "    - change active partition (e.g. part-id = nand0,1)"
2082 );
2083
2084 #ifdef CONFIG_SYS_LONGHELP
2085 static char mtdparts_help_text[] =
2086         "\n"
2087         "    - list partition table\n"
2088         "mtdparts delall\n"
2089         "    - delete all partitions\n"
2090         "mtdparts del part-id\n"
2091         "    - delete partition (e.g. part-id = nand0,1)\n"
2092         "mtdparts add <mtd-dev> <size>[@<offset>] [<name>] [ro]\n"
2093         "    - add partition\n"
2094 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
2095         "mtdparts add.spread <mtd-dev> <size>[@<offset>] [<name>] [ro]\n"
2096         "    - add partition, padding size by skipping bad blocks\n"
2097 #endif
2098         "mtdparts default\n"
2099         "    - reset partition table to defaults\n"
2100 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
2101         "mtdparts spread\n"
2102         "    - adjust the sizes of the partitions so they are\n"
2103         "      at least as big as the mtdparts variable specifies\n"
2104         "      and they each start on a good block\n\n"
2105 #else
2106         "\n"
2107 #endif /* CONFIG_CMD_MTDPARTS_SPREAD */
2108         "-----\n\n"
2109         "this command uses three environment variables:\n\n"
2110         "'partition' - keeps current partition identifier\n\n"
2111         "partition  := <part-id>\n"
2112         "<part-id>  := <dev-id>,part_num\n\n"
2113         "'mtdids' - linux kernel mtd device id <-> u-boot device id mapping\n\n"
2114         "mtdids=<idmap>[,<idmap>,...]\n\n"
2115         "<idmap>    := <dev-id>=<mtd-id>\n"
2116         "<dev-id>   := 'nand'|'nor'|'onenand'|'spi-nand'<dev-num>\n"
2117         "<dev-num>  := mtd device number, 0...\n"
2118         "<mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)\n\n"
2119         "'mtdparts' - partition list\n\n"
2120         "mtdparts=mtdparts=<mtd-def>[;<mtd-def>...]\n\n"
2121         "<mtd-def>  := <mtd-id>:<part-def>[,<part-def>...]\n"
2122         "<mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)\n"
2123         "<part-def> := <size>[@<offset>][<name>][<ro-flag>]\n"
2124         "<size>     := standard linux memsize OR '-' to denote all remaining space\n"
2125         "<offset>   := partition start offset within the device\n"
2126         "<name>     := '(' NAME ')'\n"
2127         "<ro-flag>  := when set to 'ro' makes partition read-only (not used, passed to kernel)";
2128 #endif
2129
2130 U_BOOT_CMD(
2131         mtdparts,       6,      0,      do_mtdparts,
2132         "define flash/nand partitions", mtdparts_help_text
2133 );
2134 /***************************************************/