1// SPDX-License-Identifier: GPL-2.0
2/*
3 * drivers/mtd/nand/raw/nand_util.c
4 *
5 * Copyright (C) 2006 by Weiss-Electronic GmbH.
6 * All rights reserved.
7 *
8 * @author:	Guido Classen <clagix@gmail.com>
9 * @descr:	NAND Flash support
10 * @references: borrowed heavily from Linux mtd-utils code:
11 *		flash_eraseall.c by Arcom Control System Ltd
12 *		nandwrite.c by Steven J. Hill (sjhill@realitydiluted.com)
13 *			       and Thomas Gleixner (tglx@linutronix.de)
14 *
15 * Copyright (C) 2008 Nokia Corporation: drop_ffs() function by
16 * Artem Bityutskiy <dedekind1@gmail.com> from mtd-utils
17 *
18 * Copyright 2010 Freescale Semiconductor
19 */
20
21#include <common.h>
22#include <command.h>
23#include <log.h>
24#include <watchdog.h>
25#include <malloc.h>
26#include <memalign.h>
27#include <div64.h>
28#include <asm/cache.h>
29#include <dm/devres.h>
30
31#include <linux/errno.h>
32#include <linux/mtd/mtd.h>
33#include <linux/mtd/rawnand.h>
34#include <nand.h>
35#include <jffs2/jffs2.h>
36
37typedef struct erase_info	erase_info_t;
38typedef struct mtd_info		mtd_info_t;
39
40/* support only for native endian JFFS2 */
41#define cpu_to_je16(x) (x)
42#define cpu_to_je32(x) (x)
43
44/**
45 * nand_erase_opts: - erase NAND flash with support for various options
46 *		      (jffs2 formatting)
47 *
48 * @param mtd		nand mtd instance to erase
49 * @param opts		options,  @see struct nand_erase_options
50 * Return:		0 in case of success
51 *
52 * This code is ported from flash_eraseall.c from Linux mtd utils by
53 * Arcom Control System Ltd.
54 */
55int nand_erase_opts(struct mtd_info *mtd,
56		    const nand_erase_options_t *opts)
57{
58	struct jffs2_unknown_node cleanmarker;
59	erase_info_t erase;
60	unsigned long erase_length, erased_length; /* in blocks */
61	int result;
62	int percent_complete = -1;
63	const char *mtd_device = mtd->name;
64	struct mtd_oob_ops oob_opts;
65	struct nand_chip *chip = mtd_to_nand(mtd);
66
67	if ((opts->offset & (mtd->erasesize - 1)) != 0) {
68		printf("Attempt to erase non block-aligned data\n");
69		return -1;
70	}
71
72	memset(&erase, 0, sizeof(erase));
73	memset(&oob_opts, 0, sizeof(oob_opts));
74
75	erase.mtd = mtd;
76	erase.len = mtd->erasesize;
77	erase.addr = opts->offset;
78	erase_length = lldiv(opts->length + mtd->erasesize - 1,
79			     mtd->erasesize);
80
81	cleanmarker.magic = cpu_to_je16(JFFS2_MAGIC_BITMASK);
82	cleanmarker.nodetype = cpu_to_je16(JFFS2_NODETYPE_CLEANMARKER);
83	cleanmarker.totlen = cpu_to_je32(8);
84
85	/* scrub option allows to erase badblock. To prevent internal
86	 * check from erase() method, set block check method to dummy
87	 * and disable bad block table while erasing.
88	 */
89	if (opts->scrub) {
90		erase.scrub = opts->scrub;
91		/*
92		 * We don't need the bad block table anymore...
93		 * after scrub, there are no bad blocks left!
94		 */
95		if (chip->bbt) {
96			kfree(chip->bbt);
97		}
98		chip->bbt = NULL;
99		chip->options &= ~NAND_BBT_SCANNED;
100	}
101
102	for (erased_length = 0;
103	     erased_length < erase_length;
104	     erase.addr += mtd->erasesize) {
105
106		schedule();
107
108		if (opts->lim && (erase.addr >= (opts->offset + opts->lim))) {
109			puts("Size of erase exceeds limit\n");
110			return -EFBIG;
111		}
112		if (!opts->scrub) {
113			int ret = mtd_block_isbad(mtd, erase.addr);
114			if (ret > 0) {
115				if (!opts->quiet)
116					printf("\rSkipping %s at  "
117					       "0x%08llx                 "
118					       "                         \n",
119					       ret == 1 ? "bad block" : "bbt reserved",
120					       erase.addr);
121
122				if (!opts->spread)
123					erased_length++;
124
125				continue;
126
127			} else if (ret < 0) {
128				printf("\n%s: MTD get bad block failed: %d\n",
129				       mtd_device,
130				       ret);
131				return -1;
132			}
133		}
134
135		erased_length++;
136
137		result = mtd_erase(mtd, &erase);
138		if (result != 0) {
139			printf("\n%s: MTD Erase failure: %d\n",
140			       mtd_device, result);
141			continue;
142		}
143
144		/* format for JFFS2 ? */
145		if (opts->jffs2 && chip->ecc.layout->oobavail >= 8) {
146			struct mtd_oob_ops ops;
147			ops.ooblen = 8;
148			ops.datbuf = NULL;
149			ops.oobbuf = (uint8_t *)&cleanmarker;
150			ops.ooboffs = 0;
151			ops.mode = MTD_OPS_AUTO_OOB;
152
153			result = mtd_write_oob(mtd, erase.addr, &ops);
154			if (result != 0) {
155				printf("\n%s: MTD writeoob failure: %d\n",
156				       mtd_device, result);
157				continue;
158			}
159		}
160
161		if (!opts->quiet) {
162			unsigned long long n = erased_length * 100ULL;
163			int percent;
164
165			do_div(n, erase_length);
166			percent = (int)n;
167
168			/* output progress message only at whole percent
169			 * steps to reduce the number of messages printed
170			 * on (slow) serial consoles
171			 */
172			if (percent != percent_complete) {
173				percent_complete = percent;
174
175				printf("\rErasing at 0x%llx -- %3d%% complete.",
176				       erase.addr, percent);
177
178				if (opts->jffs2 && result == 0)
179					printf(" Cleanmarker written at 0x%llx.",
180					       erase.addr);
181			}
182		}
183	}
184	if (!opts->quiet)
185		printf("\n");
186
187	return 0;
188}
189
190#ifdef CONFIG_CMD_NAND_LOCK_UNLOCK
191
192#define NAND_CMD_LOCK_TIGHT     0x2c
193#define NAND_CMD_LOCK_STATUS    0x7a
194
195/******************************************************************************
196 * Support for locking / unlocking operations of some NAND devices
197 *****************************************************************************/
198
199/**
200 * nand_lock: Set all pages of NAND flash chip to the LOCK or LOCK-TIGHT
201 *	      state
202 *
203 * @param mtd		nand mtd instance
204 * @param tight		bring device in lock tight mode
205 *
206 * Return:		0 on success, -1 in case of error
207 *
208 * The lock / lock-tight command only applies to the whole chip. To get some
209 * parts of the chip lock and others unlocked use the following sequence:
210 *
211 * - Lock all pages of the chip using nand_lock(mtd, 0) (or the lockpre pin)
212 * - Call nand_unlock() once for each consecutive area to be unlocked
213 * - If desired: Bring the chip to the lock-tight state using nand_lock(mtd, 1)
214 *
215 *   If the device is in lock-tight state software can't change the
216 *   current active lock/unlock state of all pages. nand_lock() / nand_unlock()
217 *   calls will fail. It is only posible to leave lock-tight state by
218 *   an hardware signal (low pulse on _WP pin) or by power down.
219 */
220int nand_lock(struct mtd_info *mtd, int tight)
221{
222	int ret = 0;
223	int status;
224	struct nand_chip *chip = mtd_to_nand(mtd);
225
226	/* select the NAND device */
227	chip->select_chip(mtd, 0);
228
229	/* check the Lock Tight Status */
230	chip->cmdfunc(mtd, NAND_CMD_LOCK_STATUS, -1, 0);
231	if (chip->read_byte(mtd) & NAND_LOCK_STATUS_TIGHT) {
232		printf("nand_lock: Device is locked tight!\n");
233		ret = -1;
234		goto out;
235	}
236
237	chip->cmdfunc(mtd,
238		      (tight ? NAND_CMD_LOCK_TIGHT : NAND_CMD_LOCK),
239		      -1, -1);
240
241	/* call wait ready function */
242	status = chip->waitfunc(mtd, chip);
243
244	/* see if device thinks it succeeded */
245	if (status & 0x01) {
246		ret = -1;
247	}
248
249 out:
250	/* de-select the NAND device */
251	chip->select_chip(mtd, -1);
252	return ret;
253}
254
255/**
256 * nand_get_lock_status: - query current lock state from one page of NAND
257 *			   flash
258 *
259 * @param mtd		nand mtd instance
260 * @param offset	page address to query (must be page-aligned!)
261 *
262 * Return:		-1 in case of error
263 *			>0 lock status:
264 *			  bitfield with the following combinations:
265 *			  NAND_LOCK_STATUS_TIGHT: page in tight state
266 *			  NAND_LOCK_STATUS_UNLOCK: page unlocked
267 *
268 */
269int nand_get_lock_status(struct mtd_info *mtd, loff_t offset)
270{
271	int ret = 0;
272	int chipnr;
273	int page;
274	struct nand_chip *chip = mtd_to_nand(mtd);
275
276	/* select the NAND device */
277	chipnr = (int)(offset >> chip->chip_shift);
278	chip->select_chip(mtd, chipnr);
279
280
281	if ((offset & (mtd->writesize - 1)) != 0) {
282		printf("nand_get_lock_status: "
283			"Start address must be beginning of "
284			"nand page!\n");
285		ret = -1;
286		goto out;
287	}
288
289	/* check the Lock Status */
290	page = (int)(offset >> chip->page_shift);
291	chip->cmdfunc(mtd, NAND_CMD_LOCK_STATUS, -1, page & chip->pagemask);
292
293	ret = chip->read_byte(mtd) & (NAND_LOCK_STATUS_TIGHT
294					  | NAND_LOCK_STATUS_UNLOCK);
295
296 out:
297	/* de-select the NAND device */
298	chip->select_chip(mtd, -1);
299	return ret;
300}
301
302/**
303 * nand_unlock: - Unlock area of NAND pages
304 *		  only one consecutive area can be unlocked at one time!
305 *
306 * @param mtd		nand mtd instance
307 * @param start		start byte address
308 * @param length	number of bytes to unlock (must be a multiple of
309 *			page size mtd->writesize)
310 * @param allexcept	if set, unlock everything not selected
311 *
312 * Return:		0 on success, -1 in case of error
313 */
314int nand_unlock(struct mtd_info *mtd, loff_t start, size_t length,
315	int allexcept)
316{
317	int ret = 0;
318	int chipnr;
319	int status;
320	int page;
321	struct nand_chip *chip = mtd_to_nand(mtd);
322
323	debug("nand_unlock%s: start: %08llx, length: %zd!\n",
324		allexcept ? " (allexcept)" : "", start, length);
325
326	/* select the NAND device */
327	chipnr = (int)(start >> chip->chip_shift);
328	chip->select_chip(mtd, chipnr);
329
330	/* check the WP bit */
331	chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
332	if (!(chip->read_byte(mtd) & NAND_STATUS_WP)) {
333		printf("nand_unlock: Device is write protected!\n");
334		ret = -1;
335		goto out;
336	}
337
338	/* check the Lock Tight Status */
339	page = (int)(start >> chip->page_shift);
340	chip->cmdfunc(mtd, NAND_CMD_LOCK_STATUS, -1, page & chip->pagemask);
341	if (chip->read_byte(mtd) & NAND_LOCK_STATUS_TIGHT) {
342		printf("nand_unlock: Device is locked tight!\n");
343		ret = -1;
344		goto out;
345	}
346
347	if ((start & (mtd->erasesize - 1)) != 0) {
348		printf("nand_unlock: Start address must be beginning of "
349			"nand block!\n");
350		ret = -1;
351		goto out;
352	}
353
354	if (length == 0 || (length & (mtd->erasesize - 1)) != 0) {
355		printf("nand_unlock: Length must be a multiple of nand block "
356			"size %08x!\n", mtd->erasesize);
357		ret = -1;
358		goto out;
359	}
360
361	/*
362	 * Set length so that the last address is set to the
363	 * starting address of the last block
364	 */
365	length -= mtd->erasesize;
366
367	/* submit address of first page to unlock */
368	chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
369
370	/* submit ADDRESS of LAST page to unlock */
371	page += (int)(length >> chip->page_shift);
372
373	/*
374	 * Page addresses for unlocking are supposed to be block-aligned.
375	 * At least some NAND chips use the low bit to indicate that the
376	 * page range should be inverted.
377	 */
378	if (allexcept)
379		page |= 1;
380
381	chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1, page & chip->pagemask);
382
383	/* call wait ready function */
384	status = chip->waitfunc(mtd, chip);
385	/* see if device thinks it succeeded */
386	if (status & 0x01) {
387		/* there was an error */
388		ret = -1;
389		goto out;
390	}
391
392 out:
393	/* de-select the NAND device */
394	chip->select_chip(mtd, -1);
395	return ret;
396}
397#endif
398
399/**
400 * check_skip_len
401 *
402 * Check if there are any bad blocks, and whether length including bad
403 * blocks fits into device
404 *
405 * @param mtd nand mtd instance
406 * @param offset offset in flash
407 * @param length image length
408 * @param used length of flash needed for the requested length
409 * Return: 0 if the image fits and there are no bad blocks
410 *         1 if the image fits, but there are bad blocks
411 *        -1 if the image does not fit
412 */
413static int check_skip_len(struct mtd_info *mtd, loff_t offset, size_t length,
414			  size_t *used)
415{
416	size_t len_excl_bad = 0;
417	int ret = 0;
418
419	while (len_excl_bad < length) {
420		size_t block_len, block_off;
421		loff_t block_start;
422
423		if (offset >= mtd->size)
424			return -1;
425
426		block_start = offset & ~(loff_t)(mtd->erasesize - 1);
427		block_off = offset & (mtd->erasesize - 1);
428		block_len = mtd->erasesize - block_off;
429
430		if (!nand_block_isbad(mtd, block_start))
431			len_excl_bad += block_len;
432		else
433			ret = 1;
434
435		offset += block_len;
436		*used += block_len;
437	}
438
439	/* If the length is not a multiple of block_len, adjust. */
440	if (len_excl_bad > length)
441		*used -= (len_excl_bad - length);
442
443	return ret;
444}
445
446#ifdef CONFIG_CMD_NAND_TRIMFFS
447static size_t drop_ffs(const struct mtd_info *mtd, const u_char *buf,
448			const size_t *len)
449{
450	size_t l = *len;
451	ssize_t i;
452
453	for (i = l - 1; i >= 0; i--)
454		if (buf[i] != 0xFF)
455			break;
456
457	/* The resulting length must be aligned to the minimum flash I/O size */
458	l = i + 1;
459	l = (l + mtd->writesize - 1) / mtd->writesize;
460	l *=  mtd->writesize;
461
462	/*
463	 * since the input length may be unaligned, prevent access past the end
464	 * of the buffer
465	 */
466	return min(l, *len);
467}
468#endif
469
470/**
471 * nand_verify_page_oob:
472 *
473 * Verify a page of NAND flash, including the OOB.
474 * Reads page of NAND and verifies the contents and OOB against the
475 * values in ops.
476 *
477 * @param mtd		nand mtd instance
478 * @param ops		MTD operations, including data to verify
479 * @param ofs		offset in flash
480 * Return:		0 in case of success
481 */
482int nand_verify_page_oob(struct mtd_info *mtd, struct mtd_oob_ops *ops,
483			 loff_t ofs)
484{
485	int rval;
486	struct mtd_oob_ops vops;
487	size_t verlen = mtd->writesize + mtd->oobsize;
488
489	memcpy(&vops, ops, sizeof(vops));
490
491	vops.datbuf = memalign(ARCH_DMA_MINALIGN, verlen);
492
493	if (!vops.datbuf)
494		return -ENOMEM;
495
496	vops.oobbuf = vops.datbuf + mtd->writesize;
497
498	rval = mtd_read_oob(mtd, ofs, &vops);
499	if (!rval)
500		rval = memcmp(ops->datbuf, vops.datbuf, vops.len);
501	if (!rval)
502		rval = memcmp(ops->oobbuf, vops.oobbuf, vops.ooblen);
503
504	free(vops.datbuf);
505
506	return rval ? -EIO : 0;
507}
508
509/**
510 * nand_verify:
511 *
512 * Verify a region of NAND flash.
513 * Reads NAND in page-sized chunks and verifies the contents against
514 * the contents of a buffer.  The offset into the NAND must be
515 * page-aligned, and the function doesn't handle skipping bad blocks.
516 *
517 * @param mtd		nand mtd instance
518 * @param ofs		offset in flash
519 * @param len		buffer length
520 * @param buf		buffer to read from
521 * Return:		0 in case of success
522 */
523int nand_verify(struct mtd_info *mtd, loff_t ofs, size_t len, u_char *buf)
524{
525	int rval = 0;
526	size_t verofs;
527	size_t verlen = mtd->writesize;
528	uint8_t *verbuf = memalign(ARCH_DMA_MINALIGN, verlen);
529
530	if (!verbuf)
531		return -ENOMEM;
532
533	/* Read the NAND back in page-size groups to limit malloc size */
534	for (verofs = ofs; verofs < ofs + len;
535	     verofs += verlen, buf += verlen) {
536		verlen = min(mtd->writesize, (uint32_t)(ofs + len - verofs));
537		rval = nand_read(mtd, verofs, &verlen, verbuf);
538		if (!rval || (rval == -EUCLEAN))
539			rval = memcmp(buf, verbuf, verlen);
540
541		if (rval)
542			break;
543	}
544
545	free(verbuf);
546
547	return rval ? -EIO : 0;
548}
549
550/**
551 * nand_write_skip_bad:
552 *
553 * Write image to NAND flash.
554 * Blocks that are marked bad are skipped and the is written to the next
555 * block instead as long as the image is short enough to fit even after
556 * skipping the bad blocks.  Due to bad blocks we may not be able to
557 * perform the requested write.  In the case where the write would
558 * extend beyond the end of the NAND device, both length and actual (if
559 * not NULL) are set to 0.  In the case where the write would extend
560 * beyond the limit we are passed, length is set to 0 and actual is set
561 * to the required length.
562 *
563 * @param mtd		nand mtd instance
564 * @param offset	offset in flash
565 * @param length	buffer length
566 * @param actual	set to size required to write length worth of
567 *			buffer or 0 on error, if not NULL
568 * @param lim		maximum size that actual may be in order to not
569 *			exceed the buffer
570 * @param buffer        buffer to read from
571 * @param flags		flags modifying the behaviour of the write to NAND
572 * Return:		0 in case of success
573 */
574int nand_write_skip_bad(struct mtd_info *mtd, loff_t offset, size_t *length,
575			size_t *actual, loff_t lim, u_char *buffer, int flags)
576{
577	int rval = 0, blocksize;
578	size_t left_to_write = *length;
579	size_t used_for_write = 0;
580	u_char *p_buffer = buffer;
581	int need_skip;
582
583	if (actual)
584		*actual = 0;
585
586	blocksize = mtd->erasesize;
587
588	/*
589	 * nand_write() handles unaligned, partial page writes.
590	 *
591	 * We allow length to be unaligned, for convenience in
592	 * using the $filesize variable.
593	 *
594	 * However, starting at an unaligned offset makes the
595	 * semantics of bad block skipping ambiguous (really,
596	 * you should only start a block skipping access at a
597	 * partition boundary).  So don't try to handle that.
598	 */
599	if ((offset & (mtd->writesize - 1)) != 0) {
600		printf("Attempt to write non page-aligned data\n");
601		*length = 0;
602		return -EINVAL;
603	}
604
605	need_skip = check_skip_len(mtd, offset, *length, &used_for_write);
606
607	if (actual)
608		*actual = used_for_write;
609
610	if (need_skip < 0) {
611		printf("Attempt to write outside the flash area\n");
612		*length = 0;
613		return -EINVAL;
614	}
615
616	if (used_for_write > lim) {
617		puts("Size of write exceeds partition or device limit\n");
618		*length = 0;
619		return -EFBIG;
620	}
621
622	if (!need_skip && !(flags & WITH_DROP_FFS)) {
623		rval = nand_write(mtd, offset, length, buffer);
624
625		if ((flags & WITH_WR_VERIFY) && !rval)
626			rval = nand_verify(mtd, offset, *length, buffer);
627
628		if (rval == 0)
629			return 0;
630
631		*length = 0;
632		printf("NAND write to offset %llx failed %d\n",
633			offset, rval);
634		return rval;
635	}
636
637	while (left_to_write > 0) {
638		loff_t block_start = offset & ~(loff_t)(mtd->erasesize - 1);
639		size_t block_offset = offset & (mtd->erasesize - 1);
640		size_t write_size, truncated_write_size;
641
642		schedule();
643
644		if (nand_block_isbad(mtd, block_start)) {
645			printf("Skip bad block 0x%08llx\n", block_start);
646			offset += mtd->erasesize - block_offset;
647			continue;
648		}
649
650		if (left_to_write < (blocksize - block_offset))
651			write_size = left_to_write;
652		else
653			write_size = blocksize - block_offset;
654
655		truncated_write_size = write_size;
656#ifdef CONFIG_CMD_NAND_TRIMFFS
657		if (flags & WITH_DROP_FFS)
658			truncated_write_size = drop_ffs(mtd, p_buffer,
659					&write_size);
660#endif
661
662		rval = nand_write(mtd, offset, &truncated_write_size,
663				p_buffer);
664
665		if ((flags & WITH_WR_VERIFY) && !rval)
666			rval = nand_verify(mtd, offset,
667				truncated_write_size, p_buffer);
668
669		offset += write_size;
670		p_buffer += write_size;
671
672		if (rval != 0) {
673			printf("NAND write to offset %llx failed %d\n",
674				offset, rval);
675			*length -= left_to_write;
676			return rval;
677		}
678
679		left_to_write -= write_size;
680	}
681
682	return 0;
683}
684
685/**
686 * nand_read_skip_bad:
687 *
688 * Read image from NAND flash.
689 * Blocks that are marked bad are skipped and the next block is read
690 * instead as long as the image is short enough to fit even after
691 * skipping the bad blocks.  Due to bad blocks we may not be able to
692 * perform the requested read.  In the case where the read would extend
693 * beyond the end of the NAND device, both length and actual (if not
694 * NULL) are set to 0.  In the case where the read would extend beyond
695 * the limit we are passed, length is set to 0 and actual is set to the
696 * required length.
697 *
698 * @param mtd nand mtd instance
699 * @param offset offset in flash
700 * @param length buffer length, on return holds number of read bytes
701 * @param actual set to size required to read length worth of buffer or 0
702 * on error, if not NULL
703 * @param lim maximum size that actual may be in order to not exceed the
704 * buffer
705 * @param buffer buffer to write to
706 * Return: 0 in case of success
707 */
708int nand_read_skip_bad(struct mtd_info *mtd, loff_t offset, size_t *length,
709		       size_t *actual, loff_t lim, u_char *buffer)
710{
711	int rval;
712	size_t left_to_read = *length;
713	size_t used_for_read = 0;
714	u_char *p_buffer = buffer;
715	int need_skip;
716
717	if ((offset & (mtd->writesize - 1)) != 0) {
718		printf("Attempt to read non page-aligned data\n");
719		*length = 0;
720		if (actual)
721			*actual = 0;
722		return -EINVAL;
723	}
724
725	need_skip = check_skip_len(mtd, offset, *length, &used_for_read);
726
727	if (actual)
728		*actual = used_for_read;
729
730	if (need_skip < 0) {
731		printf("Attempt to read outside the flash area\n");
732		*length = 0;
733		return -EINVAL;
734	}
735
736	if (used_for_read > lim) {
737		puts("Size of read exceeds partition or device limit\n");
738		*length = 0;
739		return -EFBIG;
740	}
741
742	if (!need_skip) {
743		rval = nand_read(mtd, offset, length, buffer);
744		if (!rval || rval == -EUCLEAN)
745			return 0;
746
747		*length = 0;
748		printf("NAND read from offset %llx failed %d\n",
749			offset, rval);
750		return rval;
751	}
752
753	while (left_to_read > 0) {
754		size_t block_offset = offset & (mtd->erasesize - 1);
755		size_t read_length;
756
757		schedule();
758
759		if (nand_block_isbad(mtd, offset & ~(mtd->erasesize - 1))) {
760			printf("Skipping bad block 0x%08llx\n",
761				offset & ~(mtd->erasesize - 1));
762			offset += mtd->erasesize - block_offset;
763			continue;
764		}
765
766		if (left_to_read < (mtd->erasesize - block_offset))
767			read_length = left_to_read;
768		else
769			read_length = mtd->erasesize - block_offset;
770
771		rval = nand_read(mtd, offset, &read_length, p_buffer);
772		if (rval && rval != -EUCLEAN) {
773			printf("NAND read from offset %llx failed %d\n",
774				offset, rval);
775			*length -= left_to_read;
776			return rval;
777		}
778
779		left_to_read -= read_length;
780		offset       += read_length;
781		p_buffer     += read_length;
782	}
783
784	return 0;
785}
786
787#ifdef CONFIG_CMD_NAND_TORTURE
788
789/**
790 * check_pattern:
791 *
792 * Check if buffer contains only a certain byte pattern.
793 *
794 * @param buf buffer to check
795 * @param patt the pattern to check
796 * @param size buffer size in bytes
797 * Return: 1 if there are only patt bytes in buf
798 *         0 if something else was found
799 */
800static int check_pattern(const u_char *buf, u_char patt, int size)
801{
802	int i;
803
804	for (i = 0; i < size; i++)
805		if (buf[i] != patt)
806			return 0;
807	return 1;
808}
809
810/**
811 * nand_torture:
812 *
813 * Torture a block of NAND flash.
814 * This is useful to determine if a block that caused a write error is still
815 * good or should be marked as bad.
816 *
817 * @param mtd nand mtd instance
818 * @param offset offset in flash
819 * Return: 0 if the block is still good
820 */
821int nand_torture(struct mtd_info *mtd, loff_t offset)
822{
823	u_char patterns[] = {0xa5, 0x5a, 0x00};
824	struct erase_info instr = {
825		.mtd = mtd,
826		.addr = offset,
827		.len = mtd->erasesize,
828	};
829	size_t retlen;
830	int err, ret = -1, i, patt_count;
831	u_char *buf;
832
833	if ((offset & (mtd->erasesize - 1)) != 0) {
834		puts("Attempt to torture a block at a non block-aligned offset\n");
835		return -EINVAL;
836	}
837
838	if (offset + mtd->erasesize > mtd->size) {
839		puts("Attempt to torture a block outside the flash area\n");
840		return -EINVAL;
841	}
842
843	patt_count = ARRAY_SIZE(patterns);
844
845	buf = malloc_cache_aligned(mtd->erasesize);
846	if (buf == NULL) {
847		puts("Out of memory for erase block buffer\n");
848		return -ENOMEM;
849	}
850
851	for (i = 0; i < patt_count; i++) {
852		err = mtd_erase(mtd, &instr);
853		if (err) {
854			printf("%s: erase() failed for block at 0x%llx: %d\n",
855				mtd->name, instr.addr, err);
856			goto out;
857		}
858
859		/* Make sure the block contains only 0xff bytes */
860		err = mtd_read(mtd, offset, mtd->erasesize, &retlen, buf);
861		if ((err && err != -EUCLEAN) || retlen != mtd->erasesize) {
862			printf("%s: read() failed for block at 0x%llx: %d\n",
863				mtd->name, instr.addr, err);
864			goto out;
865		}
866
867		err = check_pattern(buf, 0xff, mtd->erasesize);
868		if (!err) {
869			printf("Erased block at 0x%llx, but a non-0xff byte was found\n",
870				offset);
871			ret = -EIO;
872			goto out;
873		}
874
875		/* Write a pattern and check it */
876		memset(buf, patterns[i], mtd->erasesize);
877		err = mtd_write(mtd, offset, mtd->erasesize, &retlen, buf);
878		if (err || retlen != mtd->erasesize) {
879			printf("%s: write() failed for block at 0x%llx: %d\n",
880				mtd->name, instr.addr, err);
881			goto out;
882		}
883
884		err = mtd_read(mtd, offset, mtd->erasesize, &retlen, buf);
885		if ((err && err != -EUCLEAN) || retlen != mtd->erasesize) {
886			printf("%s: read() failed for block at 0x%llx: %d\n",
887				mtd->name, instr.addr, err);
888			goto out;
889		}
890
891		err = check_pattern(buf, patterns[i], mtd->erasesize);
892		if (!err) {
893			printf("Pattern 0x%.2x checking failed for block at "
894					"0x%llx\n", patterns[i], offset);
895			ret = -EIO;
896			goto out;
897		}
898	}
899
900	ret = 0;
901
902out:
903	free(buf);
904	return ret;
905}
906
907#endif
908