]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - fs/jffs2/jffs2_1pass.c
* Back out Patch by Christian Hohnstaedt, 23 Apr 2004:
[karo-tx-uboot.git] / fs / jffs2 / jffs2_1pass.c
1 /*
2 -------------------------------------------------------------------------
3  * Filename:      jffs2.c
4  * Version:       $Id: jffs2_1pass.c,v 1.7 2002/01/25 01:56:47 nyet Exp $
5  * Copyright:     Copyright (C) 2001, Russ Dill
6  * Author:        Russ Dill <Russ.Dill@asu.edu>
7  * Description:   Module to load kernel from jffs2
8  *-----------------------------------------------------------------------*/
9 /*
10  * some portions of this code are taken from jffs2, and as such, the
11  * following copyright notice is included.
12  *
13  * JFFS2 -- Journalling Flash File System, Version 2.
14  *
15  * Copyright (C) 2001 Red Hat, Inc.
16  *
17  * Created by David Woodhouse <dwmw2@cambridge.redhat.com>
18  *
19  * The original JFFS, from which the design for JFFS2 was derived,
20  * was designed and implemented by Axis Communications AB.
21  *
22  * The contents of this file are subject to the Red Hat eCos Public
23  * License Version 1.1 (the "Licence"); you may not use this file
24  * except in compliance with the Licence.  You may obtain a copy of
25  * the Licence at http://www.redhat.com/
26  *
27  * Software distributed under the Licence is distributed on an "AS IS"
28  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
29  * See the Licence for the specific language governing rights and
30  * limitations under the Licence.
31  *
32  * The Original Code is JFFS2 - Journalling Flash File System, version 2
33  *
34  * Alternatively, the contents of this file may be used under the
35  * terms of the GNU General Public License version 2 (the "GPL"), in
36  * which case the provisions of the GPL are applicable instead of the
37  * above.  If you wish to allow the use of your version of this file
38  * only under the terms of the GPL and not to allow others to use your
39  * version of this file under the RHEPL, indicate your decision by
40  * deleting the provisions above and replace them with the notice and
41  * other provisions required by the GPL.  If you do not delete the
42  * provisions above, a recipient may use your version of this file
43  * under either the RHEPL or the GPL.
44  *
45  * $Id: jffs2_1pass.c,v 1.7 2002/01/25 01:56:47 nyet Exp $
46  *
47  */
48
49 /* Ok, so anyone who knows the jffs2 code will probably want to get a papar
50  * bag to throw up into before reading this code. I looked through the jffs2
51  * code, the caching scheme is very elegant. I tried to keep the version
52  * for a bootloader as small and simple as possible. Instead of worring about
53  * unneccesary data copies, node scans, etc, I just optimized for the known
54  * common case, a kernel, which looks like:
55  *      (1) most pages are 4096 bytes
56  *      (2) version numbers are somewhat sorted in acsending order
57  *      (3) multiple compressed blocks making up one page is uncommon
58  *
59  * So I create a linked list of decending version numbers (insertions at the
60  * head), and then for each page, walk down the list, until a matching page
61  * with 4096 bytes is found, and then decompress the watching pages in
62  * reverse order.
63  *
64  */
65
66 /*
67  * Adapted by Nye Liu <nyet@zumanetworks.com> and
68  * Rex Feany <rfeany@zumanetworks.com>
69  * on Jan/2002 for U-Boot.
70  *
71  * Clipped out all the non-1pass functions, cleaned up warnings,
72  * wrappers, etc. No major changes to the code.
73  * Please, he really means it when he said have a paper bag
74  * handy. We needed it ;).
75  *
76  */
77
78 /*
79  * Bugfixing by Kai-Uwe Bloem <kai-uwe.bloem@auerswald.de>, (C) Mar/2003
80  *
81  * - overhaul of the memory management. Removed much of the "paper-bagging"
82  *   in that part of the code, fixed several bugs, now frees memory when
83  *   partition is changed.
84  *   It's still ugly :-(
85  * - fixed a bug in jffs2_1pass_read_inode where the file length calculation
86  *   was incorrect. Removed a bit of the paper-bagging as well.
87  * - removed double crc calculation for fragment headers in jffs2_private.h
88  *   for speedup.
89  * - scan_empty rewritten in a more "standard" manner (non-paperbag, that is).
90  * - spinning wheel now spins depending on how much memory has been scanned
91  * - lots of small changes all over the place to "improve" readability.
92  * - implemented fragment sorting to ensure that the newest data is copied
93  *   if there are multiple copies of fragments for a certain file offset.
94  *
95  * The fragment sorting feature must be enabled by CFG_JFFS2_SORT_FRAGMENTS.
96  * Sorting is done while adding fragments to the lists, which is more or less a
97  * bubble sort. This takes a lot of time, and is most probably not an issue if
98  * the boot filesystem is always mounted readonly.
99  *
100  * You should define it if the boot filesystem is mounted writable, and updates
101  * to the boot files are done by copying files to that filesystem.
102  *
103  *
104  * There's a big issue left: endianess is completely ignored in this code. Duh!
105  *
106  *
107  * You still should have paper bags at hand :-(. The code lacks more or less
108  * any comment, and is still arcane and difficult to read in places. As this
109  * might be incompatible with any new code from the jffs2 maintainers anyway,
110  * it should probably be dumped and replaced by something like jffs2reader!
111  */
112
113
114 #include <common.h>
115 #include <config.h>
116 #include <malloc.h>
117 #include <linux/stat.h>
118 #include <linux/time.h>
119
120 #if (CONFIG_COMMANDS & CFG_CMD_JFFS2)
121
122 #include <jffs2/jffs2.h>
123 #include <jffs2/jffs2_1pass.h>
124
125 #include "jffs2_private.h"
126
127
128 #define NODE_CHUNK      1024    /* size of memory allocation chunk in b_nodes */
129 #define SPIN_BLKSIZE    18      /* spin after having scanned 1<<BLKSIZE bytes */
130
131 /* Debugging switches */
132 #undef  DEBUG_DIRENTS           /* print directory entry list after scan */
133 #undef  DEBUG_FRAGMENTS         /* print fragment list after scan */
134 #undef  DEBUG                           /* enable debugging messages */
135
136
137 #ifdef  DEBUG
138 # define DEBUGF(fmt,args...)    printf(fmt ,##args)
139 #else
140 # define DEBUGF(fmt,args...)
141 #endif
142
143 #if defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND)
144
145 /*
146  * Support for jffs2 on top of NAND-flash
147  *
148  * NAND memory isn't mapped in processor's address space,
149  * so data should be fetched from flash before
150  * being processed. This is exactly what functions declared
151  * here do.
152  *
153  */
154
155 /* this one defined in cmd_nand.c */
156 int read_jffs2_nand(size_t start, size_t len,
157                     size_t * retlen, u_char * buf, int nanddev);
158
159 #define NAND_PAGE_SIZE 512
160 #define NAND_PAGE_SHIFT 9
161 #define NAND_PAGE_MASK (~(NAND_PAGE_SIZE-1))
162
163 #ifndef NAND_CACHE_PAGES
164 #define NAND_CACHE_PAGES 16
165 #endif
166 #define NAND_CACHE_SIZE (NAND_CACHE_PAGES*NAND_PAGE_SIZE)
167
168 static u8* nand_cache = NULL;
169 static u32 nand_cache_off = (u32)-1;
170 static int nanddev = 0; /* nand device of current partition */
171
172 static int read_nand_cached(u32 off, u32 size, u_char *buf)
173 {
174         u32 bytes_read = 0;
175         size_t retlen;
176         int cpy_bytes;
177
178         while (bytes_read < size) {
179                 if ((off + bytes_read < nand_cache_off) ||
180                     (off + bytes_read >= nand_cache_off+NAND_CACHE_SIZE)) {
181                         nand_cache_off = (off + bytes_read) & NAND_PAGE_MASK;
182                         if (!nand_cache) {
183                                 /* This memory never gets freed but 'cause
184                                    it's a bootloader, nobody cares */
185                                 nand_cache = malloc(NAND_CACHE_SIZE);
186                                 if (!nand_cache) {
187                                         printf("read_nand_cached: can't alloc cache size %d bytes\n",
188                                                NAND_CACHE_SIZE);
189                                         return -1;
190                                 }
191                         }
192                         if (read_jffs2_nand(nand_cache_off, NAND_CACHE_SIZE,
193                                             &retlen, nand_cache, nanddev) < 0 ||
194                             retlen != NAND_CACHE_SIZE) {
195                                 printf("read_nand_cached: error reading nand off %#x size %d bytes\n",
196                                        nand_cache_off, NAND_CACHE_SIZE);
197                                 return -1;
198                         }
199                 }
200                 cpy_bytes = nand_cache_off + NAND_CACHE_SIZE - (off + bytes_read);
201                 if (cpy_bytes > size - bytes_read)
202                         cpy_bytes = size - bytes_read;
203                 memcpy(buf + bytes_read,
204                        nand_cache + off + bytes_read - nand_cache_off,
205                        cpy_bytes);
206                 bytes_read += cpy_bytes;
207         }
208         return bytes_read;
209 }
210
211 static void *get_fl_mem(u32 off, u32 size, void *ext_buf)
212 {
213         u_char *buf = ext_buf ? (u_char*)ext_buf : (u_char*)malloc(size);
214
215         if (NULL == buf) {
216                 printf("get_fl_mem: can't alloc %d bytes\n", size);
217                 return NULL;
218         }
219         if (read_nand_cached(off, size, buf) < 0) {
220                 free(buf);
221                 return NULL;
222         }
223
224         return buf;
225 }
226
227 static void *get_node_mem(u32 off)
228 {
229         struct jffs2_unknown_node node;
230         void *ret = NULL;
231
232         if (NULL == get_fl_mem(off, sizeof(node), &node))
233                 return NULL;
234
235         if (!(ret = get_fl_mem(off, node.magic ==
236                                JFFS2_MAGIC_BITMASK ? node.totlen : sizeof(node),
237                                NULL))) {
238                 printf("off = %#x magic %#x type %#x node.totlen = %d\n",
239                        off, node.magic, node.nodetype, node.totlen);
240         }
241         return ret;
242 }
243
244 static void put_fl_mem(void *buf)
245 {
246         free(buf);
247 }
248
249 #else /* defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND) */
250
251 static inline void *get_fl_mem(u32 off, u32 size, void *ext_buf)
252 {
253         return (void*)off;
254 }
255
256 static inline void *get_node_mem(u32 off)
257 {
258         return (void*)off;
259 }
260
261 static inline void put_fl_mem(void *buf)
262 {
263 }
264
265 #endif /* defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND) */
266
267
268 /* Compression names */
269 static char *compr_names[] = {
270         "NONE",
271         "ZERO",
272         "RTIME",
273         "RUBINMIPS",
274         "COPY",
275         "DYNRUBIN",
276         "ZLIB"
277 };
278
279 /* Spinning wheel */
280 static char spinner[] = { '|', '/', '-', '\\' };
281
282 /* Memory management */
283 struct mem_block {
284         u32     index;
285         struct mem_block *next;
286         struct b_node nodes[NODE_CHUNK];
287 };
288
289
290 static void
291 free_nodes(struct b_list *list)
292 {
293         while (list->listMemBase != NULL) {
294                 struct mem_block *next = list->listMemBase->next;
295                 free( list->listMemBase );
296                 list->listMemBase = next;
297         }
298 }
299
300 static struct b_node *
301 add_node(struct b_list *list)
302 {
303         u32 index = 0;
304         struct mem_block *memBase;
305         struct b_node *b;
306
307         memBase = list->listMemBase;
308         if (memBase != NULL)
309                 index = memBase->index;
310 #if 0
311         putLabeledWord("add_node: index = ", index);
312         putLabeledWord("add_node: memBase = ", list->listMemBase);
313 #endif
314
315         if (memBase == NULL || index >= NODE_CHUNK) {
316                 /* we need more space before we continue */
317                 memBase = mmalloc(sizeof(struct mem_block));
318                 if (memBase == NULL) {
319                         putstr("add_node: malloc failed\n");
320                         return NULL;
321                 }
322                 memBase->next = list->listMemBase;
323                 index = 0;
324 #if 0
325                 putLabeledWord("add_node: alloced a new membase at ", *memBase);
326 #endif
327
328         }
329         /* now we have room to add it. */
330         b = &memBase->nodes[index];
331         index ++;
332
333         memBase->index = index;
334         list->listMemBase = memBase;
335         list->listCount++;
336         return b;
337 }
338
339 static struct b_node *
340 insert_node(struct b_list *list, u32 offset)
341 {
342         struct b_node *new;
343 #ifdef CFG_JFFS2_SORT_FRAGMENTS
344         struct b_node *b, *prev;
345 #endif
346
347         if (!(new = add_node(list))) {
348                 putstr("add_node failed!\r\n");
349                 return NULL;
350         }
351         new->offset = offset;
352
353 #ifdef CFG_JFFS2_SORT_FRAGMENTS
354         if (list->listTail != NULL && list->listCompare(new, list->listTail))
355                 prev = list->listTail;
356         else if (list->listLast != NULL && list->listCompare(new, list->listLast))
357                 prev = list->listLast;
358         else
359                 prev = NULL;
360
361         for (b = (prev ? prev->next : list->listHead);
362              b != NULL && list->listCompare(new, b);
363              prev = b, b = b->next) {
364                 list->listLoops++;
365         }
366         if (b != NULL)
367                 list->listLast = prev;
368
369         if (b != NULL) {
370                 new->next = b;
371                 if (prev != NULL)
372                         prev->next = new;
373                 else
374                         list->listHead = new;
375         } else
376 #endif
377         {
378                 new->next = (struct b_node *) NULL;
379                 if (list->listTail != NULL) {
380                         list->listTail->next = new;
381                         list->listTail = new;
382                 } else {
383                         list->listTail = list->listHead = new;
384                 }
385         }
386
387         return new;
388 }
389
390 #ifdef CFG_JFFS2_SORT_FRAGMENTS
391 /* Sort data entries with the latest version last, so that if there
392  * is overlapping data the latest version will be used.
393  */
394 static int compare_inodes(struct b_node *new, struct b_node *old)
395 {
396         struct jffs2_raw_inode ojNew;
397         struct jffs2_raw_inode ojOld;
398         struct jffs2_raw_inode *jNew =
399                 (struct jffs2_raw_inode *)get_fl_mem(new->offset, sizeof(ojNew), &ojNew);
400         struct jffs2_raw_inode *jOld =
401                 (struct jffs2_raw_inode *)get_fl_mem(old->offset, sizeof(ojOld), &ojOld);
402
403         return jNew->version > jOld->version;
404 }
405
406 /* Sort directory entries so all entries in the same directory
407  * with the same name are grouped together, with the latest version
408  * last. This makes it easy to eliminate all but the latest version
409  * by marking the previous version dead by setting the inode to 0.
410  */
411 static int compare_dirents(struct b_node *new, struct b_node *old)
412 {
413         struct jffs2_raw_dirent ojNew;
414         struct jffs2_raw_dirent ojOld;
415         struct jffs2_raw_dirent *jNew =
416                 (struct jffs2_raw_dirent *)get_fl_mem(new->offset, sizeof(ojNew), &ojNew);
417         struct jffs2_raw_dirent *jOld =
418                 (struct jffs2_raw_dirent *)get_fl_mem(old->offset, sizeof(ojOld), &ojOld);
419         int cmp;
420
421         /* ascending sort by pino */
422         if (jNew->pino != jOld->pino)
423                 return jNew->pino > jOld->pino;
424
425         /* pino is the same, so use ascending sort by nsize, so
426          * we don't do strncmp unless we really must.
427          */
428         if (jNew->nsize != jOld->nsize)
429                 return jNew->nsize > jOld->nsize;
430
431         /* length is also the same, so use ascending sort by name
432          */
433         cmp = strncmp(jNew->name, jOld->name, jNew->nsize);
434         if (cmp != 0)
435                 return cmp > 0;
436
437         /* we have duplicate names in this directory, so use ascending
438          * sort by version
439          */
440         if (jNew->version > jOld->version) {
441                 /* since jNew is newer, we know jOld is not valid, so
442                  * mark it with inode 0 and it will not be used
443                  */
444                 jOld->ino = 0;
445                 return 1;
446         }
447
448         return 0;
449 }
450 #endif
451
452 static u32
453 jffs2_scan_empty(u32 start_offset, struct part_info *part)
454 {
455         char *max = part->offset + part->size - sizeof(struct jffs2_raw_inode);
456         char *offset = part->offset + start_offset;
457         u32 off;
458
459         while (offset < max &&
460                *(u32*)get_fl_mem((u32)offset, sizeof(u32), &off) == 0xFFFFFFFF) {
461                 offset += sizeof(u32);
462                 /* return if spinning is due */
463                 if (((u32)offset & ((1 << SPIN_BLKSIZE)-1)) == 0) break;
464         }
465
466         return offset - part->offset;
467 }
468
469 static u32
470 jffs_init_1pass_list(struct part_info *part)
471 {
472         struct b_lists *pL;
473
474         if (part->jffs2_priv != NULL) {
475                 pL = (struct b_lists *)part->jffs2_priv;
476                 free_nodes(&pL->frag);
477                 free_nodes(&pL->dir);
478                 free(pL);
479         }
480         if (NULL != (part->jffs2_priv = malloc(sizeof(struct b_lists)))) {
481                 pL = (struct b_lists *)part->jffs2_priv;
482
483                 memset(pL, 0, sizeof(*pL));
484 #ifdef CFG_JFFS2_SORT_FRAGMENTS
485                 pL->dir.listCompare = compare_dirents;
486                 pL->frag.listCompare = compare_inodes;
487 #endif
488         }
489         return 0;
490 }
491
492 /* find the inode from the slashless name given a parent */
493 static long
494 jffs2_1pass_read_inode(struct b_lists *pL, u32 inode, char *dest)
495 {
496         struct b_node *b;
497         struct jffs2_raw_inode *jNode;
498         u32 totalSize = 0;
499         u32 latestVersion = 0;
500         char *lDest;
501         char *src;
502         long ret;
503         int i;
504         u32 counter = 0;
505 #ifdef CFG_JFFS2_SORT_FRAGMENTS
506         /* Find file size before loading any data, so fragments that
507          * start past the end of file can be ignored. A fragment
508          * that is partially in the file is loaded, so extra data may
509          * be loaded up to the next 4K boundary above the file size.
510          * This shouldn't cause trouble when loading kernel images, so
511          * we will live with it.
512          */
513         for (b = pL->frag.listHead; b != NULL; b = b->next) {
514                 jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset,
515                         sizeof(struct jffs2_raw_inode), NULL);
516                 if ((inode == jNode->ino)) {
517                         /* get actual file length from the newest node */
518                         if (jNode->version >= latestVersion) {
519                                 totalSize = jNode->isize;
520                                 latestVersion = jNode->version;
521                         }
522                 }
523                 put_fl_mem(jNode);
524         }
525 #endif
526
527         for (b = pL->frag.listHead; b != NULL; b = b->next) {
528                 jNode = (struct jffs2_raw_inode *) get_node_mem(b->offset);
529                 if ((inode == jNode->ino)) {
530 #if 0
531                         putLabeledWord("\r\n\r\nread_inode: totlen = ", jNode->totlen);
532                         putLabeledWord("read_inode: inode = ", jNode->ino);
533                         putLabeledWord("read_inode: version = ", jNode->version);
534                         putLabeledWord("read_inode: isize = ", jNode->isize);
535                         putLabeledWord("read_inode: offset = ", jNode->offset);
536                         putLabeledWord("read_inode: csize = ", jNode->csize);
537                         putLabeledWord("read_inode: dsize = ", jNode->dsize);
538                         putLabeledWord("read_inode: compr = ", jNode->compr);
539                         putLabeledWord("read_inode: usercompr = ", jNode->usercompr);
540                         putLabeledWord("read_inode: flags = ", jNode->flags);
541 #endif
542
543 #ifndef CFG_JFFS2_SORT_FRAGMENTS
544                         /* get actual file length from the newest node */
545                         if (jNode->version >= latestVersion) {
546                                 totalSize = jNode->isize;
547                                 latestVersion = jNode->version;
548                         }
549 #endif
550
551                         if(dest) {
552                                 src = ((char *) jNode) + sizeof(struct jffs2_raw_inode);
553                                 /* ignore data behind latest known EOF */
554                                 if (jNode->offset > totalSize) {
555                                         put_fl_mem(jNode);
556                                         continue;
557                                 }
558
559                                 lDest = (char *) (dest + jNode->offset);
560 #if 0
561                                 putLabeledWord("read_inode: src = ", src);
562                                 putLabeledWord("read_inode: dest = ", lDest);
563 #endif
564                                 switch (jNode->compr) {
565                                 case JFFS2_COMPR_NONE:
566                                         ret = (unsigned long) ldr_memcpy(lDest, src, jNode->dsize);
567                                         break;
568                                 case JFFS2_COMPR_ZERO:
569                                         ret = 0;
570                                         for (i = 0; i < jNode->dsize; i++)
571                                                 *(lDest++) = 0;
572                                         break;
573                                 case JFFS2_COMPR_RTIME:
574                                         ret = 0;
575                                         rtime_decompress(src, lDest, jNode->csize, jNode->dsize);
576                                         break;
577                                 case JFFS2_COMPR_DYNRUBIN:
578                                         /* this is slow but it works */
579                                         ret = 0;
580                                         dynrubin_decompress(src, lDest, jNode->csize, jNode->dsize);
581                                         break;
582                                 case JFFS2_COMPR_ZLIB:
583                                         ret = zlib_decompress(src, lDest, jNode->csize, jNode->dsize);
584                                         break;
585                                 default:
586                                         /* unknown */
587                                         putLabeledWord("UNKOWN COMPRESSION METHOD = ", jNode->compr);
588                                         put_fl_mem(jNode);
589                                         return -1;
590                                         break;
591                                 }
592                         }
593
594 #if 0
595                         putLabeledWord("read_inode: totalSize = ", totalSize);
596                         putLabeledWord("read_inode: compr ret = ", ret);
597 #endif
598                 }
599                 counter++;
600                 put_fl_mem(jNode);
601         }
602
603 #if 0
604         putLabeledWord("read_inode: returning = ", totalSize);
605 #endif
606         return totalSize;
607 }
608
609 /* find the inode from the slashless name given a parent */
610 static u32
611 jffs2_1pass_find_inode(struct b_lists * pL, const char *name, u32 pino)
612 {
613         struct b_node *b;
614         struct jffs2_raw_dirent *jDir;
615         int len;
616         u32 counter;
617         u32 version = 0;
618         u32 inode = 0;
619
620         /* name is assumed slash free */
621         len = strlen(name);
622
623         counter = 0;
624         /* we need to search all and return the inode with the highest version */
625         for(b = pL->dir.listHead; b; b = b->next, counter++) {
626                 jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset);
627                 if ((pino == jDir->pino) && (len == jDir->nsize) &&
628                     (jDir->ino) &&      /* 0 for unlink */
629                     (!strncmp(jDir->name, name, len))) {        /* a match */
630                         if (jDir->version < version) {
631                                 put_fl_mem(jDir);
632                                 continue;
633                         }
634
635                         if (jDir->version == version && inode != 0) {
636                                 /* I'm pretty sure this isn't legal */
637                                 putstr(" ** ERROR ** ");
638                                 putnstr(jDir->name, jDir->nsize);
639                                 putLabeledWord(" has dup version =", version);
640                         }
641                         inode = jDir->ino;
642                         version = jDir->version;
643                 }
644 #if 0
645                 putstr("\r\nfind_inode:p&l ->");
646                 putnstr(jDir->name, jDir->nsize);
647                 putstr("\r\n");
648                 putLabeledWord("pino = ", jDir->pino);
649                 putLabeledWord("nsize = ", jDir->nsize);
650                 putLabeledWord("b = ", (u32) b);
651                 putLabeledWord("counter = ", counter);
652 #endif
653                 put_fl_mem(jDir);
654         }
655         return inode;
656 }
657
658 char *mkmodestr(unsigned long mode, char *str)
659 {
660         static const char *l = "xwr";
661         int mask = 1, i;
662         char c;
663
664         switch (mode & S_IFMT) {
665                 case S_IFDIR:    str[0] = 'd'; break;
666                 case S_IFBLK:    str[0] = 'b'; break;
667                 case S_IFCHR:    str[0] = 'c'; break;
668                 case S_IFIFO:    str[0] = 'f'; break;
669                 case S_IFLNK:    str[0] = 'l'; break;
670                 case S_IFSOCK:   str[0] = 's'; break;
671                 case S_IFREG:    str[0] = '-'; break;
672                 default:         str[0] = '?';
673         }
674
675         for(i = 0; i < 9; i++) {
676                 c = l[i%3];
677                 str[9-i] = (mode & mask)?c:'-';
678                 mask = mask<<1;
679         }
680
681         if(mode & S_ISUID) str[3] = (mode & S_IXUSR)?'s':'S';
682         if(mode & S_ISGID) str[6] = (mode & S_IXGRP)?'s':'S';
683         if(mode & S_ISVTX) str[9] = (mode & S_IXOTH)?'t':'T';
684         str[10] = '\0';
685         return str;
686 }
687
688 static inline void dump_stat(struct stat *st, const char *name)
689 {
690         char str[20];
691         char s[64], *p;
692
693         if (st->st_mtime == (time_t)(-1)) /* some ctimes really hate -1 */
694                 st->st_mtime = 1;
695
696         ctime_r(&st->st_mtime, s/*,64*/); /* newlib ctime doesn't have buflen */
697
698         if ((p = strchr(s,'\n')) != NULL) *p = '\0';
699         if ((p = strchr(s,'\r')) != NULL) *p = '\0';
700
701 /*
702         printf("%6lo %s %8ld %s %s\n", st->st_mode, mkmodestr(st->st_mode, str),
703                 st->st_size, s, name);
704 */
705
706         printf(" %s %8ld %s %s", mkmodestr(st->st_mode,str), st->st_size, s, name);
707 }
708
709 static inline u32 dump_inode(struct b_lists * pL, struct jffs2_raw_dirent *d, struct jffs2_raw_inode *i)
710 {
711         char fname[256];
712         struct stat st;
713
714         if(!d || !i) return -1;
715
716         strncpy(fname, d->name, d->nsize);
717         fname[d->nsize] = '\0';
718
719         memset(&st,0,sizeof(st));
720
721         st.st_mtime = i->mtime;
722         st.st_mode = i->mode;
723         st.st_ino = i->ino;
724
725         /* neither dsize nor isize help us.. do it the long way */
726         st.st_size = jffs2_1pass_read_inode(pL, i->ino, NULL);
727
728         dump_stat(&st, fname);
729
730         if (d->type == DT_LNK) {
731                 unsigned char *src = (unsigned char *) (&i[1]);
732                 putstr(" -> ");
733                 putnstr(src, (int)i->dsize);
734         }
735
736         putstr("\r\n");
737
738         return 0;
739 }
740
741 /* list inodes with the given pino */
742 static u32
743 jffs2_1pass_list_inodes(struct b_lists * pL, u32 pino)
744 {
745         struct b_node *b;
746         struct jffs2_raw_dirent *jDir;
747
748         for (b = pL->dir.listHead; b; b = b->next) {
749                 jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset);
750                 if ((pino == jDir->pino) && (jDir->ino)) { /* ino=0 -> unlink */
751                         u32 i_version = 0;
752                         struct jffs2_raw_inode ojNode;
753                         struct jffs2_raw_inode *jNode, *i = NULL;
754                         struct b_node *b2 = pL->frag.listHead;
755
756                         while (b2) {
757                                 jNode = (struct jffs2_raw_inode *)
758                                         get_fl_mem(b2->offset, sizeof(ojNode), &ojNode);
759                                 if (jNode->ino == jDir->ino
760                                     && jNode->version >= i_version)
761                                         i = get_fl_mem(b2->offset, sizeof(*i), NULL);
762                                 b2 = b2->next;
763                         }
764
765                         dump_inode(pL, jDir, i);
766                         put_fl_mem(i);
767                 }
768                 put_fl_mem(jDir);
769         }
770         return pino;
771 }
772
773 static u32
774 jffs2_1pass_search_inode(struct b_lists * pL, const char *fname, u32 pino)
775 {
776         int i;
777         char tmp[256];
778         char working_tmp[256];
779         char *c;
780
781         /* discard any leading slash */
782         i = 0;
783         while (fname[i] == '/')
784                 i++;
785         strcpy(tmp, &fname[i]);
786
787         while ((c = (char *) strchr(tmp, '/'))) /* we are still dired searching */
788         {
789                 strncpy(working_tmp, tmp, c - tmp);
790                 working_tmp[c - tmp] = '\0';
791 #if 0
792                 putstr("search_inode: tmp = ");
793                 putstr(tmp);
794                 putstr("\r\n");
795                 putstr("search_inode: wtmp = ");
796                 putstr(working_tmp);
797                 putstr("\r\n");
798                 putstr("search_inode: c = ");
799                 putstr(c);
800                 putstr("\r\n");
801 #endif
802                 for (i = 0; i < strlen(c) - 1; i++)
803                         tmp[i] = c[i + 1];
804                 tmp[i] = '\0';
805 #if 0
806                 putstr("search_inode: post tmp = ");
807                 putstr(tmp);
808                 putstr("\r\n");
809 #endif
810
811                 if (!(pino = jffs2_1pass_find_inode(pL, working_tmp, pino))) {
812                         putstr("find_inode failed for name=");
813                         putstr(working_tmp);
814                         putstr("\r\n");
815                         return 0;
816                 }
817         }
818         /* this is for the bare filename, directories have already been mapped */
819         if (!(pino = jffs2_1pass_find_inode(pL, tmp, pino))) {
820                 putstr("find_inode failed for name=");
821                 putstr(tmp);
822                 putstr("\r\n");
823                 return 0;
824         }
825         return pino;
826
827 }
828
829 static u32
830 jffs2_1pass_resolve_inode(struct b_lists * pL, u32 ino)
831 {
832         struct b_node *b;
833         struct b_node *b2;
834         struct jffs2_raw_dirent *jDir;
835         struct jffs2_raw_inode *jNode;
836         u8 jDirFoundType = 0;
837         u32 jDirFoundIno = 0;
838         u32 jDirFoundPino = 0;
839         char tmp[256];
840         u32 version = 0;
841         u32 pino;
842         unsigned char *src;
843
844         /* we need to search all and return the inode with the highest version */
845         for(b = pL->dir.listHead; b; b = b->next) {
846                 jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset);
847                 if (ino == jDir->ino) {
848                         if (jDir->version < version) {
849                                 put_fl_mem(jDir);
850                                 continue;
851                         }
852
853                         if (jDir->version == version && jDirFoundType) {
854                                 /* I'm pretty sure this isn't legal */
855                                 putstr(" ** ERROR ** ");
856                                 putnstr(jDir->name, jDir->nsize);
857                                 putLabeledWord(" has dup version (resolve) = ",
858                                         version);
859                         }
860
861                         jDirFoundType = jDir->type;
862                         jDirFoundIno = jDir->ino;
863                         jDirFoundPino = jDir->pino;
864                         version = jDir->version;
865                 }
866                 put_fl_mem(jDir);
867         }
868         /* now we found the right entry again. (shoulda returned inode*) */
869         if (jDirFoundType != DT_LNK)
870                 return jDirFoundIno;
871
872         /* it's a soft link so we follow it again. */
873         b2 = pL->frag.listHead;
874         while (b2) {
875                 jNode = (struct jffs2_raw_inode *) get_node_mem(b2->offset);
876                 if (jNode->ino == jDirFoundIno) {
877                         src = (unsigned char *) (b2->offset + sizeof(struct jffs2_raw_inode));
878
879 #if 0
880                         putLabeledWord("\t\t dsize = ", jNode->dsize);
881                         putstr("\t\t target = ");
882                         putnstr(src, jNode->dsize);
883                         putstr("\r\n");
884 #endif
885                         strncpy(tmp, src, jNode->dsize);
886                         tmp[jNode->dsize] = '\0';
887                         put_fl_mem(jNode);
888                         break;
889                 }
890                 b2 = b2->next;
891                 put_fl_mem(jNode);
892         }
893         /* ok so the name of the new file to find is in tmp */
894         /* if it starts with a slash it is root based else shared dirs */
895         if (tmp[0] == '/')
896                 pino = 1;
897         else
898                 pino = jDirFoundPino;
899
900         return jffs2_1pass_search_inode(pL, tmp, pino);
901 }
902
903 static u32
904 jffs2_1pass_search_list_inodes(struct b_lists * pL, const char *fname, u32 pino)
905 {
906         int i;
907         char tmp[256];
908         char working_tmp[256];
909         char *c;
910
911         /* discard any leading slash */
912         i = 0;
913         while (fname[i] == '/')
914                 i++;
915         strcpy(tmp, &fname[i]);
916         working_tmp[0] = '\0';
917         while ((c = (char *) strchr(tmp, '/'))) /* we are still dired searching */
918         {
919                 strncpy(working_tmp, tmp, c - tmp);
920                 working_tmp[c - tmp] = '\0';
921                 for (i = 0; i < strlen(c) - 1; i++)
922                         tmp[i] = c[i + 1];
923                 tmp[i] = '\0';
924                 /* only a failure if we arent looking at top level */
925                 if (!(pino = jffs2_1pass_find_inode(pL, working_tmp, pino)) &&
926                     (working_tmp[0])) {
927                         putstr("find_inode failed for name=");
928                         putstr(working_tmp);
929                         putstr("\r\n");
930                         return 0;
931                 }
932         }
933
934         if (tmp[0] && !(pino = jffs2_1pass_find_inode(pL, tmp, pino))) {
935                 putstr("find_inode failed for name=");
936                 putstr(tmp);
937                 putstr("\r\n");
938                 return 0;
939         }
940         /* this is for the bare filename, directories have already been mapped */
941         if (!(pino = jffs2_1pass_list_inodes(pL, pino))) {
942                 putstr("find_inode failed for name=");
943                 putstr(tmp);
944                 putstr("\r\n");
945                 return 0;
946         }
947         return pino;
948
949 }
950
951 unsigned char
952 jffs2_1pass_rescan_needed(struct part_info *part)
953 {
954         struct b_node *b;
955         struct jffs2_unknown_node onode;
956         struct jffs2_unknown_node *node;
957         struct b_lists *pL = (struct b_lists *)part->jffs2_priv;
958
959         if (part->jffs2_priv == 0){
960                 DEBUGF ("rescan: First time in use\n");
961                 return 1;
962         }
963         /* if we have no list, we need to rescan */
964         if (pL->frag.listCount == 0) {
965                 DEBUGF ("rescan: fraglist zero\n");
966                 return 1;
967         }
968
969         /* or if we are scanning a new partition */
970         if (pL->partOffset != part->offset) {
971                 DEBUGF ("rescan: different partition\n");
972                 return 1;
973         }
974
975 #if defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND)
976         if (nanddev != (int)part->usr_priv - 1) {
977                 DEBUGF ("rescan: nand device changed\n");
978                 return -1;
979         }
980 #endif /* defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND) */
981
982         /* but suppose someone reflashed a partition at the same offset... */
983         b = pL->dir.listHead;
984         while (b) {
985                 node = (struct jffs2_unknown_node *) get_fl_mem(b->offset,
986                         sizeof(onode), &onode);
987                 if (node->nodetype != JFFS2_NODETYPE_DIRENT) {
988                         DEBUGF ("rescan: fs changed beneath me? (%lx)\n",
989                                         (unsigned long) b->offset);
990                         return 1;
991                 }
992                 b = b->next;
993         }
994         return 0;
995 }
996
997 #ifdef DEBUG_FRAGMENTS
998 static void
999 dump_fragments(struct b_lists *pL)
1000 {
1001         struct b_node *b;
1002         struct jffs2_raw_inode ojNode;
1003         struct jffs2_raw_inode *jNode;
1004
1005         putstr("\r\n\r\n******The fragment Entries******\r\n");
1006         b = pL->frag.listHead;
1007         while (b) {
1008                 jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset,
1009                         sizeof(ojNode), &ojNode);
1010                 putLabeledWord("\r\n\tbuild_list: FLASH_OFFSET = ", b->offset);
1011                 putLabeledWord("\tbuild_list: totlen = ", jNode->totlen);
1012                 putLabeledWord("\tbuild_list: inode = ", jNode->ino);
1013                 putLabeledWord("\tbuild_list: version = ", jNode->version);
1014                 putLabeledWord("\tbuild_list: isize = ", jNode->isize);
1015                 putLabeledWord("\tbuild_list: atime = ", jNode->atime);
1016                 putLabeledWord("\tbuild_list: offset = ", jNode->offset);
1017                 putLabeledWord("\tbuild_list: csize = ", jNode->csize);
1018                 putLabeledWord("\tbuild_list: dsize = ", jNode->dsize);
1019                 putLabeledWord("\tbuild_list: compr = ", jNode->compr);
1020                 putLabeledWord("\tbuild_list: usercompr = ", jNode->usercompr);
1021                 putLabeledWord("\tbuild_list: flags = ", jNode->flags);
1022                 putLabeledWord("\tbuild_list: offset = ", b->offset);   /* FIXME: ? [RS] */
1023                 b = b->next;
1024         }
1025 }
1026 #endif
1027
1028 #ifdef DEBUG_DIRENTS
1029 static void
1030 dump_dirents(struct b_lists *pL)
1031 {
1032         struct b_node *b;
1033         struct jffs2_raw_dirent *jDir;
1034
1035         putstr("\r\n\r\n******The directory Entries******\r\n");
1036         b = pL->dir.listHead;
1037         while (b) {
1038                 jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset);
1039                 putstr("\r\n");
1040                 putnstr(jDir->name, jDir->nsize);
1041                 putLabeledWord("\r\n\tbuild_list: magic = ", jDir->magic);
1042                 putLabeledWord("\tbuild_list: nodetype = ", jDir->nodetype);
1043                 putLabeledWord("\tbuild_list: hdr_crc = ", jDir->hdr_crc);
1044                 putLabeledWord("\tbuild_list: pino = ", jDir->pino);
1045                 putLabeledWord("\tbuild_list: version = ", jDir->version);
1046                 putLabeledWord("\tbuild_list: ino = ", jDir->ino);
1047                 putLabeledWord("\tbuild_list: mctime = ", jDir->mctime);
1048                 putLabeledWord("\tbuild_list: nsize = ", jDir->nsize);
1049                 putLabeledWord("\tbuild_list: type = ", jDir->type);
1050                 putLabeledWord("\tbuild_list: node_crc = ", jDir->node_crc);
1051                 putLabeledWord("\tbuild_list: name_crc = ", jDir->name_crc);
1052                 putLabeledWord("\tbuild_list: offset = ", b->offset);   /* FIXME: ? [RS] */
1053                 b = b->next;
1054                 put_fl_mem(jDir);
1055         }
1056 }
1057 #endif
1058
1059 static u32
1060 jffs2_1pass_build_lists(struct part_info * part)
1061 {
1062         struct b_lists *pL;
1063         struct jffs2_unknown_node *node;
1064         u32 offset, oldoffset = 0;
1065         u32 max = part->size - sizeof(struct jffs2_raw_inode);
1066         u32 counter = 0;
1067         u32 counter4 = 0;
1068         u32 counterF = 0;
1069         u32 counterN = 0;
1070
1071 #if defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND)
1072         nanddev = (int)part->usr_priv - 1;
1073 #endif /* defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND) */
1074
1075         /* turn off the lcd.  Refreshing the lcd adds 50% overhead to the */
1076         /* jffs2 list building enterprise nope.  in newer versions the overhead is */
1077         /* only about 5 %.  not enough to inconvenience people for. */
1078         /* lcd_off(); */
1079
1080         /* if we are building a list we need to refresh the cache. */
1081         jffs_init_1pass_list(part);
1082         pL = (struct b_lists *)part->jffs2_priv;
1083         pL->partOffset = part->offset;
1084         offset = 0;
1085         puts ("Scanning JFFS2 FS:   ");
1086
1087         /* start at the beginning of the partition */
1088         while (offset < max) {
1089                 if ((oldoffset >> SPIN_BLKSIZE) != (offset >> SPIN_BLKSIZE)) {
1090                         printf("\b\b%c ", spinner[counter++ % sizeof(spinner)]);
1091                         oldoffset = offset;
1092                 }
1093
1094                 node = (struct jffs2_unknown_node *) get_node_mem((u32)part->offset + offset);
1095                 if (node->magic == JFFS2_MAGIC_BITMASK && hdr_crc(node)) {
1096                         /* if its a fragment add it */
1097                         if (node->nodetype == JFFS2_NODETYPE_INODE &&
1098                                     inode_crc((struct jffs2_raw_inode *) node)) {
1099                                 if (insert_node(&pL->frag, (u32) part->offset +
1100                                                 offset) == NULL) {
1101                                         put_fl_mem(node);
1102                                         return 0;
1103                                 }
1104                         } else if (node->nodetype == JFFS2_NODETYPE_DIRENT &&
1105                                    dirent_crc((struct jffs2_raw_dirent *) node)  &&
1106                                    dirent_name_crc((struct jffs2_raw_dirent *) node)) {
1107                                 if (! (counterN%100))
1108                                         puts ("\b\b.  ");
1109                                 if (insert_node(&pL->dir, (u32) part->offset +
1110                                                 offset) == NULL) {
1111                                         put_fl_mem(node);
1112                                         return 0;
1113                                 }
1114                                 counterN++;
1115                         } else if (node->nodetype == JFFS2_NODETYPE_CLEANMARKER) {
1116                                 if (node->totlen != sizeof(struct jffs2_unknown_node))
1117                                         printf("OOPS Cleanmarker has bad size "
1118                                                 "%d != %d\n", node->totlen,
1119                                                 sizeof(struct jffs2_unknown_node));
1120                         } else if (node->nodetype == JFFS2_NODETYPE_PADDING) {
1121                                 if (node->totlen < sizeof(struct jffs2_unknown_node))
1122                                         printf("OOPS Padding has bad size "
1123                                                 "%d < %d\n", node->totlen,
1124                                                 sizeof(struct jffs2_unknown_node));
1125                         } else {
1126                                 printf("Unknown node type: %x len %d "
1127                                         "offset 0x%x\n", node->nodetype,
1128                                         node->totlen, offset);
1129                         }
1130                         offset += ((node->totlen + 3) & ~3);
1131                         counterF++;
1132                 } else if (node->magic == JFFS2_EMPTY_BITMASK &&
1133                            node->nodetype == JFFS2_EMPTY_BITMASK) {
1134                         offset = jffs2_scan_empty(offset, part);
1135                 } else {        /* if we know nothing, we just step and look. */
1136                         offset += 4;
1137                         counter4++;
1138                 }
1139 /*             printf("unknown node magic %4.4x %4.4x @ %lx\n", node->magic, node->nodetype, (unsigned long)node); */
1140                 put_fl_mem(node);
1141         }
1142
1143         putstr("\b\b done.\r\n");               /* close off the dots */
1144         /* turn the lcd back on. */
1145         /* splash(); */
1146
1147 #if 0
1148         putLabeledWord("dir entries = ", pL->dir.listCount);
1149         putLabeledWord("frag entries = ", pL->frag.listCount);
1150         putLabeledWord("+4 increments = ", counter4);
1151         putLabeledWord("+file_offset increments = ", counterF);
1152
1153 #endif
1154
1155 #ifdef DEBUG_DIRENTS
1156         dump_dirents(pL);
1157 #endif
1158
1159 #ifdef DEBUG_FRAGMENTS
1160         dump_fragments(pL);
1161 #endif
1162
1163         /* give visual feedback that we are done scanning the flash */
1164         led_blink(0x0, 0x0, 0x1, 0x1);  /* off, forever, on 100ms, off 100ms */
1165         return 1;
1166 }
1167
1168
1169 static u32
1170 jffs2_1pass_fill_info(struct b_lists * pL, struct b_jffs2_info * piL)
1171 {
1172         struct b_node *b;
1173         struct jffs2_raw_inode ojNode;
1174         struct jffs2_raw_inode *jNode;
1175         int i;
1176
1177         for (i = 0; i < JFFS2_NUM_COMPR; i++) {
1178                 piL->compr_info[i].num_frags = 0;
1179                 piL->compr_info[i].compr_sum = 0;
1180                 piL->compr_info[i].decompr_sum = 0;
1181         }
1182
1183         b = pL->frag.listHead;
1184         while (b) {
1185                 jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset,
1186                         sizeof(ojNode), &ojNode);
1187                 if (jNode->compr < JFFS2_NUM_COMPR) {
1188                         piL->compr_info[jNode->compr].num_frags++;
1189                         piL->compr_info[jNode->compr].compr_sum += jNode->csize;
1190                         piL->compr_info[jNode->compr].decompr_sum += jNode->dsize;
1191                 }
1192                 b = b->next;
1193         }
1194         return 0;
1195 }
1196
1197
1198 static struct b_lists *
1199 jffs2_get_list(struct part_info * part, const char *who)
1200 {
1201         if (jffs2_1pass_rescan_needed(part)) {
1202                 if (!jffs2_1pass_build_lists(part)) {
1203                         printf("%s: Failed to scan JFFSv2 file structure\n", who);
1204                         return NULL;
1205                 }
1206         }
1207         return (struct b_lists *)part->jffs2_priv;
1208 }
1209
1210
1211 /* Print directory / file contents */
1212 u32
1213 jffs2_1pass_ls(struct part_info * part, const char *fname)
1214 {
1215         struct b_lists *pl;
1216         long ret = 0;
1217         u32 inode;
1218
1219         if (! (pl = jffs2_get_list(part, "ls")))
1220                 return 0;
1221
1222         if (! (inode = jffs2_1pass_search_list_inodes(pl, fname, 1))) {
1223                 putstr("ls: Failed to scan jffs2 file structure\r\n");
1224                 return 0;
1225         }
1226
1227
1228 #if 0
1229         putLabeledWord("found file at inode = ", inode);
1230         putLabeledWord("read_inode returns = ", ret);
1231 #endif
1232
1233         return ret;
1234 }
1235
1236
1237 /* Load a file from flash into memory. fname can be a full path */
1238 u32
1239 jffs2_1pass_load(char *dest, struct part_info * part, const char *fname)
1240 {
1241
1242         struct b_lists *pl;
1243         long ret = 0;
1244         u32 inode;
1245
1246         if (! (pl  = jffs2_get_list(part, "load")))
1247                 return 0;
1248
1249         if (! (inode = jffs2_1pass_search_inode(pl, fname, 1))) {
1250                 putstr("load: Failed to find inode\r\n");
1251                 return 0;
1252         }
1253
1254         /* Resolve symlinks */
1255         if (! (inode = jffs2_1pass_resolve_inode(pl, inode))) {
1256                 putstr("load: Failed to resolve inode structure\r\n");
1257                 return 0;
1258         }
1259
1260         if ((ret = jffs2_1pass_read_inode(pl, inode, dest)) < 0) {
1261                 putstr("load: Failed to read inode\r\n");
1262                 return 0;
1263         }
1264
1265         DEBUGF ("load: loaded '%s' to 0x%lx (%ld bytes)\n", fname,
1266                                 (unsigned long) dest, ret);
1267         return ret;
1268 }
1269
1270 /* Return information about the fs on this partition */
1271 u32
1272 jffs2_1pass_info(struct part_info * part)
1273 {
1274         struct b_jffs2_info info;
1275         struct b_lists *pl;
1276         int i;
1277
1278         if (! (pl  = jffs2_get_list(part, "info")))
1279                 return 0;
1280
1281         jffs2_1pass_fill_info(pl, &info);
1282         for (i = 0; i < JFFS2_NUM_COMPR; i++) {
1283                 printf ("Compression: %s\n"
1284                         "\tfrag count: %d\n"
1285                         "\tcompressed sum: %d\n"
1286                         "\tuncompressed sum: %d\n",
1287                         compr_names[i],
1288                         info.compr_info[i].num_frags,
1289                         info.compr_info[i].compr_sum,
1290                         info.compr_info[i].decompr_sum);
1291         }
1292         return 1;
1293 }
1294
1295 #endif /* CFG_CMD_JFFS2 */