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