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