]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_mtdparts.c
mtdparts: regroup calls to get_mtd_device_nm
[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 /**
1219  * Format and print out a partition list for each device from global device
1220  * list.
1221  */
1222 static void list_partitions(void)
1223 {
1224         struct list_head *dentry, *pentry;
1225         struct part_info *part;
1226         struct mtd_device *dev;
1227         int part_num;
1228
1229         debug("\n---list_partitions---\n");
1230         list_for_each(dentry, &devices) {
1231                 dev = list_entry(dentry, struct mtd_device, link);
1232                 printf("\ndevice %s%d <%s>, # parts = %d\n",
1233                                 MTD_DEV_TYPE(dev->id->type), dev->id->num,
1234                                 dev->id->mtd_id, dev->num_parts);
1235                 printf(" #: name\t\tsize\t\toffset\t\tmask_flags\n");
1236
1237                 /* list partitions for given device */
1238                 part_num = 0;
1239                 list_for_each(pentry, &dev->parts) {
1240                         part = list_entry(pentry, struct part_info, link);
1241                         printf("%2d: %-20s0x%08x\t0x%08x\t%d\n",
1242                                         part_num, part->name, part->size,
1243                                         part->offset, part->mask_flags);
1244
1245                         part_num++;
1246                 }
1247         }
1248         if (list_empty(&devices))
1249                 printf("no partitions defined\n");
1250
1251         /* current_mtd_dev is not NULL only when we have non empty device list */
1252         if (current_mtd_dev) {
1253                 part = mtd_part_info(current_mtd_dev, current_mtd_partnum);
1254                 if (part) {
1255                         printf("\nactive partition: %s%d,%d - (%s) 0x%08x @ 0x%08x\n",
1256                                         MTD_DEV_TYPE(current_mtd_dev->id->type),
1257                                         current_mtd_dev->id->num, current_mtd_partnum,
1258                                         part->name, part->size, part->offset);
1259                 } else {
1260                         printf("could not get current partition info\n\n");
1261                 }
1262         }
1263
1264         printf("\ndefaults:\n");
1265         printf("mtdids  : %s\n",
1266                 mtdids_default ? mtdids_default : "none");
1267         /*
1268          * Using printf() here results in printbuffer overflow
1269          * if default mtdparts string is greater than console
1270          * printbuffer. Use puts() to prevent system crashes.
1271          */
1272         puts("mtdparts: ");
1273         puts(mtdparts_default ? mtdparts_default : "none");
1274         puts("\n");
1275 }
1276
1277 /**
1278  * Given partition identifier in form of <dev_type><dev_num>,<part_num> find
1279  * corresponding device and verify partition number.
1280  *
1281  * @param id string describing device and partition or partition name
1282  * @param dev pointer to the requested device (output)
1283  * @param part_num verified partition number (output)
1284  * @param part pointer to requested partition (output)
1285  * @return 0 on success, 1 otherwise
1286  */
1287 int find_dev_and_part(const char *id, struct mtd_device **dev,
1288                 u8 *part_num, struct part_info **part)
1289 {
1290         struct list_head *dentry, *pentry;
1291         u8 type, dnum, pnum;
1292         const char *p;
1293
1294         debug("--- find_dev_and_part ---\nid = %s\n", id);
1295
1296         list_for_each(dentry, &devices) {
1297                 *part_num = 0;
1298                 *dev = list_entry(dentry, struct mtd_device, link);
1299                 list_for_each(pentry, &(*dev)->parts) {
1300                         *part = list_entry(pentry, struct part_info, link);
1301                         if (strcmp((*part)->name, id) == 0)
1302                                 return 0;
1303                         (*part_num)++;
1304                 }
1305         }
1306
1307         p = id;
1308         *dev = NULL;
1309         *part = NULL;
1310         *part_num = 0;
1311
1312         if (mtd_id_parse(p, &p, &type, &dnum) != 0)
1313                 return 1;
1314
1315         if ((*p++ != ',') || (*p == '\0')) {
1316                 printf("no partition number specified\n");
1317                 return 1;
1318         }
1319         pnum = simple_strtoul(p, (char **)&p, 0);
1320         if (*p != '\0') {
1321                 printf("unexpected trailing character '%c'\n", *p);
1322                 return 1;
1323         }
1324
1325         if ((*dev = device_find(type, dnum)) == NULL) {
1326                 printf("no such device %s%d\n", MTD_DEV_TYPE(type), dnum);
1327                 return 1;
1328         }
1329
1330         if ((*part = mtd_part_info(*dev, pnum)) == NULL) {
1331                 printf("no such partition\n");
1332                 *dev = NULL;
1333                 return 1;
1334         }
1335
1336         *part_num = pnum;
1337
1338         return 0;
1339 }
1340
1341 /**
1342  * Find and delete partition. For partition id format see find_dev_and_part().
1343  *
1344  * @param id string describing device and partition
1345  * @return 0 on success, 1 otherwise
1346  */
1347 static int delete_partition(const char *id)
1348 {
1349         u8 pnum;
1350         struct mtd_device *dev;
1351         struct part_info *part;
1352
1353         if (find_dev_and_part(id, &dev, &pnum, &part) == 0) {
1354
1355                 debug("delete_partition: device = %s%d, partition %d = (%s) 0x%08x@0x%08x\n",
1356                                 MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum,
1357                                 part->name, part->size, part->offset);
1358
1359                 if (part_del(dev, part) != 0)
1360                         return 1;
1361
1362                 if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
1363                         printf("generated mtdparts too long, reseting to null\n");
1364                         return 1;
1365                 }
1366                 return 0;
1367         }
1368
1369         printf("partition %s not found\n", id);
1370         return 1;
1371 }
1372
1373 /**
1374  * Accept character string describing mtd partitions and call device_parse()
1375  * for each entry. Add created devices to the global devices list.
1376  *
1377  * @param mtdparts string specifing mtd partitions
1378  * @return 0 on success, 1 otherwise
1379  */
1380 static int parse_mtdparts(const char *const mtdparts)
1381 {
1382         const char *p = mtdparts;
1383         struct mtd_device *dev;
1384         int err = 1;
1385
1386         debug("\n---parse_mtdparts---\nmtdparts = %s\n\n", p);
1387
1388         /* delete all devices and partitions */
1389         if (mtd_devices_init() != 0) {
1390                 printf("could not initialise device list\n");
1391                 return err;
1392         }
1393
1394         /* re-read 'mtdparts' variable, mtd_devices_init may be updating env */
1395         p = getenv("mtdparts");
1396
1397         if (strncmp(p, "mtdparts=", 9) != 0) {
1398                 printf("mtdparts variable doesn't start with 'mtdparts='\n");
1399                 return err;
1400         }
1401         p += 9;
1402
1403         while (p && (*p != '\0')) {
1404                 err = 1;
1405                 if ((device_parse(p, &p, &dev) != 0) || (!dev))
1406                         break;
1407
1408                 debug("+ device: %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
1409                                 dev->id->num, dev->id->mtd_id);
1410
1411                 /* check if parsed device is already on the list */
1412                 if (device_find(dev->id->type, dev->id->num) != NULL) {
1413                         printf("device %s%d redefined, please correct mtdparts variable\n",
1414                                         MTD_DEV_TYPE(dev->id->type), dev->id->num);
1415                         break;
1416                 }
1417
1418                 list_add_tail(&dev->link, &devices);
1419                 err = 0;
1420         }
1421         if (err == 1) {
1422                 device_delall(&devices);
1423                 return 1;
1424         }
1425
1426         return 0;
1427 }
1428
1429 /**
1430  * Parse provided string describing mtdids mapping (see file header for mtdids
1431  * variable format). Allocate memory for each entry and add all found entries
1432  * to the global mtdids list.
1433  *
1434  * @param ids mapping string
1435  * @return 0 on success, 1 otherwise
1436  */
1437 static int parse_mtdids(const char *const ids)
1438 {
1439         const char *p = ids;
1440         const char *mtd_id;
1441         int mtd_id_len;
1442         struct mtdids *id;
1443         struct list_head *entry, *n;
1444         struct mtdids *id_tmp;
1445         u8 type, num;
1446         u32 size;
1447         int ret = 1;
1448
1449         debug("\n---parse_mtdids---\nmtdids = %s\n\n", ids);
1450
1451         /* clean global mtdids list */
1452         list_for_each_safe(entry, n, &mtdids) {
1453                 id_tmp = list_entry(entry, struct mtdids, link);
1454                 debug("mtdids del: %d %d\n", id_tmp->type, id_tmp->num);
1455                 list_del(entry);
1456                 free(id_tmp);
1457         }
1458         last_ids[0] = '\0';
1459         INIT_LIST_HEAD(&mtdids);
1460
1461         while(p && (*p != '\0')) {
1462
1463                 ret = 1;
1464                 /* parse 'nor'|'nand'|'onenand'<dev-num> */
1465                 if (mtd_id_parse(p, &p, &type, &num) != 0)
1466                         break;
1467
1468                 if (*p != '=') {
1469                         printf("mtdids: incorrect <dev-num>\n");
1470                         break;
1471                 }
1472                 p++;
1473
1474                 /* check if requested device exists */
1475                 if (mtd_device_validate(type, num, &size) != 0)
1476                         return 1;
1477
1478                 /* locate <mtd-id> */
1479                 mtd_id = p;
1480                 if ((p = strchr(mtd_id, ',')) != NULL) {
1481                         mtd_id_len = p - mtd_id + 1;
1482                         p++;
1483                 } else {
1484                         mtd_id_len = strlen(mtd_id) + 1;
1485                 }
1486                 if (mtd_id_len == 0) {
1487                         printf("mtdids: no <mtd-id> identifier\n");
1488                         break;
1489                 }
1490
1491                 /* check if this id is already on the list */
1492                 int double_entry = 0;
1493                 list_for_each(entry, &mtdids) {
1494                         id_tmp = list_entry(entry, struct mtdids, link);
1495                         if ((id_tmp->type == type) && (id_tmp->num == num)) {
1496                                 double_entry = 1;
1497                                 break;
1498                         }
1499                 }
1500                 if (double_entry) {
1501                         printf("device id %s%d redefined, please correct mtdids variable\n",
1502                                         MTD_DEV_TYPE(type), num);
1503                         break;
1504                 }
1505
1506                 /* allocate mtdids structure */
1507                 if (!(id = (struct mtdids *)malloc(sizeof(struct mtdids) + mtd_id_len))) {
1508                         printf("out of memory\n");
1509                         break;
1510                 }
1511                 memset(id, 0, sizeof(struct mtdids) + mtd_id_len);
1512                 id->num = num;
1513                 id->type = type;
1514                 id->size = size;
1515                 id->mtd_id = (char *)(id + 1);
1516                 strncpy(id->mtd_id, mtd_id, mtd_id_len - 1);
1517                 id->mtd_id[mtd_id_len - 1] = '\0';
1518                 INIT_LIST_HEAD(&id->link);
1519
1520                 debug("+ id %s%d\t%16d bytes\t%s\n",
1521                                 MTD_DEV_TYPE(id->type), id->num,
1522                                 id->size, id->mtd_id);
1523
1524                 list_add_tail(&id->link, &mtdids);
1525                 ret = 0;
1526         }
1527         if (ret == 1) {
1528                 /* clean mtdids list and free allocated memory */
1529                 list_for_each_safe(entry, n, &mtdids) {
1530                         id_tmp = list_entry(entry, struct mtdids, link);
1531                         list_del(entry);
1532                         free(id_tmp);
1533                 }
1534                 return 1;
1535         }
1536
1537         return 0;
1538 }
1539
1540 /**
1541  * Parse and initialize global mtdids mapping and create global
1542  * device/partition list.
1543  *
1544  * @return 0 on success, 1 otherwise
1545  */
1546 int mtdparts_init(void)
1547 {
1548         static int initialized = 0;
1549         const char *ids, *parts;
1550         const char *current_partition;
1551         int ids_changed;
1552         char tmp_ep[PARTITION_MAXLEN];
1553
1554         debug("\n---mtdparts_init---\n");
1555         if (!initialized) {
1556                 INIT_LIST_HEAD(&mtdids);
1557                 INIT_LIST_HEAD(&devices);
1558                 memset(last_ids, 0, MTDIDS_MAXLEN);
1559                 memset(last_parts, 0, MTDPARTS_MAXLEN);
1560                 memset(last_partition, 0, PARTITION_MAXLEN);
1561                 initialized = 1;
1562         }
1563
1564         /* get variables */
1565         ids = getenv("mtdids");
1566         parts = getenv("mtdparts");
1567         current_partition = getenv("partition");
1568
1569         /* save it for later parsing, cannot rely on current partition pointer
1570          * as 'partition' variable may be updated during init */
1571         tmp_ep[0] = '\0';
1572         if (current_partition)
1573                 strncpy(tmp_ep, current_partition, PARTITION_MAXLEN);
1574
1575         debug("last_ids  : %s\n", last_ids);
1576         debug("env_ids   : %s\n", ids);
1577         debug("last_parts: %s\n", last_parts);
1578         debug("env_parts : %s\n\n", parts);
1579
1580         debug("last_partition : %s\n", last_partition);
1581         debug("env_partition  : %s\n", current_partition);
1582
1583         /* if mtdids varible is empty try to use defaults */
1584         if (!ids) {
1585                 if (mtdids_default) {
1586                         debug("mtdids variable not defined, using default\n");
1587                         ids = mtdids_default;
1588                         setenv("mtdids", (char *)ids);
1589                 } else {
1590                         printf("mtdids not defined, no default present\n");
1591                         return 1;
1592                 }
1593         }
1594         if (strlen(ids) > MTDIDS_MAXLEN - 1) {
1595                 printf("mtdids too long (> %d)\n", MTDIDS_MAXLEN);
1596                 return 1;
1597         }
1598
1599         /* do no try to use defaults when mtdparts variable is not defined,
1600          * just check the length */
1601         if (!parts)
1602                 printf("mtdparts variable not set, see 'help mtdparts'\n");
1603
1604         if (parts && (strlen(parts) > MTDPARTS_MAXLEN - 1)) {
1605                 printf("mtdparts too long (> %d)\n", MTDPARTS_MAXLEN);
1606                 return 1;
1607         }
1608
1609         /* check if we have already parsed those mtdids */
1610         if ((last_ids[0] != '\0') && (strcmp(last_ids, ids) == 0)) {
1611                 ids_changed = 0;
1612         } else {
1613                 ids_changed = 1;
1614
1615                 if (parse_mtdids(ids) != 0) {
1616                         mtd_devices_init();
1617                         return 1;
1618                 }
1619
1620                 /* ok it's good, save new ids */
1621                 strncpy(last_ids, ids, MTDIDS_MAXLEN);
1622         }
1623
1624         /* parse partitions if either mtdparts or mtdids were updated */
1625         if (parts && ((last_parts[0] == '\0') || ((strcmp(last_parts, parts) != 0)) || ids_changed)) {
1626                 if (parse_mtdparts(parts) != 0)
1627                         return 1;
1628
1629                 if (list_empty(&devices)) {
1630                         printf("mtdparts_init: no valid partitions\n");
1631                         return 1;
1632                 }
1633
1634                 /* ok it's good, save new parts */
1635                 strncpy(last_parts, parts, MTDPARTS_MAXLEN);
1636
1637                 /* reset first partition from first dev from the list as current */
1638                 current_mtd_dev = list_entry(devices.next, struct mtd_device, link);
1639                 current_mtd_partnum = 0;
1640                 current_save();
1641
1642                 debug("mtdparts_init: current_mtd_dev  = %s%d, current_mtd_partnum = %d\n",
1643                                 MTD_DEV_TYPE(current_mtd_dev->id->type),
1644                                 current_mtd_dev->id->num, current_mtd_partnum);
1645         }
1646
1647         /* mtdparts variable was reset to NULL, delete all devices/partitions */
1648         if (!parts && (last_parts[0] != '\0'))
1649                 return mtd_devices_init();
1650
1651         /* do not process current partition if mtdparts variable is null */
1652         if (!parts)
1653                 return 0;
1654
1655         /* is current partition set in environment? if so, use it */
1656         if ((tmp_ep[0] != '\0') && (strcmp(tmp_ep, last_partition) != 0)) {
1657                 struct part_info *p;
1658                 struct mtd_device *cdev;
1659                 u8 pnum;
1660
1661                 debug("--- getting current partition: %s\n", tmp_ep);
1662
1663                 if (find_dev_and_part(tmp_ep, &cdev, &pnum, &p) == 0) {
1664                         current_mtd_dev = cdev;
1665                         current_mtd_partnum = pnum;
1666                         current_save();
1667                 }
1668         } else if (getenv("partition") == NULL) {
1669                 debug("no partition variable set, setting...\n");
1670                 current_save();
1671         }
1672
1673         return 0;
1674 }
1675
1676 /**
1677  * Return pointer to the partition of a requested number from a requested
1678  * device.
1679  *
1680  * @param dev device that is to be searched for a partition
1681  * @param part_num requested partition number
1682  * @return pointer to the part_info, NULL otherwise
1683  */
1684 static struct part_info* mtd_part_info(struct mtd_device *dev, unsigned int part_num)
1685 {
1686         struct list_head *entry;
1687         struct part_info *part;
1688         int num;
1689
1690         if (!dev)
1691                 return NULL;
1692
1693         debug("\n--- mtd_part_info: partition number %d for device %s%d (%s)\n",
1694                         part_num, MTD_DEV_TYPE(dev->id->type),
1695                         dev->id->num, dev->id->mtd_id);
1696
1697         if (part_num >= dev->num_parts) {
1698                 printf("invalid partition number %d for device %s%d (%s)\n",
1699                                 part_num, MTD_DEV_TYPE(dev->id->type),
1700                                 dev->id->num, dev->id->mtd_id);
1701                 return NULL;
1702         }
1703
1704         /* locate partition number, return it */
1705         num = 0;
1706         list_for_each(entry, &dev->parts) {
1707                 part = list_entry(entry, struct part_info, link);
1708
1709                 if (part_num == num++) {
1710                         return part;
1711                 }
1712         }
1713
1714         return NULL;
1715 }
1716
1717 /***************************************************/
1718 /* U-boot commands                                 */
1719 /***************************************************/
1720 /* command line only */
1721 /**
1722  * Routine implementing u-boot chpart command. Sets new current partition based
1723  * on the user supplied partition id. For partition id format see find_dev_and_part().
1724  *
1725  * @param cmdtp command internal data
1726  * @param flag command flag
1727  * @param argc number of arguments supplied to the command
1728  * @param argv arguments list
1729  * @return 0 on success, 1 otherwise
1730  */
1731 int do_chpart(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1732 {
1733 /* command line only */
1734         struct mtd_device *dev;
1735         struct part_info *part;
1736         u8 pnum;
1737
1738         if (mtdparts_init() !=0)
1739                 return 1;
1740
1741         if (argc < 2) {
1742                 printf("no partition id specified\n");
1743                 return 1;
1744         }
1745
1746         if (find_dev_and_part(argv[1], &dev, &pnum, &part) != 0)
1747                 return 1;
1748
1749         current_mtd_dev = dev;
1750         current_mtd_partnum = pnum;
1751         current_save();
1752
1753         printf("partition changed to %s%d,%d\n",
1754                         MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum);
1755
1756         return 0;
1757 }
1758
1759 /**
1760  * Routine implementing u-boot mtdparts command. Initialize/update default global
1761  * partition list and process user partition request (list, add, del).
1762  *
1763  * @param cmdtp command internal data
1764  * @param flag command flag
1765  * @param argc number of arguments supplied to the command
1766  * @param argv arguments list
1767  * @return 0 on success, 1 otherwise
1768  */
1769 int do_mtdparts(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1770 {
1771         if (argc == 2) {
1772                 if (strcmp(argv[1], "default") == 0) {
1773                         setenv("mtdids", (char *)mtdids_default);
1774                         setenv("mtdparts", (char *)mtdparts_default);
1775                         setenv("partition", NULL);
1776
1777                         mtdparts_init();
1778                         return 0;
1779                 } else if (strcmp(argv[1], "delall") == 0) {
1780                         /* this may be the first run, initialize lists if needed */
1781                         mtdparts_init();
1782
1783                         setenv("mtdparts", NULL);
1784
1785                         /* mtd_devices_init() calls current_save() */
1786                         return mtd_devices_init();
1787                 }
1788         }
1789
1790         /* make sure we are in sync with env variables */
1791         if (mtdparts_init() != 0)
1792                 return 1;
1793
1794         if (argc == 1) {
1795                 list_partitions();
1796                 return 0;
1797         }
1798
1799         /* mtdparts add <mtd-dev> <size>[@<offset>] <name> [ro] */
1800         if (((argc == 5) || (argc == 6)) && (strcmp(argv[1], "add") == 0)) {
1801 #define PART_ADD_DESC_MAXLEN 64
1802                 char tmpbuf[PART_ADD_DESC_MAXLEN];
1803                 u8 type, num, len;
1804                 struct mtd_device *dev;
1805                 struct mtd_device *dev_tmp;
1806                 struct mtdids *id;
1807                 struct part_info *p;
1808
1809                 if (mtd_id_parse(argv[2], NULL, &type, &num) != 0)
1810                         return 1;
1811
1812                 if ((id = id_find(type, num)) == NULL) {
1813                         printf("no such device %s defined in mtdids variable\n", argv[2]);
1814                         return 1;
1815                 }
1816
1817                 len = strlen(id->mtd_id) + 1;   /* 'mtd_id:' */
1818                 len += strlen(argv[3]);         /* size@offset */
1819                 len += strlen(argv[4]) + 2;     /* '(' name ')' */
1820                 if (argv[5] && (strlen(argv[5]) == 2))
1821                         len += 2;               /* 'ro' */
1822
1823                 if (len >= PART_ADD_DESC_MAXLEN) {
1824                         printf("too long partition description\n");
1825                         return 1;
1826                 }
1827                 sprintf(tmpbuf, "%s:%s(%s)%s",
1828                                 id->mtd_id, argv[3], argv[4], argv[5] ? argv[5] : "");
1829                 debug("add tmpbuf: %s\n", tmpbuf);
1830
1831                 if ((device_parse(tmpbuf, NULL, &dev) != 0) || (!dev))
1832                         return 1;
1833
1834                 debug("+ %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
1835                                 dev->id->num, dev->id->mtd_id);
1836
1837                 if ((dev_tmp = device_find(dev->id->type, dev->id->num)) == NULL) {
1838                         device_add(dev);
1839                 } else {
1840                         /* merge new partition with existing ones*/
1841                         p = list_entry(dev->parts.next, struct part_info, link);
1842                         if (part_add(dev_tmp, p) != 0) {
1843                                 device_del(dev);
1844                                 return 1;
1845                         }
1846                 }
1847
1848                 if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
1849                         printf("generated mtdparts too long, reseting to null\n");
1850                         return 1;
1851                 }
1852
1853                 return 0;
1854         }
1855
1856         /* mtdparts del part-id */
1857         if ((argc == 3) && (strcmp(argv[1], "del") == 0)) {
1858                 debug("del: part-id = %s\n", argv[2]);
1859
1860                 return delete_partition(argv[2]);
1861         }
1862
1863         return cmd_usage(cmdtp);
1864 }
1865
1866 /***************************************************/
1867 U_BOOT_CMD(
1868         chpart, 2,      0,      do_chpart,
1869         "change active partition",
1870         "part-id\n"
1871         "    - change active partition (e.g. part-id = nand0,1)"
1872 );
1873
1874 U_BOOT_CMD(
1875         mtdparts,       6,      0,      do_mtdparts,
1876         "define flash/nand partitions",
1877         "\n"
1878         "    - list partition table\n"
1879         "mtdparts delall\n"
1880         "    - delete all partitions\n"
1881         "mtdparts del part-id\n"
1882         "    - delete partition (e.g. part-id = nand0,1)\n"
1883         "mtdparts add <mtd-dev> <size>[@<offset>] [<name>] [ro]\n"
1884         "    - add partition\n"
1885         "mtdparts default\n"
1886         "    - reset partition table to defaults\n\n"
1887         "-----\n\n"
1888         "this command uses three environment variables:\n\n"
1889         "'partition' - keeps current partition identifier\n\n"
1890         "partition  := <part-id>\n"
1891         "<part-id>  := <dev-id>,part_num\n\n"
1892         "'mtdids' - linux kernel mtd device id <-> u-boot device id mapping\n\n"
1893         "mtdids=<idmap>[,<idmap>,...]\n\n"
1894         "<idmap>    := <dev-id>=<mtd-id>\n"
1895         "<dev-id>   := 'nand'|'nor'|'onenand'<dev-num>\n"
1896         "<dev-num>  := mtd device number, 0...\n"
1897         "<mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)\n\n"
1898         "'mtdparts' - partition list\n\n"
1899         "mtdparts=mtdparts=<mtd-def>[;<mtd-def>...]\n\n"
1900         "<mtd-def>  := <mtd-id>:<part-def>[,<part-def>...]\n"
1901         "<mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)\n"
1902         "<part-def> := <size>[@<offset>][<name>][<ro-flag>]\n"
1903         "<size>     := standard linux memsize OR '-' to denote all remaining space\n"
1904         "<offset>   := partition start offset within the device\n"
1905         "<name>     := '(' NAME ')'\n"
1906         "<ro-flag>  := when set to 'ro' makes partition read-only (not used, passed to kernel)"
1907 );
1908 /***************************************************/