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