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