io.c 41.6 KB
Newer Older
A
Artem B. Bityutskiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Copyright (c) International Business Machines Corp., 2006
 * Copyright (c) Nokia Corporation, 2006, 2007
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
 * the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Author: Artem Bityutskiy (Битюцкий Артём)
 */

/*
A
Artem Bityutskiy 已提交
23
 * UBI input/output sub-system.
A
Artem B. Bityutskiy 已提交
24
 *
A
Artem Bityutskiy 已提交
25 26 27
 * This sub-system provides a uniform way to work with all kinds of the
 * underlying MTD devices. It also implements handy functions for reading and
 * writing UBI headers.
A
Artem B. Bityutskiy 已提交
28 29
 *
 * We are trying to have a paranoid mindset and not to trust to what we read
A
Artem Bityutskiy 已提交
30 31
 * from the flash media in order to be more secure and robust. So this
 * sub-system validates every single header it reads from the flash media.
A
Artem B. Bityutskiy 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
 *
 * Some words about how the eraseblock headers are stored.
 *
 * The erase counter header is always stored at offset zero. By default, the
 * VID header is stored after the EC header at the closest aligned offset
 * (i.e. aligned to the minimum I/O unit size). Data starts next to the VID
 * header at the closest aligned offset. But this default layout may be
 * changed. For example, for different reasons (e.g., optimization) UBI may be
 * asked to put the VID header at further offset, and even at an unaligned
 * offset. Of course, if the offset of the VID header is unaligned, UBI adds
 * proper padding in front of it. Data offset may also be changed but it has to
 * be aligned.
 *
 * About minimal I/O units. In general, UBI assumes flash device model where
 * there is only one minimal I/O unit size. E.g., in case of NOR flash it is 1,
 * in case of NAND flash it is a NAND page, etc. This is reported by MTD in the
 * @ubi->mtd->writesize field. But as an exception, UBI admits of using another
 * (smaller) minimal I/O unit size for EC and VID headers to make it possible
 * to do different optimizations.
 *
 * This is extremely useful in case of NAND flashes which admit of several
 * write operations to one NAND page. In this case UBI can fit EC and VID
 * headers at one NAND page. Thus, UBI may use "sub-page" size as the minimal
 * I/O unit for the headers (the @ubi->hdrs_min_io_size field). But it still
 * reports NAND page size (@ubi->min_io_size) as a minimal I/O unit for the UBI
 * users.
 *
 * Example: some Samsung NANDs with 2KiB pages allow 4x 512-byte writes, so
 * although the minimal I/O unit is 2K, UBI uses 512 bytes for EC and VID
 * headers.
 *
 * Q: why not just to treat sub-page as a minimal I/O unit of this flash
 * device, e.g., make @ubi->min_io_size = 512 in the example above?
 *
 * A: because when writing a sub-page, MTD still writes a full 2K page but the
S
Shinya Kuribayashi 已提交
67 68 69
 * bytes which are not relevant to the sub-page are 0xFF. So, basically,
 * writing 4x512 sub-pages is 4 times slower than writing one 2KiB NAND page.
 * Thus, we prefer to use sub-pages only for EC and VID headers.
A
Artem B. Bityutskiy 已提交
70 71 72 73 74 75 76 77 78 79 80 81
 *
 * As it was noted above, the VID header may start at a non-aligned offset.
 * For example, in case of a 2KiB page NAND flash with a 512 bytes sub-page,
 * the VID header may reside at offset 1984 which is the last 64 bytes of the
 * last sub-page (EC header is always at offset zero). This causes some
 * difficulties when reading and writing VID headers.
 *
 * Suppose we have a 64-byte buffer and we read a VID header at it. We change
 * the data and want to write this VID header out. As we can only write in
 * 512-byte chunks, we have to allocate one more buffer and copy our VID header
 * to offset 448 of this buffer.
 *
A
Artem Bityutskiy 已提交
82 83 84 85 86
 * The I/O sub-system does the following trick in order to avoid this extra
 * copy. It always allocates a @ubi->vid_hdr_alsize bytes buffer for the VID
 * header and returns a pointer to offset @ubi->vid_hdr_shift of this buffer.
 * When the VID header is being written out, it shifts the VID header pointer
 * back and writes the whole sub-page.
A
Artem B. Bityutskiy 已提交
87 88 89 90
 */

#include <linux/crc32.h>
#include <linux/err.h>
91
#include <linux/slab.h>
A
Artem B. Bityutskiy 已提交
92 93
#include "ubi.h"

94 95 96 97 98 99 100
static int self_check_not_bad(const struct ubi_device *ubi, int pnum);
static int self_check_peb_ec_hdr(const struct ubi_device *ubi, int pnum);
static int self_check_ec_hdr(const struct ubi_device *ubi, int pnum,
			     const struct ubi_ec_hdr *ec_hdr);
static int self_check_peb_vid_hdr(const struct ubi_device *ubi, int pnum);
static int self_check_vid_hdr(const struct ubi_device *ubi, int pnum,
			      const struct ubi_vid_hdr *vid_hdr);
101 102
static int self_check_write(struct ubi_device *ubi, const void *buf, int pnum,
			    int offset, int len);
A
Artem B. Bityutskiy 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

/**
 * ubi_io_read - read data from a physical eraseblock.
 * @ubi: UBI device description object
 * @buf: buffer where to store the read data
 * @pnum: physical eraseblock number to read from
 * @offset: offset within the physical eraseblock from where to read
 * @len: how many bytes to read
 *
 * This function reads data from offset @offset of physical eraseblock @pnum
 * and stores the read data in the @buf buffer. The following return codes are
 * possible:
 *
 * o %0 if all the requested data were successfully read;
 * o %UBI_IO_BITFLIPS if all the requested data were successfully read, but
 *   correctable bit-flips were detected; this is harmless but may indicate
 *   that this eraseblock may become bad soon (but do not have to);
A
Artem Bityutskiy 已提交
120 121 122
 * o %-EBADMSG if the MTD subsystem reported about data integrity problems, for
 *   example it can be an ECC error in case of NAND; this most probably means
 *   that the data is corrupted;
A
Artem B. Bityutskiy 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
 * o %-EIO if some I/O error occurred;
 * o other negative error codes in case of other errors.
 */
int ubi_io_read(const struct ubi_device *ubi, void *buf, int pnum, int offset,
		int len)
{
	int err, retries = 0;
	size_t read;
	loff_t addr;

	dbg_io("read %d bytes from PEB %d:%d", len, pnum, offset);

	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);
	ubi_assert(offset >= 0 && offset + len <= ubi->peb_size);
	ubi_assert(len > 0);

139
	err = self_check_not_bad(ubi, pnum);
A
Artem B. Bityutskiy 已提交
140
	if (err)
141
		return err;
A
Artem B. Bityutskiy 已提交
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
	/*
	 * Deliberately corrupt the buffer to improve robustness. Indeed, if we
	 * do not do this, the following may happen:
	 * 1. The buffer contains data from previous operation, e.g., read from
	 *    another PEB previously. The data looks like expected, e.g., if we
	 *    just do not read anything and return - the caller would not
	 *    notice this. E.g., if we are reading a VID header, the buffer may
	 *    contain a valid VID header from another PEB.
	 * 2. The driver is buggy and returns us success or -EBADMSG or
	 *    -EUCLEAN, but it does not actually put any data to the buffer.
	 *
	 * This may confuse UBI or upper layers - they may think the buffer
	 * contains valid data while in fact it is just old data. This is
	 * especially possible because UBI (and UBIFS) relies on CRC, and
	 * treats data as correct even in case of ECC errors if the CRC is
	 * correct.
	 *
	 * Try to prevent this situation by changing the first byte of the
	 * buffer.
	 */
	*((uint8_t *)buf) ^= 0xFF;

A
Artem B. Bityutskiy 已提交
165 166
	addr = (loff_t)pnum * ubi->peb_size + offset;
retry:
167
	err = mtd_read(ubi->mtd, addr, len, &read, buf);
A
Artem B. Bityutskiy 已提交
168
	if (err) {
169
		const char *errstr = mtd_is_eccerr(err) ? " (ECC error)" : "";
170

171
		if (mtd_is_bitflip(err)) {
A
Artem B. Bityutskiy 已提交
172 173 174
			/*
			 * -EUCLEAN is reported if there was a bit-flip which
			 * was corrected, so this is harmless.
175 176 177 178
			 *
			 * We do not report about it here unless debugging is
			 * enabled. A corresponding message will be printed
			 * later, when it is has been scrubbed.
A
Artem B. Bityutskiy 已提交
179
			 */
180 181
			ubi_msg(ubi, "fixable bit-flip detected at PEB %d",
				pnum);
A
Artem B. Bityutskiy 已提交
182 183 184 185
			ubi_assert(len == read);
			return UBI_IO_BITFLIPS;
		}

186
		if (retries++ < UBI_IO_RETRIES) {
187
			ubi_warn(ubi, "error %d%s while reading %d bytes from PEB %d:%d, read only %zd bytes, retry",
188
				 err, errstr, len, pnum, offset, read);
A
Artem B. Bityutskiy 已提交
189 190 191 192
			yield();
			goto retry;
		}

193
		ubi_err(ubi, "error %d%s while reading %d bytes from PEB %d:%d, read %zd bytes",
A
Artem Bityutskiy 已提交
194
			err, errstr, len, pnum, offset, read);
195
		dump_stack();
196 197 198 199 200 201

		/*
		 * The driver should never return -EBADMSG if it failed to read
		 * all the requested data. But some buggy drivers might do
		 * this, so we change it to -EIO.
		 */
202
		if (read != len && mtd_is_eccerr(err)) {
203 204 205
			ubi_assert(0);
			err = -EIO;
		}
A
Artem B. Bityutskiy 已提交
206 207 208
	} else {
		ubi_assert(len == read);

209
		if (ubi_dbg_is_bitflip(ubi)) {
210
			dbg_gen("bit-flip (emulated)");
A
Artem B. Bityutskiy 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
			err = UBI_IO_BITFLIPS;
		}
	}

	return err;
}

/**
 * ubi_io_write - write data to a physical eraseblock.
 * @ubi: UBI device description object
 * @buf: buffer with the data to write
 * @pnum: physical eraseblock number to write to
 * @offset: offset within the physical eraseblock where to write
 * @len: how many bytes to write
 *
 * This function writes @len bytes of data from buffer @buf to offset @offset
 * of physical eraseblock @pnum. If all the data were successfully written,
 * zero is returned. If an error occurred, this function returns a negative
 * error code. If %-EIO is returned, the physical eraseblock most probably went
 * bad.
 *
 * Note, in case of an error, it is possible that something was still written
 * to the flash media, but may be some garbage.
 */
235 236
int ubi_io_write(struct ubi_device *ubi, const void *buf, int pnum, int offset,
		 int len)
A
Artem B. Bityutskiy 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249
{
	int err;
	size_t written;
	loff_t addr;

	dbg_io("write %d bytes to PEB %d:%d", len, pnum, offset);

	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);
	ubi_assert(offset >= 0 && offset + len <= ubi->peb_size);
	ubi_assert(offset % ubi->hdrs_min_io_size == 0);
	ubi_assert(len > 0 && len % ubi->hdrs_min_io_size == 0);

	if (ubi->ro_mode) {
250
		ubi_err(ubi, "read-only mode");
A
Artem B. Bityutskiy 已提交
251 252 253
		return -EROFS;
	}

254
	err = self_check_not_bad(ubi, pnum);
A
Artem B. Bityutskiy 已提交
255
	if (err)
256
		return err;
A
Artem B. Bityutskiy 已提交
257 258

	/* The area we are writing to has to contain all 0xFF bytes */
259
	err = ubi_self_check_all_ff(ubi, pnum, offset, len);
A
Artem B. Bityutskiy 已提交
260
	if (err)
261
		return err;
A
Artem B. Bityutskiy 已提交
262 263 264 265 266 267

	if (offset >= ubi->leb_start) {
		/*
		 * We write to the data area of the physical eraseblock. Make
		 * sure it has valid EC and VID headers.
		 */
268
		err = self_check_peb_ec_hdr(ubi, pnum);
A
Artem B. Bityutskiy 已提交
269
		if (err)
270
			return err;
271
		err = self_check_peb_vid_hdr(ubi, pnum);
A
Artem B. Bityutskiy 已提交
272
		if (err)
273
			return err;
A
Artem B. Bityutskiy 已提交
274 275
	}

276
	if (ubi_dbg_is_write_failure(ubi)) {
277
		ubi_err(ubi, "cannot write %d bytes to PEB %d:%d (emulated)",
A
Artem Bityutskiy 已提交
278
			len, pnum, offset);
279
		dump_stack();
A
Artem B. Bityutskiy 已提交
280 281 282 283
		return -EIO;
	}

	addr = (loff_t)pnum * ubi->peb_size + offset;
284
	err = mtd_write(ubi->mtd, addr, len, &written, buf);
A
Artem B. Bityutskiy 已提交
285
	if (err) {
286
		ubi_err(ubi, "error %d while writing %d bytes to PEB %d:%d, written %zd bytes",
A
Artem Bityutskiy 已提交
287
			err, len, pnum, offset, written);
288
		dump_stack();
289
		ubi_dump_flash(ubi, pnum, offset, len);
A
Artem B. Bityutskiy 已提交
290 291 292
	} else
		ubi_assert(written == len);

A
Artem Bityutskiy 已提交
293
	if (!err) {
294
		err = self_check_write(ubi, buf, pnum, offset, len);
A
Artem Bityutskiy 已提交
295 296 297 298 299 300 301 302 303 304
		if (err)
			return err;

		/*
		 * Since we always write sequentially, the rest of the PEB has
		 * to contain only 0xFF bytes.
		 */
		offset += len;
		len = ubi->peb_size - offset;
		if (len)
305
			err = ubi_self_check_all_ff(ubi, pnum, offset, len);
A
Artem Bityutskiy 已提交
306 307
	}

A
Artem B. Bityutskiy 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
	return err;
}

/**
 * erase_callback - MTD erasure call-back.
 * @ei: MTD erase information object.
 *
 * Note, even though MTD erase interface is asynchronous, all the current
 * implementations are synchronous anyway.
 */
static void erase_callback(struct erase_info *ei)
{
	wake_up_interruptible((wait_queue_head_t *)ei->priv);
}

/**
 * do_sync_erase - synchronously erase a physical eraseblock.
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to erase
 *
 * This function synchronously erases physical eraseblock @pnum and returns
 * zero in case of success and a negative error code in case of failure. If
 * %-EIO is returned, the physical eraseblock most probably went bad.
 */
332
static int do_sync_erase(struct ubi_device *ubi, int pnum)
A
Artem B. Bityutskiy 已提交
333 334 335 336 337 338
{
	int err, retries = 0;
	struct erase_info ei;
	wait_queue_head_t wq;

	dbg_io("erase PEB %d", pnum);
339 340 341
	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);

	if (ubi->ro_mode) {
342
		ubi_err(ubi, "read-only mode");
343 344
		return -EROFS;
	}
A
Artem B. Bityutskiy 已提交
345 346 347 348 349 350

retry:
	init_waitqueue_head(&wq);
	memset(&ei, 0, sizeof(struct erase_info));

	ei.mtd      = ubi->mtd;
351
	ei.addr     = (loff_t)pnum * ubi->peb_size;
A
Artem B. Bityutskiy 已提交
352 353 354 355
	ei.len      = ubi->peb_size;
	ei.callback = erase_callback;
	ei.priv     = (unsigned long)&wq;

356
	err = mtd_erase(ubi->mtd, &ei);
A
Artem B. Bityutskiy 已提交
357 358
	if (err) {
		if (retries++ < UBI_IO_RETRIES) {
359
			ubi_warn(ubi, "error %d while erasing PEB %d, retry",
360
				 err, pnum);
A
Artem B. Bityutskiy 已提交
361 362 363
			yield();
			goto retry;
		}
364
		ubi_err(ubi, "cannot erase PEB %d, error %d", pnum, err);
365
		dump_stack();
A
Artem B. Bityutskiy 已提交
366 367 368 369 370 371
		return err;
	}

	err = wait_event_interruptible(wq, ei.state == MTD_ERASE_DONE ||
					   ei.state == MTD_ERASE_FAILED);
	if (err) {
372
		ubi_err(ubi, "interrupted PEB %d erasure", pnum);
A
Artem B. Bityutskiy 已提交
373 374 375 376 377
		return -EINTR;
	}

	if (ei.state == MTD_ERASE_FAILED) {
		if (retries++ < UBI_IO_RETRIES) {
378 379
			ubi_warn(ubi, "error while erasing PEB %d, retry",
				 pnum);
A
Artem B. Bityutskiy 已提交
380 381 382
			yield();
			goto retry;
		}
383
		ubi_err(ubi, "cannot erase PEB %d", pnum);
384
		dump_stack();
A
Artem B. Bityutskiy 已提交
385 386 387
		return -EIO;
	}

388
	err = ubi_self_check_all_ff(ubi, pnum, 0, ubi->peb_size);
A
Artem B. Bityutskiy 已提交
389
	if (err)
390
		return err;
A
Artem B. Bityutskiy 已提交
391

392
	if (ubi_dbg_is_erase_failure(ubi)) {
393
		ubi_err(ubi, "cannot erase PEB %d (emulated)", pnum);
A
Artem B. Bityutskiy 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		return -EIO;
	}

	return 0;
}

/* Patterns to write to a physical eraseblock when torturing it */
static uint8_t patterns[] = {0xa5, 0x5a, 0x0};

/**
 * torture_peb - test a supposedly bad physical eraseblock.
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to test
 *
 * This function returns %-EIO if the physical eraseblock did not pass the
 * test, a positive number of erase operations done if the test was
 * successfully passed, and other negative error codes in case of other errors.
 */
412
static int torture_peb(struct ubi_device *ubi, int pnum)
A
Artem B. Bityutskiy 已提交
413 414 415
{
	int err, i, patt_count;

416
	ubi_msg(ubi, "run torture test for PEB %d", pnum);
A
Artem B. Bityutskiy 已提交
417 418 419
	patt_count = ARRAY_SIZE(patterns);
	ubi_assert(patt_count > 0);

420
	mutex_lock(&ubi->buf_mutex);
A
Artem B. Bityutskiy 已提交
421 422 423 424 425 426
	for (i = 0; i < patt_count; i++) {
		err = do_sync_erase(ubi, pnum);
		if (err)
			goto out;

		/* Make sure the PEB contains only 0xFF bytes */
427
		err = ubi_io_read(ubi, ubi->peb_buf, pnum, 0, ubi->peb_size);
A
Artem B. Bityutskiy 已提交
428 429 430
		if (err)
			goto out;

431
		err = ubi_check_pattern(ubi->peb_buf, 0xFF, ubi->peb_size);
A
Artem B. Bityutskiy 已提交
432
		if (err == 0) {
433
			ubi_err(ubi, "erased PEB %d, but a non-0xFF byte found",
A
Artem B. Bityutskiy 已提交
434 435 436 437 438 439
				pnum);
			err = -EIO;
			goto out;
		}

		/* Write a pattern and check it */
440 441
		memset(ubi->peb_buf, patterns[i], ubi->peb_size);
		err = ubi_io_write(ubi, ubi->peb_buf, pnum, 0, ubi->peb_size);
A
Artem B. Bityutskiy 已提交
442 443 444
		if (err)
			goto out;

445 446
		memset(ubi->peb_buf, ~patterns[i], ubi->peb_size);
		err = ubi_io_read(ubi, ubi->peb_buf, pnum, 0, ubi->peb_size);
A
Artem B. Bityutskiy 已提交
447 448 449
		if (err)
			goto out;

450
		err = ubi_check_pattern(ubi->peb_buf, patterns[i],
451
					ubi->peb_size);
A
Artem B. Bityutskiy 已提交
452
		if (err == 0) {
453
			ubi_err(ubi, "pattern %x checking failed for PEB %d",
A
Artem B. Bityutskiy 已提交
454 455 456 457 458 459 460
				patterns[i], pnum);
			err = -EIO;
			goto out;
		}
	}

	err = patt_count;
461
	ubi_msg(ubi, "PEB %d passed torture test, do not mark it as bad", pnum);
A
Artem B. Bityutskiy 已提交
462 463

out:
464
	mutex_unlock(&ubi->buf_mutex);
465
	if (err == UBI_IO_BITFLIPS || mtd_is_eccerr(err)) {
A
Artem B. Bityutskiy 已提交
466 467 468 469 470
		/*
		 * If a bit-flip or data integrity error was detected, the test
		 * has not passed because it happened on a freshly erased
		 * physical eraseblock which means something is wrong with it.
		 */
471
		ubi_err(ubi, "read problems on freshly erased PEB %d, must be bad",
A
Artem Bityutskiy 已提交
472
			pnum);
A
Artem B. Bityutskiy 已提交
473
		err = -EIO;
A
Artem Bityutskiy 已提交
474
	}
A
Artem B. Bityutskiy 已提交
475 476 477
	return err;
}

A
Artem Bityutskiy 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
/**
 * nor_erase_prepare - prepare a NOR flash PEB for erasure.
 * @ubi: UBI device description object
 * @pnum: physical eraseblock number to prepare
 *
 * NOR flash, or at least some of them, have peculiar embedded PEB erasure
 * algorithm: the PEB is first filled with zeroes, then it is erased. And
 * filling with zeroes starts from the end of the PEB. This was observed with
 * Spansion S29GL512N NOR flash.
 *
 * This means that in case of a power cut we may end up with intact data at the
 * beginning of the PEB, and all zeroes at the end of PEB. In other words, the
 * EC and VID headers are OK, but a large chunk of data at the end of PEB is
 * zeroed. This makes UBI mistakenly treat this PEB as used and associate it
 * with an LEB, which leads to subsequent failures (e.g., UBIFS fails).
 *
 * This function is called before erasing NOR PEBs and it zeroes out EC and VID
 * magic numbers in order to invalidate them and prevent the failures. Returns
 * zero in case of success and a negative error code in case of failure.
 */
static int nor_erase_prepare(struct ubi_device *ubi, int pnum)
{
500
	int err;
A
Artem Bityutskiy 已提交
501 502 503
	size_t written;
	loff_t addr;
	uint32_t data = 0;
504 505
	struct ubi_ec_hdr ec_hdr;

506 507 508 509 510 511 512
	/*
	 * Note, we cannot generally define VID header buffers on stack,
	 * because of the way we deal with these buffers (see the header
	 * comment in this file). But we know this is a NOR-specific piece of
	 * code, so we can do this. But yes, this is error-prone and we should
	 * (pre-)allocate VID header buffer instead.
	 */
513
	struct ubi_vid_hdr vid_hdr;
A
Artem Bityutskiy 已提交
514

515
	/*
516
	 * If VID or EC is valid, we have to corrupt them before erasing.
517 518 519
	 * It is important to first invalidate the EC header, and then the VID
	 * header. Otherwise a power cut may lead to valid EC header and
	 * invalid VID header, in which case UBI will treat this PEB as
520
	 * corrupted and will try to preserve it, and print scary warnings.
521 522
	 */
	addr = (loff_t)pnum * ubi->peb_size;
523 524 525
	err = ubi_io_read_ec_hdr(ubi, pnum, &ec_hdr, 0);
	if (err != UBI_IO_BAD_HDR_EBADMSG && err != UBI_IO_BAD_HDR &&
	    err != UBI_IO_FF){
526
		err = mtd_write(ubi->mtd, addr, 4, &written, (void *)&data);
527 528
		if(err)
			goto error;
A
Artem Bityutskiy 已提交
529 530
	}

531 532 533 534 535 536 537
	err = ubi_io_read_vid_hdr(ubi, pnum, &vid_hdr, 0);
	if (err != UBI_IO_BAD_HDR_EBADMSG && err != UBI_IO_BAD_HDR &&
	    err != UBI_IO_FF){
		addr += ubi->vid_hdr_aloffset;
		err = mtd_write(ubi->mtd, addr, 4, &written, (void *)&data);
		if (err)
			goto error;
538
	}
539
	return 0;
540

541
error:
542
	/*
543 544 545
	 * The PEB contains a valid VID or EC header, but we cannot invalidate
	 * it. Supposedly the flash media or the driver is screwed up, so
	 * return an error.
546
	 */
547
	ubi_err(ubi, "cannot invalidate PEB %d, write returned %d", pnum, err);
548
	ubi_dump_flash(ubi, pnum, 0, ubi->peb_size);
549
	return -EIO;
A
Artem Bityutskiy 已提交
550 551
}

A
Artem B. Bityutskiy 已提交
552 553 554 555 556 557 558 559 560
/**
 * ubi_io_sync_erase - synchronously erase a physical eraseblock.
 * @ubi: UBI device description object
 * @pnum: physical eraseblock number to erase
 * @torture: if this physical eraseblock has to be tortured
 *
 * This function synchronously erases physical eraseblock @pnum. If @torture
 * flag is not zero, the physical eraseblock is checked by means of writing
 * different patterns to it and reading them back. If the torturing is enabled,
561
 * the physical eraseblock is erased more than once.
A
Artem B. Bityutskiy 已提交
562 563 564 565 566 567
 *
 * This function returns the number of erasures made in case of success, %-EIO
 * if the erasure failed or the torturing test failed, and other negative error
 * codes in case of other errors. Note, %-EIO means that the physical
 * eraseblock is bad.
 */
568
int ubi_io_sync_erase(struct ubi_device *ubi, int pnum, int torture)
A
Artem B. Bityutskiy 已提交
569 570 571 572 573
{
	int err, ret = 0;

	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);

574
	err = self_check_not_bad(ubi, pnum);
A
Artem B. Bityutskiy 已提交
575
	if (err != 0)
576
		return err;
A
Artem B. Bityutskiy 已提交
577 578

	if (ubi->ro_mode) {
579
		ubi_err(ubi, "read-only mode");
A
Artem B. Bityutskiy 已提交
580 581 582
		return -EROFS;
	}

A
Artem Bityutskiy 已提交
583 584 585 586 587 588
	if (ubi->nor_flash) {
		err = nor_erase_prepare(ubi, pnum);
		if (err)
			return err;
	}

A
Artem B. Bityutskiy 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	if (torture) {
		ret = torture_peb(ubi, pnum);
		if (ret < 0)
			return ret;
	}

	err = do_sync_erase(ubi, pnum);
	if (err)
		return err;

	return ret + 1;
}

/**
 * ubi_io_is_bad - check if a physical eraseblock is bad.
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to check
 *
 * This function returns a positive number if the physical eraseblock is bad,
 * zero if not, and a negative error code if an error occurred.
 */
int ubi_io_is_bad(const struct ubi_device *ubi, int pnum)
{
	struct mtd_info *mtd = ubi->mtd;

	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);

	if (ubi->bad_allowed) {
		int ret;

619
		ret = mtd_block_isbad(mtd, (loff_t)pnum * ubi->peb_size);
A
Artem B. Bityutskiy 已提交
620
		if (ret < 0)
621
			ubi_err(ubi, "error %d while checking if PEB %d is bad",
A
Artem B. Bityutskiy 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
				ret, pnum);
		else if (ret)
			dbg_io("PEB %d is bad", pnum);
		return ret;
	}

	return 0;
}

/**
 * ubi_io_mark_bad - mark a physical eraseblock as bad.
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to mark
 *
 * This function returns zero in case of success and a negative error code in
 * case of failure.
 */
int ubi_io_mark_bad(const struct ubi_device *ubi, int pnum)
{
	int err;
	struct mtd_info *mtd = ubi->mtd;

	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);

	if (ubi->ro_mode) {
647
		ubi_err(ubi, "read-only mode");
A
Artem B. Bityutskiy 已提交
648 649 650 651 652 653
		return -EROFS;
	}

	if (!ubi->bad_allowed)
		return 0;

654
	err = mtd_block_markbad(mtd, (loff_t)pnum * ubi->peb_size);
A
Artem B. Bityutskiy 已提交
655
	if (err)
656
		ubi_err(ubi, "cannot mark PEB %d bad, error %d", pnum, err);
A
Artem B. Bityutskiy 已提交
657 658 659 660 661 662 663 664 665 666 667
	return err;
}

/**
 * validate_ec_hdr - validate an erase counter header.
 * @ubi: UBI device description object
 * @ec_hdr: the erase counter header to check
 *
 * This function returns zero if the erase counter header is OK, and %1 if
 * not.
 */
668
static int validate_ec_hdr(const struct ubi_device *ubi,
A
Artem B. Bityutskiy 已提交
669 670 671
			   const struct ubi_ec_hdr *ec_hdr)
{
	long long ec;
672
	int vid_hdr_offset, leb_start;
A
Artem B. Bityutskiy 已提交
673

674 675 676
	ec = be64_to_cpu(ec_hdr->ec);
	vid_hdr_offset = be32_to_cpu(ec_hdr->vid_hdr_offset);
	leb_start = be32_to_cpu(ec_hdr->data_offset);
A
Artem B. Bityutskiy 已提交
677 678

	if (ec_hdr->version != UBI_VERSION) {
679
		ubi_err(ubi, "node with incompatible UBI version found: this UBI version is %d, image version is %d",
A
Artem B. Bityutskiy 已提交
680 681 682 683 684
			UBI_VERSION, (int)ec_hdr->version);
		goto bad;
	}

	if (vid_hdr_offset != ubi->vid_hdr_offset) {
685
		ubi_err(ubi, "bad VID header offset %d, expected %d",
A
Artem B. Bityutskiy 已提交
686 687 688 689 690
			vid_hdr_offset, ubi->vid_hdr_offset);
		goto bad;
	}

	if (leb_start != ubi->leb_start) {
691
		ubi_err(ubi, "bad data offset %d, expected %d",
A
Artem B. Bityutskiy 已提交
692 693 694 695 696
			leb_start, ubi->leb_start);
		goto bad;
	}

	if (ec < 0 || ec > UBI_MAX_ERASECOUNTER) {
697
		ubi_err(ubi, "bad erase counter %lld", ec);
A
Artem B. Bityutskiy 已提交
698 699 700 701 702 703
		goto bad;
	}

	return 0;

bad:
704
	ubi_err(ubi, "bad EC header");
705
	ubi_dump_ec_hdr(ec_hdr);
706
	dump_stack();
A
Artem B. Bityutskiy 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
	return 1;
}

/**
 * ubi_io_read_ec_hdr - read and check an erase counter header.
 * @ubi: UBI device description object
 * @pnum: physical eraseblock to read from
 * @ec_hdr: a &struct ubi_ec_hdr object where to store the read erase counter
 * header
 * @verbose: be verbose if the header is corrupted or was not found
 *
 * This function reads erase counter header from physical eraseblock @pnum and
 * stores it in @ec_hdr. This function also checks CRC checksum of the read
 * erase counter header. The following codes may be returned:
 *
 * o %0 if the CRC checksum is correct and the header was successfully read;
 * o %UBI_IO_BITFLIPS if the CRC is correct, but bit-flips were detected
 *   and corrected by the flash driver; this is harmless but may indicate that
 *   this eraseblock may become bad soon (but may be not);
A
Artem Bityutskiy 已提交
726
 * o %UBI_IO_BAD_HDR if the erase counter header is corrupted (a CRC error);
A
Artem Bityutskiy 已提交
727 728
 * o %UBI_IO_BAD_HDR_EBADMSG is the same as %UBI_IO_BAD_HDR, but there also was
 *   a data integrity error (uncorrectable ECC error in case of NAND);
729
 * o %UBI_IO_FF if only 0xFF bytes were read (the PEB is supposedly empty)
A
Artem B. Bityutskiy 已提交
730 731
 * o a negative error code in case of failure.
 */
732
int ubi_io_read_ec_hdr(struct ubi_device *ubi, int pnum,
A
Artem B. Bityutskiy 已提交
733 734
		       struct ubi_ec_hdr *ec_hdr, int verbose)
{
735
	int err, read_err;
A
Artem B. Bityutskiy 已提交
736 737 738 739 740
	uint32_t crc, magic, hdr_crc;

	dbg_io("read EC header from PEB %d", pnum);
	ubi_assert(pnum >= 0 && pnum < ubi->peb_count);

741 742
	read_err = ubi_io_read(ubi, ec_hdr, pnum, 0, UBI_EC_HDR_SIZE);
	if (read_err) {
743
		if (read_err != UBI_IO_BITFLIPS && !mtd_is_eccerr(read_err))
744
			return read_err;
A
Artem B. Bityutskiy 已提交
745 746 747

		/*
		 * We read all the data, but either a correctable bit-flip
A
Artem Bityutskiy 已提交
748 749 750 751 752 753
		 * occurred, or MTD reported a data integrity error
		 * (uncorrectable ECC error in case of NAND). The former is
		 * harmless, the later may mean that the read data is
		 * corrupted. But we have a CRC check-sum and we will detect
		 * this. If the EC header is still OK, we just report this as
		 * there was a bit-flip, to force scrubbing.
A
Artem B. Bityutskiy 已提交
754 755 756
		 */
	}

757
	magic = be32_to_cpu(ec_hdr->magic);
A
Artem B. Bityutskiy 已提交
758
	if (magic != UBI_EC_HDR_MAGIC) {
759
		if (mtd_is_eccerr(read_err))
760
			return UBI_IO_BAD_HDR_EBADMSG;
761

A
Artem B. Bityutskiy 已提交
762 763 764 765 766
		/*
		 * The magic field is wrong. Let's check if we have read all
		 * 0xFF. If yes, this physical eraseblock is assumed to be
		 * empty.
		 */
767
		if (ubi_check_pattern(ec_hdr, 0xFF, UBI_EC_HDR_SIZE)) {
A
Artem B. Bityutskiy 已提交
768 769
			/* The physical eraseblock is supposedly empty */
			if (verbose)
770
				ubi_warn(ubi, "no EC header found at PEB %d, only 0xFF bytes",
A
Artem Bityutskiy 已提交
771 772 773
					 pnum);
			dbg_bld("no EC header found at PEB %d, only 0xFF bytes",
				pnum);
774 775 776 777
			if (!read_err)
				return UBI_IO_FF;
			else
				return UBI_IO_FF_BITFLIPS;
A
Artem B. Bityutskiy 已提交
778 779 780 781 782 783 784
		}

		/*
		 * This is not a valid erase counter header, and these are not
		 * 0xFF bytes. Report that the header is corrupted.
		 */
		if (verbose) {
785
			ubi_warn(ubi, "bad magic number at PEB %d: %08x instead of %08x",
A
Artem Bityutskiy 已提交
786
				 pnum, magic, UBI_EC_HDR_MAGIC);
787
			ubi_dump_ec_hdr(ec_hdr);
788
		}
A
Artem Bityutskiy 已提交
789 790
		dbg_bld("bad magic number at PEB %d: %08x instead of %08x",
			pnum, magic, UBI_EC_HDR_MAGIC);
A
Artem Bityutskiy 已提交
791
		return UBI_IO_BAD_HDR;
A
Artem B. Bityutskiy 已提交
792 793 794
	}

	crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC);
795
	hdr_crc = be32_to_cpu(ec_hdr->hdr_crc);
A
Artem B. Bityutskiy 已提交
796 797 798

	if (hdr_crc != crc) {
		if (verbose) {
799
			ubi_warn(ubi, "bad EC header CRC at PEB %d, calculated %#08x, read %#08x",
A
Artem Bityutskiy 已提交
800
				 pnum, crc, hdr_crc);
801
			ubi_dump_ec_hdr(ec_hdr);
802
		}
A
Artem Bityutskiy 已提交
803 804
		dbg_bld("bad EC header CRC at PEB %d, calculated %#08x, read %#08x",
			pnum, crc, hdr_crc);
805 806 807 808 809

		if (!read_err)
			return UBI_IO_BAD_HDR;
		else
			return UBI_IO_BAD_HDR_EBADMSG;
A
Artem B. Bityutskiy 已提交
810 811 812 813 814
	}

	/* And of course validate what has just been read from the media */
	err = validate_ec_hdr(ubi, ec_hdr);
	if (err) {
815
		ubi_err(ubi, "validation failed for PEB %d", pnum);
A
Artem B. Bityutskiy 已提交
816 817 818
		return -EINVAL;
	}

819 820 821 822
	/*
	 * If there was %-EBADMSG, but the header CRC is still OK, report about
	 * a bit-flip to force scrubbing on this PEB.
	 */
A
Artem B. Bityutskiy 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
	return read_err ? UBI_IO_BITFLIPS : 0;
}

/**
 * ubi_io_write_ec_hdr - write an erase counter header.
 * @ubi: UBI device description object
 * @pnum: physical eraseblock to write to
 * @ec_hdr: the erase counter header to write
 *
 * This function writes erase counter header described by @ec_hdr to physical
 * eraseblock @pnum. It also fills most fields of @ec_hdr before writing, so
 * the caller do not have to fill them. Callers must only fill the @ec_hdr->ec
 * field.
 *
 * This function returns zero in case of success and a negative error code in
 * case of failure. If %-EIO is returned, the physical eraseblock most probably
 * went bad.
 */
841
int ubi_io_write_ec_hdr(struct ubi_device *ubi, int pnum,
A
Artem B. Bityutskiy 已提交
842 843 844 845 846 847 848 849
			struct ubi_ec_hdr *ec_hdr)
{
	int err;
	uint32_t crc;

	dbg_io("write EC header to PEB %d", pnum);
	ubi_assert(pnum >= 0 &&  pnum < ubi->peb_count);

850
	ec_hdr->magic = cpu_to_be32(UBI_EC_HDR_MAGIC);
A
Artem B. Bityutskiy 已提交
851
	ec_hdr->version = UBI_VERSION;
852 853
	ec_hdr->vid_hdr_offset = cpu_to_be32(ubi->vid_hdr_offset);
	ec_hdr->data_offset = cpu_to_be32(ubi->leb_start);
854
	ec_hdr->image_seq = cpu_to_be32(ubi->image_seq);
A
Artem B. Bityutskiy 已提交
855
	crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC);
856
	ec_hdr->hdr_crc = cpu_to_be32(crc);
A
Artem B. Bityutskiy 已提交
857

858
	err = self_check_ec_hdr(ubi, pnum, ec_hdr);
A
Artem B. Bityutskiy 已提交
859
	if (err)
860
		return err;
A
Artem B. Bityutskiy 已提交
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

	err = ubi_io_write(ubi, ec_hdr, pnum, 0, ubi->ec_hdr_alsize);
	return err;
}

/**
 * validate_vid_hdr - validate a volume identifier header.
 * @ubi: UBI device description object
 * @vid_hdr: the volume identifier header to check
 *
 * This function checks that data stored in the volume identifier header
 * @vid_hdr. Returns zero if the VID header is OK and %1 if not.
 */
static int validate_vid_hdr(const struct ubi_device *ubi,
			    const struct ubi_vid_hdr *vid_hdr)
{
	int vol_type = vid_hdr->vol_type;
	int copy_flag = vid_hdr->copy_flag;
879 880
	int vol_id = be32_to_cpu(vid_hdr->vol_id);
	int lnum = be32_to_cpu(vid_hdr->lnum);
A
Artem B. Bityutskiy 已提交
881
	int compat = vid_hdr->compat;
882 883 884 885
	int data_size = be32_to_cpu(vid_hdr->data_size);
	int used_ebs = be32_to_cpu(vid_hdr->used_ebs);
	int data_pad = be32_to_cpu(vid_hdr->data_pad);
	int data_crc = be32_to_cpu(vid_hdr->data_crc);
A
Artem B. Bityutskiy 已提交
886 887 888
	int usable_leb_size = ubi->leb_size - data_pad;

	if (copy_flag != 0 && copy_flag != 1) {
889
		ubi_err(ubi, "bad copy_flag");
A
Artem B. Bityutskiy 已提交
890 891 892 893 894
		goto bad;
	}

	if (vol_id < 0 || lnum < 0 || data_size < 0 || used_ebs < 0 ||
	    data_pad < 0) {
895
		ubi_err(ubi, "negative values");
A
Artem B. Bityutskiy 已提交
896 897 898 899
		goto bad;
	}

	if (vol_id >= UBI_MAX_VOLUMES && vol_id < UBI_INTERNAL_VOL_START) {
900
		ubi_err(ubi, "bad vol_id");
A
Artem B. Bityutskiy 已提交
901 902 903 904
		goto bad;
	}

	if (vol_id < UBI_INTERNAL_VOL_START && compat != 0) {
905
		ubi_err(ubi, "bad compat");
A
Artem B. Bityutskiy 已提交
906 907 908 909 910 911
		goto bad;
	}

	if (vol_id >= UBI_INTERNAL_VOL_START && compat != UBI_COMPAT_DELETE &&
	    compat != UBI_COMPAT_RO && compat != UBI_COMPAT_PRESERVE &&
	    compat != UBI_COMPAT_REJECT) {
912
		ubi_err(ubi, "bad compat");
A
Artem B. Bityutskiy 已提交
913 914 915 916
		goto bad;
	}

	if (vol_type != UBI_VID_DYNAMIC && vol_type != UBI_VID_STATIC) {
917
		ubi_err(ubi, "bad vol_type");
A
Artem B. Bityutskiy 已提交
918 919 920 921
		goto bad;
	}

	if (data_pad >= ubi->leb_size / 2) {
922
		ubi_err(ubi, "bad data_pad");
A
Artem B. Bityutskiy 已提交
923 924 925 926 927 928 929 930 931 932 933
		goto bad;
	}

	if (vol_type == UBI_VID_STATIC) {
		/*
		 * Although from high-level point of view static volumes may
		 * contain zero bytes of data, but no VID headers can contain
		 * zero at these fields, because they empty volumes do not have
		 * mapped logical eraseblocks.
		 */
		if (used_ebs == 0) {
934
			ubi_err(ubi, "zero used_ebs");
A
Artem B. Bityutskiy 已提交
935 936 937
			goto bad;
		}
		if (data_size == 0) {
938
			ubi_err(ubi, "zero data_size");
A
Artem B. Bityutskiy 已提交
939 940 941 942
			goto bad;
		}
		if (lnum < used_ebs - 1) {
			if (data_size != usable_leb_size) {
943
				ubi_err(ubi, "bad data_size");
A
Artem B. Bityutskiy 已提交
944 945 946 947
				goto bad;
			}
		} else if (lnum == used_ebs - 1) {
			if (data_size == 0) {
948
				ubi_err(ubi, "bad data_size at last LEB");
A
Artem B. Bityutskiy 已提交
949 950 951
				goto bad;
			}
		} else {
952
			ubi_err(ubi, "too high lnum");
A
Artem B. Bityutskiy 已提交
953 954 955 956 957
			goto bad;
		}
	} else {
		if (copy_flag == 0) {
			if (data_crc != 0) {
958
				ubi_err(ubi, "non-zero data CRC");
A
Artem B. Bityutskiy 已提交
959 960 961
				goto bad;
			}
			if (data_size != 0) {
962
				ubi_err(ubi, "non-zero data_size");
A
Artem B. Bityutskiy 已提交
963 964 965 966
				goto bad;
			}
		} else {
			if (data_size == 0) {
967
				ubi_err(ubi, "zero data_size of copy");
A
Artem B. Bityutskiy 已提交
968 969 970 971
				goto bad;
			}
		}
		if (used_ebs != 0) {
972
			ubi_err(ubi, "bad used_ebs");
A
Artem B. Bityutskiy 已提交
973 974 975 976 977 978 979
			goto bad;
		}
	}

	return 0;

bad:
980
	ubi_err(ubi, "bad VID header");
981
	ubi_dump_vid_hdr(vid_hdr);
982
	dump_stack();
A
Artem B. Bityutskiy 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995
	return 1;
}

/**
 * ubi_io_read_vid_hdr - read and check a volume identifier header.
 * @ubi: UBI device description object
 * @pnum: physical eraseblock number to read from
 * @vid_hdr: &struct ubi_vid_hdr object where to store the read volume
 * identifier header
 * @verbose: be verbose if the header is corrupted or wasn't found
 *
 * This function reads the volume identifier header from physical eraseblock
 * @pnum and stores it in @vid_hdr. It also checks CRC checksum of the read
996 997
 * volume identifier header. The error codes are the same as in
 * 'ubi_io_read_ec_hdr()'.
A
Artem B. Bityutskiy 已提交
998
 *
999 1000
 * Note, the implementation of this function is also very similar to
 * 'ubi_io_read_ec_hdr()', so refer commentaries in 'ubi_io_read_ec_hdr()'.
A
Artem B. Bityutskiy 已提交
1001
 */
1002
int ubi_io_read_vid_hdr(struct ubi_device *ubi, int pnum,
A
Artem B. Bityutskiy 已提交
1003 1004
			struct ubi_vid_hdr *vid_hdr, int verbose)
{
1005
	int err, read_err;
A
Artem B. Bityutskiy 已提交
1006 1007 1008 1009 1010 1011 1012
	uint32_t crc, magic, hdr_crc;
	void *p;

	dbg_io("read VID header from PEB %d", pnum);
	ubi_assert(pnum >= 0 &&  pnum < ubi->peb_count);

	p = (char *)vid_hdr - ubi->vid_hdr_shift;
1013
	read_err = ubi_io_read(ubi, p, pnum, ubi->vid_hdr_aloffset,
A
Artem B. Bityutskiy 已提交
1014
			  ubi->vid_hdr_alsize);
1015
	if (read_err && read_err != UBI_IO_BITFLIPS && !mtd_is_eccerr(read_err))
1016
		return read_err;
A
Artem B. Bityutskiy 已提交
1017

1018
	magic = be32_to_cpu(vid_hdr->magic);
A
Artem B. Bityutskiy 已提交
1019
	if (magic != UBI_VID_HDR_MAGIC) {
1020
		if (mtd_is_eccerr(read_err))
1021
			return UBI_IO_BAD_HDR_EBADMSG;
1022

1023
		if (ubi_check_pattern(vid_hdr, 0xFF, UBI_VID_HDR_SIZE)) {
A
Artem B. Bityutskiy 已提交
1024
			if (verbose)
1025
				ubi_warn(ubi, "no VID header found at PEB %d, only 0xFF bytes",
A
Artem Bityutskiy 已提交
1026 1027 1028
					 pnum);
			dbg_bld("no VID header found at PEB %d, only 0xFF bytes",
				pnum);
1029 1030 1031 1032
			if (!read_err)
				return UBI_IO_FF;
			else
				return UBI_IO_FF_BITFLIPS;
A
Artem B. Bityutskiy 已提交
1033 1034 1035
		}

		if (verbose) {
1036
			ubi_warn(ubi, "bad magic number at PEB %d: %08x instead of %08x",
A
Artem Bityutskiy 已提交
1037
				 pnum, magic, UBI_VID_HDR_MAGIC);
1038
			ubi_dump_vid_hdr(vid_hdr);
1039
		}
A
Artem Bityutskiy 已提交
1040 1041
		dbg_bld("bad magic number at PEB %d: %08x instead of %08x",
			pnum, magic, UBI_VID_HDR_MAGIC);
A
Artem Bityutskiy 已提交
1042
		return UBI_IO_BAD_HDR;
A
Artem B. Bityutskiy 已提交
1043 1044 1045
	}

	crc = crc32(UBI_CRC32_INIT, vid_hdr, UBI_VID_HDR_SIZE_CRC);
1046
	hdr_crc = be32_to_cpu(vid_hdr->hdr_crc);
A
Artem B. Bityutskiy 已提交
1047 1048 1049

	if (hdr_crc != crc) {
		if (verbose) {
1050
			ubi_warn(ubi, "bad CRC at PEB %d, calculated %#08x, read %#08x",
A
Artem Bityutskiy 已提交
1051
				 pnum, crc, hdr_crc);
1052
			ubi_dump_vid_hdr(vid_hdr);
1053
		}
A
Artem Bityutskiy 已提交
1054 1055
		dbg_bld("bad CRC at PEB %d, calculated %#08x, read %#08x",
			pnum, crc, hdr_crc);
1056 1057 1058 1059
		if (!read_err)
			return UBI_IO_BAD_HDR;
		else
			return UBI_IO_BAD_HDR_EBADMSG;
A
Artem B. Bityutskiy 已提交
1060 1061 1062 1063
	}

	err = validate_vid_hdr(ubi, vid_hdr);
	if (err) {
1064
		ubi_err(ubi, "validation failed for PEB %d", pnum);
A
Artem B. Bityutskiy 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
		return -EINVAL;
	}

	return read_err ? UBI_IO_BITFLIPS : 0;
}

/**
 * ubi_io_write_vid_hdr - write a volume identifier header.
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to write to
 * @vid_hdr: the volume identifier header to write
 *
 * This function writes the volume identifier header described by @vid_hdr to
 * physical eraseblock @pnum. This function automatically fills the
 * @vid_hdr->magic and the @vid_hdr->version fields, as well as calculates
 * header CRC checksum and stores it at vid_hdr->hdr_crc.
 *
 * This function returns zero in case of success and a negative error code in
 * case of failure. If %-EIO is returned, the physical eraseblock probably went
 * bad.
 */
1086
int ubi_io_write_vid_hdr(struct ubi_device *ubi, int pnum,
A
Artem B. Bityutskiy 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095
			 struct ubi_vid_hdr *vid_hdr)
{
	int err;
	uint32_t crc;
	void *p;

	dbg_io("write VID header to PEB %d", pnum);
	ubi_assert(pnum >= 0 &&  pnum < ubi->peb_count);

1096
	err = self_check_peb_ec_hdr(ubi, pnum);
A
Artem B. Bityutskiy 已提交
1097
	if (err)
1098
		return err;
A
Artem B. Bityutskiy 已提交
1099

1100
	vid_hdr->magic = cpu_to_be32(UBI_VID_HDR_MAGIC);
A
Artem B. Bityutskiy 已提交
1101 1102
	vid_hdr->version = UBI_VERSION;
	crc = crc32(UBI_CRC32_INIT, vid_hdr, UBI_VID_HDR_SIZE_CRC);
1103
	vid_hdr->hdr_crc = cpu_to_be32(crc);
A
Artem B. Bityutskiy 已提交
1104

1105
	err = self_check_vid_hdr(ubi, pnum, vid_hdr);
A
Artem B. Bityutskiy 已提交
1106
	if (err)
1107
		return err;
A
Artem B. Bityutskiy 已提交
1108 1109 1110 1111 1112 1113 1114 1115

	p = (char *)vid_hdr - ubi->vid_hdr_shift;
	err = ubi_io_write(ubi, p, pnum, ubi->vid_hdr_aloffset,
			   ubi->vid_hdr_alsize);
	return err;
}

/**
1116
 * self_check_not_bad - ensure that a physical eraseblock is not bad.
A
Artem B. Bityutskiy 已提交
1117 1118 1119
 * @ubi: UBI device description object
 * @pnum: physical eraseblock number to check
 *
1120 1121
 * This function returns zero if the physical eraseblock is good, %-EINVAL if
 * it is bad and a negative error code if an error occurred.
A
Artem B. Bityutskiy 已提交
1122
 */
1123
static int self_check_not_bad(const struct ubi_device *ubi, int pnum)
A
Artem B. Bityutskiy 已提交
1124 1125 1126
{
	int err;

1127
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1128 1129
		return 0;

A
Artem B. Bityutskiy 已提交
1130 1131 1132 1133
	err = ubi_io_is_bad(ubi, pnum);
	if (!err)
		return err;

1134
	ubi_err(ubi, "self-check failed for PEB %d", pnum);
1135
	dump_stack();
1136
	return err > 0 ? -EINVAL : err;
A
Artem B. Bityutskiy 已提交
1137 1138 1139
}

/**
1140
 * self_check_ec_hdr - check if an erase counter header is all right.
A
Artem B. Bityutskiy 已提交
1141 1142 1143 1144 1145
 * @ubi: UBI device description object
 * @pnum: physical eraseblock number the erase counter header belongs to
 * @ec_hdr: the erase counter header to check
 *
 * This function returns zero if the erase counter header contains valid
1146
 * values, and %-EINVAL if not.
A
Artem B. Bityutskiy 已提交
1147
 */
1148 1149
static int self_check_ec_hdr(const struct ubi_device *ubi, int pnum,
			     const struct ubi_ec_hdr *ec_hdr)
A
Artem B. Bityutskiy 已提交
1150 1151 1152 1153
{
	int err;
	uint32_t magic;

1154
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1155 1156
		return 0;

1157
	magic = be32_to_cpu(ec_hdr->magic);
A
Artem B. Bityutskiy 已提交
1158
	if (magic != UBI_EC_HDR_MAGIC) {
1159
		ubi_err(ubi, "bad magic %#08x, must be %#08x",
A
Artem B. Bityutskiy 已提交
1160 1161 1162 1163 1164 1165
			magic, UBI_EC_HDR_MAGIC);
		goto fail;
	}

	err = validate_ec_hdr(ubi, ec_hdr);
	if (err) {
1166
		ubi_err(ubi, "self-check failed for PEB %d", pnum);
A
Artem B. Bityutskiy 已提交
1167 1168 1169 1170 1171 1172
		goto fail;
	}

	return 0;

fail:
1173
	ubi_dump_ec_hdr(ec_hdr);
1174
	dump_stack();
1175
	return -EINVAL;
A
Artem B. Bityutskiy 已提交
1176 1177 1178
}

/**
1179
 * self_check_peb_ec_hdr - check erase counter header.
A
Artem B. Bityutskiy 已提交
1180 1181 1182
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to check
 *
1183 1184
 * This function returns zero if the erase counter header is all right and and
 * a negative error code if not or if an error occurred.
A
Artem B. Bityutskiy 已提交
1185
 */
1186
static int self_check_peb_ec_hdr(const struct ubi_device *ubi, int pnum)
A
Artem B. Bityutskiy 已提交
1187 1188 1189 1190 1191
{
	int err;
	uint32_t crc, hdr_crc;
	struct ubi_ec_hdr *ec_hdr;

1192
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1193 1194
		return 0;

1195
	ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
A
Artem B. Bityutskiy 已提交
1196 1197 1198 1199
	if (!ec_hdr)
		return -ENOMEM;

	err = ubi_io_read(ubi, ec_hdr, pnum, 0, UBI_EC_HDR_SIZE);
1200
	if (err && err != UBI_IO_BITFLIPS && !mtd_is_eccerr(err))
A
Artem B. Bityutskiy 已提交
1201 1202 1203
		goto exit;

	crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC);
1204
	hdr_crc = be32_to_cpu(ec_hdr->hdr_crc);
A
Artem B. Bityutskiy 已提交
1205
	if (hdr_crc != crc) {
1206 1207 1208
		ubi_err(ubi, "bad CRC, calculated %#08x, read %#08x",
			crc, hdr_crc);
		ubi_err(ubi, "self-check failed for PEB %d", pnum);
1209
		ubi_dump_ec_hdr(ec_hdr);
1210
		dump_stack();
1211
		err = -EINVAL;
A
Artem B. Bityutskiy 已提交
1212 1213 1214
		goto exit;
	}

1215
	err = self_check_ec_hdr(ubi, pnum, ec_hdr);
A
Artem B. Bityutskiy 已提交
1216 1217 1218 1219 1220 1221 1222

exit:
	kfree(ec_hdr);
	return err;
}

/**
1223
 * self_check_vid_hdr - check that a volume identifier header is all right.
A
Artem B. Bityutskiy 已提交
1224 1225 1226 1227 1228
 * @ubi: UBI device description object
 * @pnum: physical eraseblock number the volume identifier header belongs to
 * @vid_hdr: the volume identifier header to check
 *
 * This function returns zero if the volume identifier header is all right, and
1229
 * %-EINVAL if not.
A
Artem B. Bityutskiy 已提交
1230
 */
1231 1232
static int self_check_vid_hdr(const struct ubi_device *ubi, int pnum,
			      const struct ubi_vid_hdr *vid_hdr)
A
Artem B. Bityutskiy 已提交
1233 1234 1235 1236
{
	int err;
	uint32_t magic;

1237
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1238 1239
		return 0;

1240
	magic = be32_to_cpu(vid_hdr->magic);
A
Artem B. Bityutskiy 已提交
1241
	if (magic != UBI_VID_HDR_MAGIC) {
1242
		ubi_err(ubi, "bad VID header magic %#08x at PEB %d, must be %#08x",
A
Artem B. Bityutskiy 已提交
1243 1244 1245 1246 1247 1248
			magic, pnum, UBI_VID_HDR_MAGIC);
		goto fail;
	}

	err = validate_vid_hdr(ubi, vid_hdr);
	if (err) {
1249
		ubi_err(ubi, "self-check failed for PEB %d", pnum);
A
Artem B. Bityutskiy 已提交
1250 1251 1252 1253 1254 1255
		goto fail;
	}

	return err;

fail:
1256
	ubi_err(ubi, "self-check failed for PEB %d", pnum);
1257
	ubi_dump_vid_hdr(vid_hdr);
1258
	dump_stack();
1259
	return -EINVAL;
A
Artem B. Bityutskiy 已提交
1260 1261 1262 1263

}

/**
1264
 * self_check_peb_vid_hdr - check volume identifier header.
A
Artem B. Bityutskiy 已提交
1265 1266 1267 1268
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to check
 *
 * This function returns zero if the volume identifier header is all right,
1269
 * and a negative error code if not or if an error occurred.
A
Artem B. Bityutskiy 已提交
1270
 */
1271
static int self_check_peb_vid_hdr(const struct ubi_device *ubi, int pnum)
A
Artem B. Bityutskiy 已提交
1272 1273 1274 1275 1276 1277
{
	int err;
	uint32_t crc, hdr_crc;
	struct ubi_vid_hdr *vid_hdr;
	void *p;

1278
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1279 1280
		return 0;

1281
	vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
A
Artem B. Bityutskiy 已提交
1282 1283 1284 1285 1286 1287
	if (!vid_hdr)
		return -ENOMEM;

	p = (char *)vid_hdr - ubi->vid_hdr_shift;
	err = ubi_io_read(ubi, p, pnum, ubi->vid_hdr_aloffset,
			  ubi->vid_hdr_alsize);
1288
	if (err && err != UBI_IO_BITFLIPS && !mtd_is_eccerr(err))
A
Artem B. Bityutskiy 已提交
1289 1290 1291
		goto exit;

	crc = crc32(UBI_CRC32_INIT, vid_hdr, UBI_EC_HDR_SIZE_CRC);
1292
	hdr_crc = be32_to_cpu(vid_hdr->hdr_crc);
A
Artem B. Bityutskiy 已提交
1293
	if (hdr_crc != crc) {
1294
		ubi_err(ubi, "bad VID header CRC at PEB %d, calculated %#08x, read %#08x",
A
Artem Bityutskiy 已提交
1295
			pnum, crc, hdr_crc);
1296
		ubi_err(ubi, "self-check failed for PEB %d", pnum);
1297
		ubi_dump_vid_hdr(vid_hdr);
1298
		dump_stack();
1299
		err = -EINVAL;
A
Artem B. Bityutskiy 已提交
1300 1301 1302
		goto exit;
	}

1303
	err = self_check_vid_hdr(ubi, pnum, vid_hdr);
A
Artem B. Bityutskiy 已提交
1304 1305 1306 1307 1308 1309

exit:
	ubi_free_vid_hdr(ubi, vid_hdr);
	return err;
}

A
Artem Bityutskiy 已提交
1310
/**
1311
 * self_check_write - make sure write succeeded.
A
Artem Bityutskiy 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
 * @ubi: UBI device description object
 * @buf: buffer with data which were written
 * @pnum: physical eraseblock number the data were written to
 * @offset: offset within the physical eraseblock the data were written to
 * @len: how many bytes were written
 *
 * This functions reads data which were recently written and compares it with
 * the original data buffer - the data have to match. Returns zero if the data
 * match and a negative error code if not or in case of failure.
 */
1322 1323
static int self_check_write(struct ubi_device *ubi, const void *buf, int pnum,
			    int offset, int len)
A
Artem Bityutskiy 已提交
1324 1325
{
	int err, i;
1326
	size_t read;
1327
	void *buf1;
1328
	loff_t addr = (loff_t)pnum * ubi->peb_size + offset;
A
Artem Bityutskiy 已提交
1329

1330
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1331 1332
		return 0;

A
Artem Bityutskiy 已提交
1333
	buf1 = __vmalloc(len, GFP_NOFS, PAGE_KERNEL);
1334
	if (!buf1) {
1335
		ubi_err(ubi, "cannot allocate memory to check writes");
1336 1337 1338
		return 0;
	}

1339
	err = mtd_read(ubi->mtd, addr, len, &read, buf1);
1340
	if (err && !mtd_is_bitflip(err))
1341
		goto out_free;
A
Artem Bityutskiy 已提交
1342 1343 1344

	for (i = 0; i < len; i++) {
		uint8_t c = ((uint8_t *)buf)[i];
1345
		uint8_t c1 = ((uint8_t *)buf1)[i];
A
Artem Bityutskiy 已提交
1346 1347 1348 1349 1350
		int dump_len;

		if (c == c1)
			continue;

1351
		ubi_err(ubi, "self-check failed for PEB %d:%d, len %d",
A
Artem Bityutskiy 已提交
1352
			pnum, offset, len);
1353
		ubi_msg(ubi, "data differ at position %d", i);
A
Artem Bityutskiy 已提交
1354
		dump_len = max_t(int, 128, len - i);
1355
		ubi_msg(ubi, "hex dump of the original buffer from %d to %d",
A
Artem Bityutskiy 已提交
1356 1357 1358
			i, i + dump_len);
		print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
			       buf + i, dump_len, 1);
1359
		ubi_msg(ubi, "hex dump of the read buffer from %d to %d",
A
Artem Bityutskiy 已提交
1360 1361
			i, i + dump_len);
		print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
1362
			       buf1 + i, dump_len, 1);
1363
		dump_stack();
A
Artem Bityutskiy 已提交
1364
		err = -EINVAL;
1365
		goto out_free;
A
Artem Bityutskiy 已提交
1366 1367
	}

1368
	vfree(buf1);
A
Artem Bityutskiy 已提交
1369 1370
	return 0;

1371 1372
out_free:
	vfree(buf1);
A
Artem Bityutskiy 已提交
1373 1374 1375
	return err;
}

A
Artem B. Bityutskiy 已提交
1376
/**
1377
 * ubi_self_check_all_ff - check that a region of flash is empty.
A
Artem B. Bityutskiy 已提交
1378 1379 1380 1381 1382 1383
 * @ubi: UBI device description object
 * @pnum: the physical eraseblock number to check
 * @offset: the starting offset within the physical eraseblock to check
 * @len: the length of the region to check
 *
 * This function returns zero if only 0xFF bytes are present at offset
1384 1385
 * @offset of the physical eraseblock @pnum, and a negative error code if not
 * or if an error occurred.
A
Artem B. Bityutskiy 已提交
1386
 */
1387
int ubi_self_check_all_ff(struct ubi_device *ubi, int pnum, int offset, int len)
A
Artem B. Bityutskiy 已提交
1388 1389 1390
{
	size_t read;
	int err;
1391
	void *buf;
A
Artem B. Bityutskiy 已提交
1392 1393
	loff_t addr = (loff_t)pnum * ubi->peb_size + offset;

1394
	if (!ubi_dbg_chk_io(ubi))
A
Artem Bityutskiy 已提交
1395 1396
		return 0;

A
Artem Bityutskiy 已提交
1397
	buf = __vmalloc(len, GFP_NOFS, PAGE_KERNEL);
1398
	if (!buf) {
1399
		ubi_err(ubi, "cannot allocate memory to check for 0xFFs");
1400 1401 1402
		return 0;
	}

1403
	err = mtd_read(ubi->mtd, addr, len, &read, buf);
1404
	if (err && !mtd_is_bitflip(err)) {
1405
		ubi_err(ubi, "err %d while reading %d bytes from PEB %d:%d, read %zd bytes",
A
Artem Bityutskiy 已提交
1406
			err, len, pnum, offset, read);
A
Artem B. Bityutskiy 已提交
1407 1408 1409
		goto error;
	}

1410
	err = ubi_check_pattern(buf, 0xFF, len);
A
Artem B. Bityutskiy 已提交
1411
	if (err == 0) {
1412
		ubi_err(ubi, "flash region at PEB %d:%d, length %d does not contain all 0xFF bytes",
A
Artem Bityutskiy 已提交
1413
			pnum, offset, len);
A
Artem B. Bityutskiy 已提交
1414 1415 1416
		goto fail;
	}

1417
	vfree(buf);
A
Artem B. Bityutskiy 已提交
1418 1419 1420
	return 0;

fail:
1421 1422 1423
	ubi_err(ubi, "self-check failed for PEB %d", pnum);
	ubi_msg(ubi, "hex dump of the %d-%d region",
		 offset, offset + len);
1424
	print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1, buf, len, 1);
1425
	err = -EINVAL;
A
Artem B. Bityutskiy 已提交
1426
error:
1427
	dump_stack();
1428
	vfree(buf);
A
Artem B. Bityutskiy 已提交
1429 1430
	return err;
}