2 * drivers/mtd/nand/nand_util.c
4 * Copyright (C) 2006 by Weiss-Electronic GmbH.
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)
14 * Copyright (C) 2008 Nokia Corporation: drop_ffs() function by
15 * Artem Bityutskiy <dedekind1@gmail.com> from mtd-utils
17 * SPDX-License-Identifier: GPL-2.0+
26 #include <asm/errno.h>
27 #include <linux/mtd/mtd.h>
29 #include <jffs2/jffs2.h>
31 typedef struct erase_info erase_info_t;
32 typedef struct mtd_info mtd_info_t;
34 /* support only for native endian JFFS2 */
35 #define cpu_to_je16(x) (x)
36 #define cpu_to_je32(x) (x)
39 * nand_erase_opts: - erase NAND flash with support for various options
42 * @param meminfo NAND device to erase
43 * @param opts options, @see struct nand_erase_options
44 * @return 0 in case of success
46 * This code is ported from flash_eraseall.c from Linux mtd utils by
47 * Arcom Control System Ltd.
49 int nand_erase_opts(nand_info_t *meminfo, const nand_erase_options_t *opts)
51 struct jffs2_unknown_node cleanmarker;
53 unsigned long erase_length, erased_length; /* in blocks */
55 int percent_complete = -1;
56 const char *mtd_device = meminfo->name;
57 struct mtd_oob_ops oob_opts;
58 struct nand_chip *chip = meminfo->priv;
60 if ((opts->offset & (meminfo->erasesize - 1)) != 0) {
61 printf("Attempt to erase non block-aligned data\n");
65 memset(&erase, 0, sizeof(erase));
66 memset(&oob_opts, 0, sizeof(oob_opts));
69 erase.len = meminfo->erasesize;
70 erase.addr = opts->offset;
71 erase_length = lldiv(opts->length + meminfo->erasesize - 1,
74 cleanmarker.magic = cpu_to_je16(JFFS2_MAGIC_BITMASK);
75 cleanmarker.nodetype = cpu_to_je16(JFFS2_NODETYPE_CLEANMARKER);
76 cleanmarker.totlen = cpu_to_je32(8);
78 /* scrub option allows to erase badblock. To prevent internal
79 * check from erase() method, set block check method to dummy
80 * and disable bad block table while erasing.
83 erase.scrub = opts->scrub;
85 * We don't need the bad block table anymore...
86 * after scrub, there are no bad blocks left!
94 for (erased_length = 0;
95 erased_length < erase_length;
96 erase.addr += meminfo->erasesize) {
100 if (opts->lim && (erase.addr >= (opts->offset + opts->lim))) {
101 puts("Size of erase exceeds limit\n");
105 int ret = mtd_block_isbad(meminfo, erase.addr);
108 printf("\rSkipping bad block at "
118 } else if (ret < 0) {
119 printf("\n%s: MTD get bad block failed: %d\n",
128 result = mtd_erase(meminfo, &erase);
130 printf("\n%s: MTD Erase failure: %d\n",
135 /* format for JFFS2 ? */
136 if (opts->jffs2 && chip->ecc.layout->oobavail >= 8) {
137 struct mtd_oob_ops ops;
140 ops.oobbuf = (uint8_t *)&cleanmarker;
142 ops.mode = MTD_OPS_AUTO_OOB;
144 result = mtd_write_oob(meminfo,
148 printf("\n%s: MTD writeoob failure: %d\n",
155 unsigned long long n = erased_length * 100ULL;
158 do_div(n, erase_length);
161 /* output progress message only at whole percent
162 * steps to reduce the number of messages printed
163 * on (slow) serial consoles
165 if (percent != percent_complete) {
166 percent_complete = percent;
168 printf("\rErasing at 0x%llx -- %3d%% complete.",
169 erase.addr, percent);
171 if (opts->jffs2 && result == 0)
172 printf(" Cleanmarker written at 0x%llx.",
181 chip->scan_bbt(meminfo);
186 #ifdef CONFIG_CMD_NAND_LOCK_UNLOCK
188 /******************************************************************************
189 * Support for locking / unlocking operations of some NAND devices
190 *****************************************************************************/
193 * nand_lock: Set all pages of NAND flash chip to the LOCK or LOCK-TIGHT
196 * @param mtd nand mtd instance
197 * @param tight bring device in lock tight mode
199 * @return 0 on success, -1 in case of error
201 * The lock / lock-tight command only applies to the whole chip. To get some
202 * parts of the chip lock and others unlocked use the following sequence:
204 * - Lock all pages of the chip using nand_lock(mtd, 0) (or the lockpre pin)
205 * - Call nand_unlock() once for each consecutive area to be unlocked
206 * - If desired: Bring the chip to the lock-tight state using nand_lock(mtd, 1)
208 * If the device is in lock-tight state software can't change the
209 * current active lock/unlock state of all pages. nand_lock() / nand_unlock()
210 * calls will fail. It is only posible to leave lock-tight state by
211 * an hardware signal (low pulse on _WP pin) or by power down.
213 int nand_lock(struct mtd_info *mtd, int tight)
217 struct nand_chip *chip = mtd->priv;
219 /* select the NAND device */
220 chip->select_chip(mtd, 0);
222 /* check the Lock Tight Status */
223 chip->cmdfunc(mtd, NAND_CMD_LOCK_STATUS, -1, 0);
224 if (chip->read_byte(mtd) & NAND_LOCK_STATUS_TIGHT) {
225 printf("nand_lock: Device is locked tight!\n");
231 (tight ? NAND_CMD_LOCK_TIGHT : NAND_CMD_LOCK),
234 /* call wait ready function */
235 status = chip->waitfunc(mtd, chip);
237 /* see if device thinks it succeeded */
243 /* de-select the NAND device */
244 chip->select_chip(mtd, -1);
249 * nand_get_lock_status: - query current lock state from one page of NAND
252 * @param mtd nand mtd instance
253 * @param offset page address to query (must be page-aligned!)
255 * @return -1 in case of error
257 * bitfield with the following combinations:
258 * NAND_LOCK_STATUS_TIGHT: page in tight state
259 * NAND_LOCK_STATUS_UNLOCK: page unlocked
262 int nand_get_lock_status(struct mtd_info *mtd, loff_t offset)
267 struct nand_chip *chip = mtd->priv;
269 /* select the NAND device */
270 chipnr = (int)(offset >> chip->chip_shift);
271 chip->select_chip(mtd, chipnr);
274 if ((offset & (mtd->writesize - 1)) != 0) {
275 printf("nand_get_lock_status: "
276 "Start address must be beginning of "
282 /* check the Lock Status */
283 page = (int)(offset >> chip->page_shift);
284 chip->cmdfunc(mtd, NAND_CMD_LOCK_STATUS, -1, page & chip->pagemask);
286 ret = chip->read_byte(mtd) & (NAND_LOCK_STATUS_TIGHT
287 | NAND_LOCK_STATUS_UNLOCK);
290 /* de-select the NAND device */
291 chip->select_chip(mtd, -1);
296 * nand_unlock: - Unlock area of NAND pages
297 * only one consecutive area can be unlocked at one time!
299 * @param mtd nand mtd instance
300 * @param start start byte address
301 * @param length number of bytes to unlock (must be a multiple of
302 * page size nand->writesize)
303 * @param allexcept if set, unlock everything not selected
305 * @return 0 on success, -1 in case of error
307 int nand_unlock(struct mtd_info *mtd, loff_t start, size_t length,
314 struct nand_chip *chip = mtd->priv;
316 debug("nand_unlock%s: start: %08llx, length: %d!\n",
317 allexcept ? " (allexcept)" : "", start, length);
319 /* select the NAND device */
320 chipnr = (int)(start >> chip->chip_shift);
321 chip->select_chip(mtd, chipnr);
323 /* check the WP bit */
324 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
325 if (!(chip->read_byte(mtd) & NAND_STATUS_WP)) {
326 printf("nand_unlock: Device is write protected!\n");
331 /* check the Lock Tight Status */
332 page = (int)(start >> chip->page_shift);
333 chip->cmdfunc(mtd, NAND_CMD_LOCK_STATUS, -1, page & chip->pagemask);
334 if (chip->read_byte(mtd) & NAND_LOCK_STATUS_TIGHT) {
335 printf("nand_unlock: Device is locked tight!\n");
340 if ((start & (mtd->erasesize - 1)) != 0) {
341 printf("nand_unlock: Start address must be beginning of "
347 if (length == 0 || (length & (mtd->erasesize - 1)) != 0) {
348 printf("nand_unlock: Length must be a multiple of nand block "
349 "size %08x!\n", mtd->erasesize);
355 * Set length so that the last address is set to the
356 * starting address of the last block
358 length -= mtd->erasesize;
360 /* submit address of first page to unlock */
361 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
363 /* submit ADDRESS of LAST page to unlock */
364 page += (int)(length >> chip->page_shift);
367 * Page addresses for unlocking are supposed to be block-aligned.
368 * At least some NAND chips use the low bit to indicate that the
369 * page range should be inverted.
374 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1, page & chip->pagemask);
376 /* call wait ready function */
377 status = chip->waitfunc(mtd, chip);
378 /* see if device thinks it succeeded */
380 /* there was an error */
386 /* de-select the NAND device */
387 chip->select_chip(mtd, -1);
395 * Check if there are any bad blocks, and whether length including bad
396 * blocks fits into device
398 * @param nand NAND device
399 * @param offset offset in flash
400 * @param length image length
401 * @param used length of flash needed for the requested length
402 * @return 0 if the image fits and there are no bad blocks
403 * 1 if the image fits, but there are bad blocks
404 * -1 if the image does not fit
406 static int check_skip_len(nand_info_t *nand, loff_t offset, size_t length,
409 size_t len_excl_bad = 0;
412 while (len_excl_bad < length) {
413 size_t block_len, block_off;
416 if (offset >= nand->size)
419 block_start = offset & ~(loff_t)(nand->erasesize - 1);
420 block_off = offset & (nand->erasesize - 1);
421 block_len = nand->erasesize - block_off;
423 if (!nand_block_isbad(nand, block_start))
424 len_excl_bad += block_len;
432 /* If the length is not a multiple of block_len, adjust. */
433 if (len_excl_bad > length)
434 *used -= (len_excl_bad - length);
439 #ifdef CONFIG_CMD_NAND_TRIMFFS
440 static size_t drop_ffs(const nand_info_t *nand, const u_char *buf,
446 for (i = l - 1; i >= 0; i--)
450 /* The resulting length must be aligned to the minimum flash I/O size */
452 l = (l + nand->writesize - 1) / nand->writesize;
453 l *= nand->writesize;
456 * since the input length may be unaligned, prevent access past the end
464 * nand_write_skip_bad:
466 * Write image to NAND flash.
467 * Blocks that are marked bad are skipped and the is written to the next
468 * block instead as long as the image is short enough to fit even after
469 * skipping the bad blocks. Due to bad blocks we may not be able to
470 * perform the requested write. In the case where the write would
471 * extend beyond the end of the NAND device, both length and actual (if
472 * not NULL) are set to 0. In the case where the write would extend
473 * beyond the limit we are passed, length is set to 0 and actual is set
474 * to the required length.
476 * @param nand NAND device
477 * @param offset offset in flash
478 * @param length buffer length
479 * @param actual set to size required to write length worth of
480 * buffer or 0 on error, if not NULL
481 * @param lim maximum size that actual may be in order to not
483 * @param buffer buffer to read from
484 * @param flags flags modifying the behaviour of the write to NAND
485 * @return 0 in case of success
487 int nand_write_skip_bad(nand_info_t *nand, loff_t offset, size_t *length,
488 size_t *actual, loff_t lim, u_char *buffer, int flags)
490 int rval = 0, blocksize;
491 size_t left_to_write = *length;
492 size_t used_for_write = 0;
493 u_char *p_buffer = buffer;
499 #ifdef CONFIG_CMD_NAND_YAFFS
500 if (flags & WITH_YAFFS_OOB) {
501 if (flags & ~WITH_YAFFS_OOB)
505 pages = nand->erasesize / nand->writesize;
506 blocksize = (pages * nand->oobsize) + nand->erasesize;
507 if (*length % (nand->writesize + nand->oobsize)) {
508 printf("Attempt to write incomplete page"
515 blocksize = nand->erasesize;
519 * nand_write() handles unaligned, partial page writes.
521 * We allow length to be unaligned, for convenience in
522 * using the $filesize variable.
524 * However, starting at an unaligned offset makes the
525 * semantics of bad block skipping ambiguous (really,
526 * you should only start a block skipping access at a
527 * partition boundary). So don't try to handle that.
529 if ((offset & (nand->writesize - 1)) != 0) {
530 printf("Attempt to write non page-aligned data\n");
535 need_skip = check_skip_len(nand, offset, *length, &used_for_write);
538 *actual = used_for_write;
541 printf("Attempt to write outside the flash area\n");
546 if (used_for_write > lim) {
547 puts("Size of write exceeds partition or device limit\n");
552 if (!need_skip && !(flags & WITH_DROP_FFS)) {
553 rval = nand_write(nand, offset, length, buffer);
558 printf("NAND write to offset %llx failed %d\n",
563 while (left_to_write > 0) {
564 size_t block_offset = offset & (nand->erasesize - 1);
565 size_t write_size, truncated_write_size;
569 if (nand_block_isbad(nand, offset & ~(nand->erasesize - 1))) {
570 printf("Skip bad block 0x%08llx\n",
571 offset & ~(nand->erasesize - 1));
572 offset += nand->erasesize - block_offset;
576 if (left_to_write < (blocksize - block_offset))
577 write_size = left_to_write;
579 write_size = blocksize - block_offset;
581 #ifdef CONFIG_CMD_NAND_YAFFS
582 if (flags & WITH_YAFFS_OOB) {
584 size_t pagesize = nand->writesize;
585 size_t pagesize_oob = pagesize + nand->oobsize;
586 struct mtd_oob_ops ops;
589 ops.ooblen = nand->oobsize;
590 ops.mode = MTD_OPS_AUTO_OOB;
593 pages = write_size / pagesize_oob;
594 for (page = 0; page < pages; page++) {
597 ops.datbuf = p_buffer;
598 ops.oobbuf = ops.datbuf + pagesize;
600 rval = mtd_write_oob(nand, offset, &ops);
605 p_buffer += pagesize_oob;
611 truncated_write_size = write_size;
612 #ifdef CONFIG_CMD_NAND_TRIMFFS
613 if (flags & WITH_DROP_FFS)
614 truncated_write_size = drop_ffs(nand, p_buffer,
618 rval = nand_write(nand, offset, &truncated_write_size,
620 offset += write_size;
621 p_buffer += write_size;
625 printf("NAND write to offset %llx failed %d\n",
627 *length -= left_to_write;
631 left_to_write -= write_size;
638 * nand_read_skip_bad:
640 * Read image from NAND flash.
641 * Blocks that are marked bad are skipped and the next block is read
642 * instead as long as the image is short enough to fit even after
643 * skipping the bad blocks. Due to bad blocks we may not be able to
644 * perform the requested read. In the case where the read would extend
645 * beyond the end of the NAND device, both length and actual (if not
646 * NULL) are set to 0. In the case where the read would extend beyond
647 * the limit we are passed, length is set to 0 and actual is set to the
650 * @param nand NAND device
651 * @param offset offset in flash
652 * @param length buffer length, on return holds number of read bytes
653 * @param actual set to size required to read length worth of buffer or 0
654 * on error, if not NULL
655 * @param lim maximum size that actual may be in order to not exceed the
657 * @param buffer buffer to write to
658 * @return 0 in case of success
660 int nand_read_skip_bad(nand_info_t *nand, loff_t offset, size_t *length,
661 size_t *actual, loff_t lim, u_char *buffer)
664 size_t left_to_read = *length;
665 size_t used_for_read = 0;
666 u_char *p_buffer = buffer;
669 if ((offset & (nand->writesize - 1)) != 0) {
670 printf("Attempt to read non page-aligned data\n");
677 need_skip = check_skip_len(nand, offset, *length, &used_for_read);
680 *actual = used_for_read;
683 printf("Attempt to read outside the flash area\n");
688 if (used_for_read > lim) {
689 puts("Size of read exceeds partition or device limit\n");
695 rval = nand_read(nand, offset, length, buffer);
696 if (!rval || rval == -EUCLEAN)
700 printf("NAND read from offset %llx failed %d\n",
705 while (left_to_read > 0) {
706 size_t block_offset = offset & (nand->erasesize - 1);
711 if (nand_block_isbad(nand, offset & ~(nand->erasesize - 1))) {
712 printf("Skipping bad block 0x%08llx\n",
713 offset & ~(nand->erasesize - 1));
714 offset += nand->erasesize - block_offset;
718 if (left_to_read < (nand->erasesize - block_offset))
719 read_length = left_to_read;
721 read_length = nand->erasesize - block_offset;
723 rval = nand_read(nand, offset, &read_length, p_buffer);
724 if (rval && rval != -EUCLEAN) {
725 printf("NAND read from offset %llx failed %d\n",
727 *length -= left_to_read;
731 left_to_read -= read_length;
732 offset += read_length;
733 p_buffer += read_length;
739 #ifdef CONFIG_CMD_NAND_TORTURE
744 * Check if buffer contains only a certain byte pattern.
746 * @param buf buffer to check
747 * @param patt the pattern to check
748 * @param size buffer size in bytes
749 * @return 1 if there are only patt bytes in buf
750 * 0 if something else was found
752 static int check_pattern(const u_char *buf, u_char patt, int size)
756 for (i = 0; i < size; i++)
765 * Torture a block of NAND flash.
766 * This is useful to determine if a block that caused a write error is still
767 * good or should be marked as bad.
769 * @param nand NAND device
770 * @param offset offset in flash
771 * @return 0 if the block is still good
773 int nand_torture(nand_info_t *nand, loff_t offset)
775 u_char patterns[] = {0xa5, 0x5a, 0x00};
776 struct erase_info instr = {
779 .len = nand->erasesize,
782 int err, ret = -1, i, patt_count;
785 if ((offset & (nand->erasesize - 1)) != 0) {
786 puts("Attempt to torture a block at a non block-aligned offset\n");
790 if (offset + nand->erasesize > nand->size) {
791 puts("Attempt to torture a block outside the flash area\n");
795 patt_count = ARRAY_SIZE(patterns);
797 buf = malloc(nand->erasesize);
799 puts("Out of memory for erase block buffer\n");
803 for (i = 0; i < patt_count; i++) {
804 err = nand->erase(nand, &instr);
806 printf("%s: erase() failed for block at 0x%llx: %d\n",
807 nand->name, instr.addr, err);
811 /* Make sure the block contains only 0xff bytes */
812 err = nand->read(nand, offset, nand->erasesize, &retlen, buf);
813 if ((err && err != -EUCLEAN) || retlen != nand->erasesize) {
814 printf("%s: read() failed for block at 0x%llx: %d\n",
815 nand->name, instr.addr, err);
819 err = check_pattern(buf, 0xff, nand->erasesize);
821 printf("Erased block at 0x%llx, but a non-0xff byte was found\n",
827 /* Write a pattern and check it */
828 memset(buf, patterns[i], nand->erasesize);
829 err = nand->write(nand, offset, nand->erasesize, &retlen, buf);
830 if (err || retlen != nand->erasesize) {
831 printf("%s: write() failed for block at 0x%llx: %d\n",
832 nand->name, instr.addr, err);
836 err = nand->read(nand, offset, nand->erasesize, &retlen, buf);
837 if ((err && err != -EUCLEAN) || retlen != nand->erasesize) {
838 printf("%s: read() failed for block at 0x%llx: %d\n",
839 nand->name, instr.addr, err);
843 err = check_pattern(buf, patterns[i], nand->erasesize);
845 printf("Pattern 0x%.2x checking failed for block at "
846 "0x%llx\n", patterns[i], offset);