Merge branch 'next' of git://git.denx.de/u-boot-avr32
[kernel/u-boot.git] / drivers / mtd / nand / nand_util.c
1 /*
2  * drivers/mtd/nand/nand_util.c
3  *
4  * Copyright (C) 2006 by Weiss-Electronic GmbH.
5  * All rights reserved.
6  *
7  * @author:     Guido Classen <clagix@gmail.com>
8  * @descr:      NAND Flash support
9  * @references: borrowed heavily from Linux mtd-utils code:
10  *              flash_eraseall.c by Arcom Control System Ltd
11  *              nandwrite.c by Steven J. Hill (sjhill@realitydiluted.com)
12  *                             and Thomas Gleixner (tglx@linutronix.de)
13  *
14  * See file CREDITS for list of people who contributed to this
15  * project.
16  *
17  * This program is free software; you can redistribute it and/or
18  * modify it under the terms of the GNU General Public License version
19  * 2 as published by the Free Software Foundation.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, write to the Free Software
28  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
29  * MA 02111-1307 USA
30  *
31  */
32
33 #include <common.h>
34 #include <command.h>
35 #include <watchdog.h>
36 #include <malloc.h>
37 #include <div64.h>
38
39
40 #include <asm/errno.h>
41 #include <linux/mtd/mtd.h>
42 #include <nand.h>
43 #include <jffs2/jffs2.h>
44
45 typedef struct erase_info erase_info_t;
46 typedef struct mtd_info   mtd_info_t;
47
48 /* support only for native endian JFFS2 */
49 #define cpu_to_je16(x) (x)
50 #define cpu_to_je32(x) (x)
51
52 /*****************************************************************************/
53 static int nand_block_bad_scrub(struct mtd_info *mtd, loff_t ofs, int getchip)
54 {
55         return 0;
56 }
57
58 /**
59  * nand_erase_opts: - erase NAND flash with support for various options
60  *                    (jffs2 formating)
61  *
62  * @param meminfo       NAND device to erase
63  * @param opts          options,  @see struct nand_erase_options
64  * @return              0 in case of success
65  *
66  * This code is ported from flash_eraseall.c from Linux mtd utils by
67  * Arcom Control System Ltd.
68  */
69 int nand_erase_opts(nand_info_t *meminfo, const nand_erase_options_t *opts)
70 {
71         struct jffs2_unknown_node cleanmarker;
72         erase_info_t erase;
73         ulong erase_length;
74         int bbtest = 1;
75         int result;
76         int percent_complete = -1;
77         int (*nand_block_bad_old)(struct mtd_info *, loff_t, int) = NULL;
78         const char *mtd_device = meminfo->name;
79         struct mtd_oob_ops oob_opts;
80         struct nand_chip *chip = meminfo->priv;
81         uint8_t buf[64];
82
83         memset(buf, 0, sizeof(buf));
84         memset(&erase, 0, sizeof(erase));
85         memset(&oob_opts, 0, sizeof(oob_opts));
86
87         erase.mtd = meminfo;
88         erase.len  = meminfo->erasesize;
89         erase.addr = opts->offset;
90         erase_length = opts->length;
91
92
93         cleanmarker.magic = cpu_to_je16 (JFFS2_MAGIC_BITMASK);
94         cleanmarker.nodetype = cpu_to_je16 (JFFS2_NODETYPE_CLEANMARKER);
95         cleanmarker.totlen = cpu_to_je32(8);
96         cleanmarker.hdr_crc = cpu_to_je32(
97         crc32_no_comp(0, (unsigned char *) &cleanmarker,
98         sizeof(struct jffs2_unknown_node) - 4));
99
100         /* scrub option allows to erase badblock. To prevent internal
101          * check from erase() method, set block check method to dummy
102          * and disable bad block table while erasing.
103          */
104         if (opts->scrub) {
105                 struct nand_chip *priv_nand = meminfo->priv;
106
107                 nand_block_bad_old = priv_nand->block_bad;
108                 priv_nand->block_bad = nand_block_bad_scrub;
109                 /* we don't need the bad block table anymore...
110                  * after scrub, there are no bad blocks left!
111                  */
112                 if (priv_nand->bbt) {
113                         kfree(priv_nand->bbt);
114                 }
115                 priv_nand->bbt = NULL;
116         }
117
118         if (erase_length < meminfo->erasesize) {
119                 printf("Warning: Erase size 0x%08lx smaller than one "  \
120                        "erase block 0x%08x\n",erase_length, meminfo->erasesize);
121                 printf("         Erasing 0x%08x instead\n", meminfo->erasesize);
122                 erase_length = meminfo->erasesize;
123         }
124
125         for (;
126              erase.addr < opts->offset + erase_length;
127              erase.addr += meminfo->erasesize) {
128
129                 WATCHDOG_RESET ();
130
131                 if (!opts->scrub && bbtest) {
132                         int ret = meminfo->block_isbad(meminfo, erase.addr);
133                         if (ret > 0) {
134                                 if (!opts->quiet)
135                                         printf("\rSkipping bad block at  "
136                                                "0x%08x                   "
137                                                "                         \n",
138                                                erase.addr);
139                                 continue;
140
141                         } else if (ret < 0) {
142                                 printf("\n%s: MTD get bad block failed: %d\n",
143                                        mtd_device,
144                                        ret);
145                                 return -1;
146                         }
147                 }
148
149                 result = meminfo->erase(meminfo, &erase);
150                 if (result != 0) {
151                         printf("\n%s: MTD Erase failure: %d\n",
152                                mtd_device, result);
153                         continue;
154                 }
155
156                 /* format for JFFS2 ? */
157                 if (opts->jffs2) {
158
159                         chip->ops.len = chip->ops.ooblen = 64;
160                         chip->ops.datbuf = NULL;
161                         chip->ops.oobbuf = buf;
162                         chip->ops.ooboffs = chip->badblockpos & ~0x01;
163
164                         result = meminfo->write_oob(meminfo,
165                                                         erase.addr + meminfo->oobsize,
166                                                         &chip->ops);
167                         if (result != 0) {
168                                 printf("\n%s: MTD writeoob failure: %d\n",
169                                 mtd_device, result);
170                                 continue;
171                         }
172                         else
173                                 printf("%s: MTD writeoob at 0x%08x\n",mtd_device, erase.addr + meminfo->oobsize );
174                 }
175
176                 if (!opts->quiet) {
177                         unsigned long long n =(unsigned long long)
178                                 (erase.addr + meminfo->erasesize - opts->offset)
179                                 * 100;
180                         int percent;
181
182                         do_div(n, erase_length);
183                         percent = (int)n;
184
185                         /* output progress message only at whole percent
186                          * steps to reduce the number of messages printed
187                          * on (slow) serial consoles
188                          */
189                         if (percent != percent_complete) {
190                                 percent_complete = percent;
191
192                                 printf("\rErasing at 0x%x -- %3d%% complete.",
193                                 erase.addr, percent);
194
195                                 if (opts->jffs2 && result == 0)
196                                 printf(" Cleanmarker written at 0x%x.",
197                                 erase.addr);
198                         }
199                 }
200         }
201         if (!opts->quiet)
202                 printf("\n");
203
204         if (nand_block_bad_old) {
205                 struct nand_chip *priv_nand = meminfo->priv;
206
207                 priv_nand->block_bad = nand_block_bad_old;
208                 priv_nand->scan_bbt(meminfo);
209         }
210
211         return 0;
212 }
213
214 /* XXX U-BOOT XXX */
215 #if 0
216
217 #define MAX_PAGE_SIZE   2048
218 #define MAX_OOB_SIZE    64
219
220 /*
221  * buffer array used for writing data
222  */
223 static unsigned char data_buf[MAX_PAGE_SIZE];
224 static unsigned char oob_buf[MAX_OOB_SIZE];
225
226 /* OOB layouts to pass into the kernel as default */
227 static struct nand_ecclayout none_ecclayout = {
228         .useecc = MTD_NANDECC_OFF,
229 };
230
231 static struct nand_ecclayout jffs2_ecclayout = {
232         .useecc = MTD_NANDECC_PLACE,
233         .eccbytes = 6,
234         .eccpos = { 0, 1, 2, 3, 6, 7 }
235 };
236
237 static struct nand_ecclayout yaffs_ecclayout = {
238         .useecc = MTD_NANDECC_PLACE,
239         .eccbytes = 6,
240         .eccpos = { 8, 9, 10, 13, 14, 15}
241 };
242
243 static struct nand_ecclayout autoplace_ecclayout = {
244         .useecc = MTD_NANDECC_AUTOPLACE
245 };
246 #endif
247
248 /* XXX U-BOOT XXX */
249 #if 0
250 /******************************************************************************
251  * Support for locking / unlocking operations of some NAND devices
252  *****************************************************************************/
253
254 #define NAND_CMD_LOCK           0x2a
255 #define NAND_CMD_LOCK_TIGHT     0x2c
256 #define NAND_CMD_UNLOCK1        0x23
257 #define NAND_CMD_UNLOCK2        0x24
258 #define NAND_CMD_LOCK_STATUS    0x7a
259
260 /**
261  * nand_lock: Set all pages of NAND flash chip to the LOCK or LOCK-TIGHT
262  *            state
263  *
264  * @param meminfo       nand mtd instance
265  * @param tight         bring device in lock tight mode
266  *
267  * @return              0 on success, -1 in case of error
268  *
269  * The lock / lock-tight command only applies to the whole chip. To get some
270  * parts of the chip lock and others unlocked use the following sequence:
271  *
272  * - Lock all pages of the chip using nand_lock(mtd, 0) (or the lockpre pin)
273  * - Call nand_unlock() once for each consecutive area to be unlocked
274  * - If desired: Bring the chip to the lock-tight state using nand_lock(mtd, 1)
275  *
276  *   If the device is in lock-tight state software can't change the
277  *   current active lock/unlock state of all pages. nand_lock() / nand_unlock()
278  *   calls will fail. It is only posible to leave lock-tight state by
279  *   an hardware signal (low pulse on _WP pin) or by power down.
280  */
281 int nand_lock(nand_info_t *meminfo, int tight)
282 {
283         int ret = 0;
284         int status;
285         struct nand_chip *this = meminfo->priv;
286
287         /* select the NAND device */
288         this->select_chip(meminfo, 0);
289
290         this->cmdfunc(meminfo,
291                       (tight ? NAND_CMD_LOCK_TIGHT : NAND_CMD_LOCK),
292                       -1, -1);
293
294         /* call wait ready function */
295         status = this->waitfunc(meminfo, this, FL_WRITING);
296
297         /* see if device thinks it succeeded */
298         if (status & 0x01) {
299                 ret = -1;
300         }
301
302         /* de-select the NAND device */
303         this->select_chip(meminfo, -1);
304         return ret;
305 }
306
307 /**
308  * nand_get_lock_status: - query current lock state from one page of NAND
309  *                         flash
310  *
311  * @param meminfo       nand mtd instance
312  * @param offset        page address to query (muss be page aligned!)
313  *
314  * @return              -1 in case of error
315  *                      >0 lock status:
316  *                        bitfield with the following combinations:
317  *                        NAND_LOCK_STATUS_TIGHT: page in tight state
318  *                        NAND_LOCK_STATUS_LOCK:  page locked
319  *                        NAND_LOCK_STATUS_UNLOCK: page unlocked
320  *
321  */
322 int nand_get_lock_status(nand_info_t *meminfo, ulong offset)
323 {
324         int ret = 0;
325         int chipnr;
326         int page;
327         struct nand_chip *this = meminfo->priv;
328
329         /* select the NAND device */
330         chipnr = (int)(offset >> this->chip_shift);
331         this->select_chip(meminfo, chipnr);
332
333
334         if ((offset & (meminfo->writesize - 1)) != 0) {
335                 printf ("nand_get_lock_status: "
336                         "Start address must be beginning of "
337                         "nand page!\n");
338                 ret = -1;
339                 goto out;
340         }
341
342         /* check the Lock Status */
343         page = (int)(offset >> this->page_shift);
344         this->cmdfunc(meminfo, NAND_CMD_LOCK_STATUS, -1, page & this->pagemask);
345
346         ret = this->read_byte(meminfo) & (NAND_LOCK_STATUS_TIGHT
347                                           | NAND_LOCK_STATUS_LOCK
348                                           | NAND_LOCK_STATUS_UNLOCK);
349
350  out:
351         /* de-select the NAND device */
352         this->select_chip(meminfo, -1);
353         return ret;
354 }
355
356 /**
357  * nand_unlock: - Unlock area of NAND pages
358  *                only one consecutive area can be unlocked at one time!
359  *
360  * @param meminfo       nand mtd instance
361  * @param start         start byte address
362  * @param length        number of bytes to unlock (must be a multiple of
363  *                      page size nand->writesize)
364  *
365  * @return              0 on success, -1 in case of error
366  */
367 int nand_unlock(nand_info_t *meminfo, ulong start, ulong length)
368 {
369         int ret = 0;
370         int chipnr;
371         int status;
372         int page;
373         struct nand_chip *this = meminfo->priv;
374         printf ("nand_unlock: start: %08x, length: %d!\n",
375                 (int)start, (int)length);
376
377         /* select the NAND device */
378         chipnr = (int)(start >> this->chip_shift);
379         this->select_chip(meminfo, chipnr);
380
381         /* check the WP bit */
382         this->cmdfunc(meminfo, NAND_CMD_STATUS, -1, -1);
383         if ((this->read_byte(meminfo) & 0x80) == 0) {
384                 printf ("nand_unlock: Device is write protected!\n");
385                 ret = -1;
386                 goto out;
387         }
388
389         if ((start & (meminfo->writesize - 1)) != 0) {
390                 printf ("nand_unlock: Start address must be beginning of "
391                         "nand page!\n");
392                 ret = -1;
393                 goto out;
394         }
395
396         if (length == 0 || (length & (meminfo->writesize - 1)) != 0) {
397                 printf ("nand_unlock: Length must be a multiple of nand page "
398                         "size!\n");
399                 ret = -1;
400                 goto out;
401         }
402
403         /* submit address of first page to unlock */
404         page = (int)(start >> this->page_shift);
405         this->cmdfunc(meminfo, NAND_CMD_UNLOCK1, -1, page & this->pagemask);
406
407         /* submit ADDRESS of LAST page to unlock */
408         page += (int)(length >> this->page_shift) - 1;
409         this->cmdfunc(meminfo, NAND_CMD_UNLOCK2, -1, page & this->pagemask);
410
411         /* call wait ready function */
412         status = this->waitfunc(meminfo, this, FL_WRITING);
413         /* see if device thinks it succeeded */
414         if (status & 0x01) {
415                 /* there was an error */
416                 ret = -1;
417                 goto out;
418         }
419
420  out:
421         /* de-select the NAND device */
422         this->select_chip(meminfo, -1);
423         return ret;
424 }
425 #endif
426
427 /**
428  * get_len_incl_bad
429  *
430  * Check if length including bad blocks fits into device.
431  *
432  * @param nand NAND device
433  * @param offset offset in flash
434  * @param length image length
435  * @return image length including bad blocks
436  */
437 static size_t get_len_incl_bad (nand_info_t *nand, size_t offset,
438                                 const size_t length)
439 {
440         size_t len_incl_bad = 0;
441         size_t len_excl_bad = 0;
442         size_t block_len;
443
444         while (len_excl_bad < length) {
445                 block_len = nand->erasesize - (offset & (nand->erasesize - 1));
446
447                 if (!nand_block_isbad (nand, offset & ~(nand->erasesize - 1)))
448                         len_excl_bad += block_len;
449
450                 len_incl_bad += block_len;
451                 offset       += block_len;
452
453                 if ((offset + len_incl_bad) >= nand->size)
454                         break;
455         }
456
457         return len_incl_bad;
458 }
459
460 /**
461  * nand_write_skip_bad:
462  *
463  * Write image to NAND flash.
464  * Blocks that are marked bad are skipped and the is written to the next
465  * block instead as long as the image is short enough to fit even after
466  * skipping the bad blocks.
467  *
468  * @param nand          NAND device
469  * @param offset        offset in flash
470  * @param length        buffer length
471  * @param buf           buffer to read from
472  * @return              0 in case of success
473  */
474 int nand_write_skip_bad(nand_info_t *nand, size_t offset, size_t *length,
475                         u_char *buffer)
476 {
477         int rval;
478         size_t left_to_write = *length;
479         size_t len_incl_bad;
480         u_char *p_buffer = buffer;
481
482         /* Reject writes, which are not page aligned */
483         if ((offset & (nand->writesize - 1)) != 0 ||
484             (*length & (nand->writesize - 1)) != 0) {
485                 printf ("Attempt to write non page aligned data\n");
486                 return -EINVAL;
487         }
488
489         len_incl_bad = get_len_incl_bad (nand, offset, *length);
490
491         if ((offset + len_incl_bad) >= nand->size) {
492                 printf ("Attempt to write outside the flash area\n");
493                 return -EINVAL;
494         }
495
496         if (len_incl_bad == *length) {
497                 rval = nand_write (nand, offset, length, buffer);
498                 if (rval != 0) {
499                         printf ("NAND write to offset %x failed %d\n",
500                                 offset, rval);
501                         return rval;
502                 }
503         }
504
505         while (left_to_write > 0) {
506                 size_t block_offset = offset & (nand->erasesize - 1);
507                 size_t write_size;
508
509                 if (nand_block_isbad (nand, offset & ~(nand->erasesize - 1))) {
510                         printf ("Skip bad block 0x%08x\n",
511                                 offset & ~(nand->erasesize - 1));
512                         offset += nand->erasesize - block_offset;
513                         continue;
514                 }
515
516                 if (left_to_write < (nand->erasesize - block_offset))
517                         write_size = left_to_write;
518                 else
519                         write_size = nand->erasesize - block_offset;
520
521                 rval = nand_write (nand, offset, &write_size, p_buffer);
522                 if (rval != 0) {
523                         printf ("NAND write to offset %x failed %d\n",
524                                 offset, rval);
525                         *length -= left_to_write;
526                         return rval;
527                 }
528
529                 left_to_write -= write_size;
530                 offset        += write_size;
531                 p_buffer      += write_size;
532         }
533
534         return 0;
535 }
536
537 /**
538  * nand_read_skip_bad:
539  *
540  * Read image from NAND flash.
541  * Blocks that are marked bad are skipped and the next block is readen
542  * instead as long as the image is short enough to fit even after skipping the
543  * bad blocks.
544  *
545  * @param nand NAND device
546  * @param offset offset in flash
547  * @param length buffer length, on return holds remaining bytes to read
548  * @param buffer buffer to write to
549  * @return 0 in case of success
550  */
551 int nand_read_skip_bad(nand_info_t *nand, size_t offset, size_t *length,
552                        u_char *buffer)
553 {
554         int rval;
555         size_t left_to_read = *length;
556         size_t len_incl_bad;
557         u_char *p_buffer = buffer;
558
559         len_incl_bad = get_len_incl_bad (nand, offset, *length);
560
561         if ((offset + len_incl_bad) >= nand->size) {
562                 printf ("Attempt to read outside the flash area\n");
563                 return -EINVAL;
564         }
565
566         if (len_incl_bad == *length) {
567                 rval = nand_read (nand, offset, length, buffer);
568                 if (rval != 0) {
569                         printf ("NAND read from offset %x failed %d\n",
570                                 offset, rval);
571                         return rval;
572                 }
573         }
574
575         while (left_to_read > 0) {
576                 size_t block_offset = offset & (nand->erasesize - 1);
577                 size_t read_length;
578
579                 if (nand_block_isbad (nand, offset & ~(nand->erasesize - 1))) {
580                         printf ("Skipping bad block 0x%08x\n",
581                                 offset & ~(nand->erasesize - 1));
582                         offset += nand->erasesize - block_offset;
583                         continue;
584                 }
585
586                 if (left_to_read < (nand->erasesize - block_offset))
587                         read_length = left_to_read;
588                 else
589                         read_length = nand->erasesize - block_offset;
590
591                 rval = nand_read (nand, offset, &read_length, p_buffer);
592                 if (rval != 0) {
593                         printf ("NAND read from offset %x failed %d\n",
594                                 offset, rval);
595                         *length -= left_to_read;
596                         return rval;
597                 }
598
599                 left_to_read -= read_length;
600                 offset       += read_length;
601                 p_buffer     += read_length;
602         }
603
604         return 0;
605 }