Merge remote-tracking branches 'asoc/topic/wm9712', 'asoc/topic/wm9713' and 'asoc...
[linux-2.6-block.git] / drivers / mtd / nand / nand_base.c
CommitLineData
1da177e4 1/*
1da177e4
LT
2 * Overview:
3 * This is the generic MTD driver for NAND flash devices. It should be
4 * capable of working with almost all NAND chips currently available.
61b03bd7 5 *
1da177e4 6 * Additional technical information is available on
8b2b403c 7 * http://www.linux-mtd.infradead.org/doc/nand.html
61b03bd7 8 *
1da177e4 9 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
ace4dfee 10 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
1da177e4 11 *
ace4dfee 12 * Credits:
61b03bd7
TG
13 * David Woodhouse for adding multichip support
14 *
1da177e4
LT
15 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
16 * rework for 2K page size chips
17 *
ace4dfee 18 * TODO:
1da177e4
LT
19 * Enable cached programming for 2k page size chips
20 * Check, if mtd->ecctype should be set to MTD_ECC_HW
7854d3f7 21 * if we have HW ECC support.
c0b8ba7b 22 * BBT table is not serialized, has to be fixed
1da177e4 23 *
1da177e4
LT
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License version 2 as
26 * published by the Free Software Foundation.
27 *
28 */
29
20171642
EG
30#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31
552d9205 32#include <linux/module.h>
1da177e4
LT
33#include <linux/delay.h>
34#include <linux/errno.h>
7aa65bfd 35#include <linux/err.h>
1da177e4
LT
36#include <linux/sched.h>
37#include <linux/slab.h>
66507c7b 38#include <linux/mm.h>
1da177e4
LT
39#include <linux/types.h>
40#include <linux/mtd/mtd.h>
41#include <linux/mtd/nand.h>
42#include <linux/mtd/nand_ecc.h>
193bd400 43#include <linux/mtd/nand_bch.h>
1da177e4
LT
44#include <linux/interrupt.h>
45#include <linux/bitops.h>
7351d3a5 46#include <linux/io.h>
1da177e4 47#include <linux/mtd/partitions.h>
d48f62b9 48#include <linux/of.h>
1da177e4 49
41b207a7
BB
50static int nand_get_device(struct mtd_info *mtd, int new_state);
51
52static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
53 struct mtd_oob_ops *ops);
1da177e4
LT
54
55/* Define default oob placement schemes for large and small page devices */
41b207a7
BB
56static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
57 struct mtd_oob_region *oobregion)
58{
59 struct nand_chip *chip = mtd_to_nand(mtd);
60 struct nand_ecc_ctrl *ecc = &chip->ecc;
1da177e4 61
41b207a7
BB
62 if (section > 1)
63 return -ERANGE;
1da177e4 64
41b207a7
BB
65 if (!section) {
66 oobregion->offset = 0;
67 oobregion->length = 4;
68 } else {
69 oobregion->offset = 6;
70 oobregion->length = ecc->total - 4;
71 }
1da177e4 72
41b207a7
BB
73 return 0;
74}
75
76static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
77 struct mtd_oob_region *oobregion)
78{
79 if (section > 1)
80 return -ERANGE;
1da177e4 81
41b207a7
BB
82 if (mtd->oobsize == 16) {
83 if (section)
84 return -ERANGE;
85
86 oobregion->length = 8;
87 oobregion->offset = 8;
88 } else {
89 oobregion->length = 2;
90 if (!section)
91 oobregion->offset = 3;
92 else
93 oobregion->offset = 6;
94 }
95
96 return 0;
97}
98
99const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
100 .ecc = nand_ooblayout_ecc_sp,
101 .free = nand_ooblayout_free_sp,
81ec5364 102};
41b207a7 103EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
81ec5364 104
41b207a7
BB
105static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
106 struct mtd_oob_region *oobregion)
107{
108 struct nand_chip *chip = mtd_to_nand(mtd);
109 struct nand_ecc_ctrl *ecc = &chip->ecc;
1da177e4 110
41b207a7
BB
111 if (section)
112 return -ERANGE;
8593fbc6 113
41b207a7
BB
114 oobregion->length = ecc->total;
115 oobregion->offset = mtd->oobsize - oobregion->length;
116
117 return 0;
118}
119
120static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
121 struct mtd_oob_region *oobregion)
122{
123 struct nand_chip *chip = mtd_to_nand(mtd);
124 struct nand_ecc_ctrl *ecc = &chip->ecc;
125
126 if (section)
127 return -ERANGE;
128
129 oobregion->length = mtd->oobsize - ecc->total - 2;
130 oobregion->offset = 2;
131
132 return 0;
133}
134
135const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
136 .ecc = nand_ooblayout_ecc_lp,
137 .free = nand_ooblayout_free_lp,
138};
139EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
d470a97c 140
6fe5a6ac
VS
141static int check_offs_len(struct mtd_info *mtd,
142 loff_t ofs, uint64_t len)
143{
862eba51 144 struct nand_chip *chip = mtd_to_nand(mtd);
6fe5a6ac
VS
145 int ret = 0;
146
147 /* Start address must align on block boundary */
daae74ca 148 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
289c0522 149 pr_debug("%s: unaligned address\n", __func__);
6fe5a6ac
VS
150 ret = -EINVAL;
151 }
152
153 /* Length must align on block boundary */
daae74ca 154 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
289c0522 155 pr_debug("%s: length not block aligned\n", __func__);
6fe5a6ac
VS
156 ret = -EINVAL;
157 }
158
6fe5a6ac
VS
159 return ret;
160}
161
1da177e4
LT
162/**
163 * nand_release_device - [GENERIC] release chip
8b6e50c9 164 * @mtd: MTD device structure
61b03bd7 165 *
b0bb6903 166 * Release chip lock and wake up anyone waiting on the device.
1da177e4 167 */
e0c7d767 168static void nand_release_device(struct mtd_info *mtd)
1da177e4 169{
862eba51 170 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 171
a36ed299 172 /* Release the controller and the chip */
ace4dfee
TG
173 spin_lock(&chip->controller->lock);
174 chip->controller->active = NULL;
175 chip->state = FL_READY;
176 wake_up(&chip->controller->wq);
177 spin_unlock(&chip->controller->lock);
1da177e4
LT
178}
179
180/**
181 * nand_read_byte - [DEFAULT] read one byte from the chip
8b6e50c9 182 * @mtd: MTD device structure
1da177e4 183 *
7854d3f7 184 * Default read function for 8bit buswidth
1da177e4 185 */
58dd8f2b 186static uint8_t nand_read_byte(struct mtd_info *mtd)
1da177e4 187{
862eba51 188 struct nand_chip *chip = mtd_to_nand(mtd);
ace4dfee 189 return readb(chip->IO_ADDR_R);
1da177e4
LT
190}
191
1da177e4 192/**
7854d3f7 193 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
8b6e50c9 194 * @mtd: MTD device structure
1da177e4 195 *
7854d3f7
BN
196 * Default read function for 16bit buswidth with endianness conversion.
197 *
1da177e4 198 */
58dd8f2b 199static uint8_t nand_read_byte16(struct mtd_info *mtd)
1da177e4 200{
862eba51 201 struct nand_chip *chip = mtd_to_nand(mtd);
ace4dfee 202 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
1da177e4
LT
203}
204
1da177e4
LT
205/**
206 * nand_read_word - [DEFAULT] read one word from the chip
8b6e50c9 207 * @mtd: MTD device structure
1da177e4 208 *
7854d3f7 209 * Default read function for 16bit buswidth without endianness conversion.
1da177e4
LT
210 */
211static u16 nand_read_word(struct mtd_info *mtd)
212{
862eba51 213 struct nand_chip *chip = mtd_to_nand(mtd);
ace4dfee 214 return readw(chip->IO_ADDR_R);
1da177e4
LT
215}
216
1da177e4
LT
217/**
218 * nand_select_chip - [DEFAULT] control CE line
8b6e50c9
BN
219 * @mtd: MTD device structure
220 * @chipnr: chipnumber to select, -1 for deselect
1da177e4
LT
221 *
222 * Default select function for 1 chip devices.
223 */
ace4dfee 224static void nand_select_chip(struct mtd_info *mtd, int chipnr)
1da177e4 225{
862eba51 226 struct nand_chip *chip = mtd_to_nand(mtd);
ace4dfee
TG
227
228 switch (chipnr) {
1da177e4 229 case -1:
ace4dfee 230 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
1da177e4
LT
231 break;
232 case 0:
1da177e4
LT
233 break;
234
235 default:
236 BUG();
237 }
238}
239
05f78359
UKK
240/**
241 * nand_write_byte - [DEFAULT] write single byte to chip
242 * @mtd: MTD device structure
243 * @byte: value to write
244 *
245 * Default function to write a byte to I/O[7:0]
246 */
247static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
248{
862eba51 249 struct nand_chip *chip = mtd_to_nand(mtd);
05f78359
UKK
250
251 chip->write_buf(mtd, &byte, 1);
252}
253
254/**
255 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
256 * @mtd: MTD device structure
257 * @byte: value to write
258 *
259 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
260 */
261static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
262{
862eba51 263 struct nand_chip *chip = mtd_to_nand(mtd);
05f78359
UKK
264 uint16_t word = byte;
265
266 /*
267 * It's not entirely clear what should happen to I/O[15:8] when writing
268 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
269 *
270 * When the host supports a 16-bit bus width, only data is
271 * transferred at the 16-bit width. All address and command line
272 * transfers shall use only the lower 8-bits of the data bus. During
273 * command transfers, the host may place any value on the upper
274 * 8-bits of the data bus. During address transfers, the host shall
275 * set the upper 8-bits of the data bus to 00h.
276 *
277 * One user of the write_byte callback is nand_onfi_set_features. The
278 * four parameters are specified to be written to I/O[7:0], but this is
279 * neither an address nor a command transfer. Let's assume a 0 on the
280 * upper I/O lines is OK.
281 */
282 chip->write_buf(mtd, (uint8_t *)&word, 2);
283}
284
1da177e4
LT
285/**
286 * nand_write_buf - [DEFAULT] write buffer to chip
8b6e50c9
BN
287 * @mtd: MTD device structure
288 * @buf: data buffer
289 * @len: number of bytes to write
1da177e4 290 *
7854d3f7 291 * Default write function for 8bit buswidth.
1da177e4 292 */
58dd8f2b 293static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
1da177e4 294{
862eba51 295 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 296
76413839 297 iowrite8_rep(chip->IO_ADDR_W, buf, len);
1da177e4
LT
298}
299
300/**
61b03bd7 301 * nand_read_buf - [DEFAULT] read chip data into buffer
8b6e50c9
BN
302 * @mtd: MTD device structure
303 * @buf: buffer to store date
304 * @len: number of bytes to read
1da177e4 305 *
7854d3f7 306 * Default read function for 8bit buswidth.
1da177e4 307 */
58dd8f2b 308static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
1da177e4 309{
862eba51 310 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 311
76413839 312 ioread8_rep(chip->IO_ADDR_R, buf, len);
1da177e4
LT
313}
314
1da177e4
LT
315/**
316 * nand_write_buf16 - [DEFAULT] write buffer to chip
8b6e50c9
BN
317 * @mtd: MTD device structure
318 * @buf: data buffer
319 * @len: number of bytes to write
1da177e4 320 *
7854d3f7 321 * Default write function for 16bit buswidth.
1da177e4 322 */
58dd8f2b 323static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
1da177e4 324{
862eba51 325 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 326 u16 *p = (u16 *) buf;
61b03bd7 327
76413839 328 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
1da177e4
LT
329}
330
331/**
61b03bd7 332 * nand_read_buf16 - [DEFAULT] read chip data into buffer
8b6e50c9
BN
333 * @mtd: MTD device structure
334 * @buf: buffer to store date
335 * @len: number of bytes to read
1da177e4 336 *
7854d3f7 337 * Default read function for 16bit buswidth.
1da177e4 338 */
58dd8f2b 339static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
1da177e4 340{
862eba51 341 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 342 u16 *p = (u16 *) buf;
1da177e4 343
76413839 344 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
1da177e4
LT
345}
346
1da177e4
LT
347/**
348 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
8b6e50c9
BN
349 * @mtd: MTD device structure
350 * @ofs: offset from device start
1da177e4 351 *
61b03bd7 352 * Check, if the block is bad.
1da177e4 353 */
9f3e0429 354static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
1da177e4 355{
9f3e0429 356 int page, res = 0, i = 0;
862eba51 357 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4
LT
358 u16 bad;
359
5fb1549d 360 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
b60b08b0
KC
361 ofs += mtd->erasesize - mtd->writesize;
362
1a12f46a
TK
363 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
364
cdbec050
BN
365 do {
366 if (chip->options & NAND_BUSWIDTH_16) {
367 chip->cmdfunc(mtd, NAND_CMD_READOOB,
368 chip->badblockpos & 0xFE, page);
369 bad = cpu_to_le16(chip->read_word(mtd));
370 if (chip->badblockpos & 0x1)
371 bad >>= 8;
372 else
373 bad &= 0xFF;
374 } else {
375 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
376 page);
377 bad = chip->read_byte(mtd);
378 }
379
380 if (likely(chip->badblockbits == 8))
381 res = bad != 0xFF;
e0b58d0a 382 else
cdbec050
BN
383 res = hweight8(bad) < chip->badblockbits;
384 ofs += mtd->writesize;
385 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
386 i++;
387 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
e0b58d0a 388
1da177e4
LT
389 return res;
390}
391
392/**
5a0edb25 393 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
8b6e50c9
BN
394 * @mtd: MTD device structure
395 * @ofs: offset from device start
1da177e4 396 *
8b6e50c9 397 * This is the default implementation, which can be overridden by a hardware
5a0edb25
BN
398 * specific driver. It provides the details for writing a bad block marker to a
399 * block.
400 */
401static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
402{
862eba51 403 struct nand_chip *chip = mtd_to_nand(mtd);
5a0edb25
BN
404 struct mtd_oob_ops ops;
405 uint8_t buf[2] = { 0, 0 };
406 int ret = 0, res, i = 0;
407
0ec56dc4 408 memset(&ops, 0, sizeof(ops));
5a0edb25
BN
409 ops.oobbuf = buf;
410 ops.ooboffs = chip->badblockpos;
411 if (chip->options & NAND_BUSWIDTH_16) {
412 ops.ooboffs &= ~0x01;
413 ops.len = ops.ooblen = 2;
414 } else {
415 ops.len = ops.ooblen = 1;
416 }
417 ops.mode = MTD_OPS_PLACE_OOB;
418
419 /* Write to first/last page(s) if necessary */
420 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
421 ofs += mtd->erasesize - mtd->writesize;
422 do {
423 res = nand_do_write_oob(mtd, ofs, &ops);
424 if (!ret)
425 ret = res;
426
427 i++;
428 ofs += mtd->writesize;
429 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
430
431 return ret;
432}
433
434/**
435 * nand_block_markbad_lowlevel - mark a block bad
436 * @mtd: MTD device structure
437 * @ofs: offset from device start
438 *
439 * This function performs the generic NAND bad block marking steps (i.e., bad
440 * block table(s) and/or marker(s)). We only allow the hardware driver to
441 * specify how to write bad block markers to OOB (chip->block_markbad).
442 *
b32843b7 443 * We try operations in the following order:
e2414f4c 444 * (1) erase the affected block, to allow OOB marker to be written cleanly
b32843b7
BN
445 * (2) write bad block marker to OOB area of affected block (unless flag
446 * NAND_BBT_NO_OOB_BBM is present)
447 * (3) update the BBT
448 * Note that we retain the first error encountered in (2) or (3), finish the
e2414f4c 449 * procedures, and dump the error in the end.
1da177e4 450*/
5a0edb25 451static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
1da177e4 452{
862eba51 453 struct nand_chip *chip = mtd_to_nand(mtd);
b32843b7 454 int res, ret = 0;
61b03bd7 455
b32843b7 456 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
00918429
BN
457 struct erase_info einfo;
458
459 /* Attempt erase before marking OOB */
460 memset(&einfo, 0, sizeof(einfo));
461 einfo.mtd = mtd;
462 einfo.addr = ofs;
daae74ca 463 einfo.len = 1ULL << chip->phys_erase_shift;
00918429 464 nand_erase_nand(mtd, &einfo, 0);
1da177e4 465
b32843b7 466 /* Write bad block marker to OOB */
6a8214aa 467 nand_get_device(mtd, FL_WRITING);
5a0edb25 468 ret = chip->block_markbad(mtd, ofs);
c0b8ba7b 469 nand_release_device(mtd);
f1a28c02 470 }
e2414f4c 471
b32843b7
BN
472 /* Mark block bad in BBT */
473 if (chip->bbt) {
474 res = nand_markbad_bbt(mtd, ofs);
e2414f4c
BN
475 if (!ret)
476 ret = res;
477 }
478
f1a28c02
TG
479 if (!ret)
480 mtd->ecc_stats.badblocks++;
c0b8ba7b 481
f1a28c02 482 return ret;
1da177e4
LT
483}
484
61b03bd7 485/**
1da177e4 486 * nand_check_wp - [GENERIC] check if the chip is write protected
8b6e50c9 487 * @mtd: MTD device structure
1da177e4 488 *
8b6e50c9
BN
489 * Check, if the device is write protected. The function expects, that the
490 * device is already selected.
1da177e4 491 */
e0c7d767 492static int nand_check_wp(struct mtd_info *mtd)
1da177e4 493{
862eba51 494 struct nand_chip *chip = mtd_to_nand(mtd);
93edbad6 495
8b6e50c9 496 /* Broken xD cards report WP despite being writable */
93edbad6
ML
497 if (chip->options & NAND_BROKEN_XD)
498 return 0;
499
1da177e4 500 /* Check the WP bit */
ace4dfee
TG
501 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
502 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
1da177e4
LT
503}
504
8471bb73 505/**
c30e1f79 506 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
8471bb73
EG
507 * @mtd: MTD device structure
508 * @ofs: offset from device start
509 *
c30e1f79 510 * Check if the block is marked as reserved.
8471bb73
EG
511 */
512static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
513{
862eba51 514 struct nand_chip *chip = mtd_to_nand(mtd);
8471bb73
EG
515
516 if (!chip->bbt)
517 return 0;
518 /* Return info from the table */
519 return nand_isreserved_bbt(mtd, ofs);
520}
521
1da177e4
LT
522/**
523 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
8b6e50c9
BN
524 * @mtd: MTD device structure
525 * @ofs: offset from device start
8b6e50c9 526 * @allowbbt: 1, if its allowed to access the bbt area
1da177e4
LT
527 *
528 * Check, if the block is bad. Either by reading the bad block table or
529 * calling of the scan function.
530 */
9f3e0429 531static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
1da177e4 532{
862eba51 533 struct nand_chip *chip = mtd_to_nand(mtd);
61b03bd7 534
ace4dfee 535 if (!chip->bbt)
9f3e0429 536 return chip->block_bad(mtd, ofs);
61b03bd7 537
1da177e4 538 /* Return info from the table */
e0c7d767 539 return nand_isbad_bbt(mtd, ofs, allowbbt);
1da177e4
LT
540}
541
2af7c653
SK
542/**
543 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
8b6e50c9
BN
544 * @mtd: MTD device structure
545 * @timeo: Timeout
2af7c653
SK
546 *
547 * Helper function for nand_wait_ready used when needing to wait in interrupt
548 * context.
549 */
550static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
551{
862eba51 552 struct nand_chip *chip = mtd_to_nand(mtd);
2af7c653
SK
553 int i;
554
555 /* Wait for the device to get ready */
556 for (i = 0; i < timeo; i++) {
557 if (chip->dev_ready(mtd))
558 break;
559 touch_softlockup_watchdog();
560 mdelay(1);
561 }
562}
563
b70af9be
AS
564/**
565 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
566 * @mtd: MTD device structure
567 *
568 * Wait for the ready pin after a command, and warn if a timeout occurs.
569 */
4b648b02 570void nand_wait_ready(struct mtd_info *mtd)
3b88775c 571{
862eba51 572 struct nand_chip *chip = mtd_to_nand(mtd);
b70af9be 573 unsigned long timeo = 400;
3b88775c 574
2af7c653 575 if (in_interrupt() || oops_in_progress)
b70af9be 576 return panic_nand_wait_ready(mtd, timeo);
2af7c653 577
7854d3f7 578 /* Wait until command is processed or timeout occurs */
b70af9be 579 timeo = jiffies + msecs_to_jiffies(timeo);
3b88775c 580 do {
ace4dfee 581 if (chip->dev_ready(mtd))
4c7e054f 582 return;
b70af9be 583 cond_resched();
61b03bd7 584 } while (time_before(jiffies, timeo));
b70af9be 585
9ebfdf5b
BN
586 if (!chip->dev_ready(mtd))
587 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
3b88775c 588}
4b648b02 589EXPORT_SYMBOL_GPL(nand_wait_ready);
3b88775c 590
60c70d66
RQ
591/**
592 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
593 * @mtd: MTD device structure
594 * @timeo: Timeout in ms
595 *
596 * Wait for status ready (i.e. command done) or timeout.
597 */
598static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
599{
862eba51 600 register struct nand_chip *chip = mtd_to_nand(mtd);
60c70d66
RQ
601
602 timeo = jiffies + msecs_to_jiffies(timeo);
603 do {
604 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
605 break;
606 touch_softlockup_watchdog();
607 } while (time_before(jiffies, timeo));
608};
609
1da177e4
LT
610/**
611 * nand_command - [DEFAULT] Send command to NAND device
8b6e50c9
BN
612 * @mtd: MTD device structure
613 * @command: the command to be sent
614 * @column: the column address for this command, -1 if none
615 * @page_addr: the page address for this command, -1 if none
1da177e4 616 *
8b6e50c9 617 * Send command to NAND device. This function is used for small page devices
51148f1f 618 * (512 Bytes per page).
1da177e4 619 */
7abd3ef9
TG
620static void nand_command(struct mtd_info *mtd, unsigned int command,
621 int column, int page_addr)
1da177e4 622{
862eba51 623 register struct nand_chip *chip = mtd_to_nand(mtd);
7abd3ef9 624 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
1da177e4 625
8b6e50c9 626 /* Write out the command to the device */
1da177e4
LT
627 if (command == NAND_CMD_SEQIN) {
628 int readcmd;
629
28318776 630 if (column >= mtd->writesize) {
1da177e4 631 /* OOB area */
28318776 632 column -= mtd->writesize;
1da177e4
LT
633 readcmd = NAND_CMD_READOOB;
634 } else if (column < 256) {
635 /* First 256 bytes --> READ0 */
636 readcmd = NAND_CMD_READ0;
637 } else {
638 column -= 256;
639 readcmd = NAND_CMD_READ1;
640 }
ace4dfee 641 chip->cmd_ctrl(mtd, readcmd, ctrl);
7abd3ef9 642 ctrl &= ~NAND_CTRL_CHANGE;
1da177e4 643 }
ace4dfee 644 chip->cmd_ctrl(mtd, command, ctrl);
1da177e4 645
8b6e50c9 646 /* Address cycle, when necessary */
7abd3ef9
TG
647 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
648 /* Serially input address */
649 if (column != -1) {
650 /* Adjust columns for 16 bit buswidth */
3dad2344
BN
651 if (chip->options & NAND_BUSWIDTH_16 &&
652 !nand_opcode_8bits(command))
7abd3ef9 653 column >>= 1;
ace4dfee 654 chip->cmd_ctrl(mtd, column, ctrl);
7abd3ef9
TG
655 ctrl &= ~NAND_CTRL_CHANGE;
656 }
657 if (page_addr != -1) {
ace4dfee 658 chip->cmd_ctrl(mtd, page_addr, ctrl);
7abd3ef9 659 ctrl &= ~NAND_CTRL_CHANGE;
ace4dfee 660 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
7abd3ef9 661 /* One more address cycle for devices > 32MiB */
ace4dfee
TG
662 if (chip->chipsize > (32 << 20))
663 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
1da177e4 664 }
ace4dfee 665 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
61b03bd7
TG
666
667 /*
8b6e50c9
BN
668 * Program and erase have their own busy handlers status and sequential
669 * in needs no delay
e0c7d767 670 */
1da177e4 671 switch (command) {
61b03bd7 672
1da177e4
LT
673 case NAND_CMD_PAGEPROG:
674 case NAND_CMD_ERASE1:
675 case NAND_CMD_ERASE2:
676 case NAND_CMD_SEQIN:
677 case NAND_CMD_STATUS:
678 return;
679
680 case NAND_CMD_RESET:
ace4dfee 681 if (chip->dev_ready)
1da177e4 682 break;
ace4dfee
TG
683 udelay(chip->chip_delay);
684 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
7abd3ef9 685 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
12efdde3
TG
686 chip->cmd_ctrl(mtd,
687 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
60c70d66
RQ
688 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
689 nand_wait_status_ready(mtd, 250);
1da177e4
LT
690 return;
691
e0c7d767 692 /* This applies to read commands */
1da177e4 693 default:
61b03bd7 694 /*
1da177e4
LT
695 * If we don't have access to the busy pin, we apply the given
696 * command delay
e0c7d767 697 */
ace4dfee
TG
698 if (!chip->dev_ready) {
699 udelay(chip->chip_delay);
1da177e4 700 return;
61b03bd7 701 }
1da177e4 702 }
8b6e50c9
BN
703 /*
704 * Apply this short delay always to ensure that we do wait tWB in
705 * any case on any machine.
706 */
e0c7d767 707 ndelay(100);
3b88775c
TG
708
709 nand_wait_ready(mtd);
1da177e4
LT
710}
711
712/**
713 * nand_command_lp - [DEFAULT] Send command to NAND large page device
8b6e50c9
BN
714 * @mtd: MTD device structure
715 * @command: the command to be sent
716 * @column: the column address for this command, -1 if none
717 * @page_addr: the page address for this command, -1 if none
1da177e4 718 *
7abd3ef9 719 * Send command to NAND device. This is the version for the new large page
7854d3f7
BN
720 * devices. We don't have the separate regions as we have in the small page
721 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
1da177e4 722 */
7abd3ef9
TG
723static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
724 int column, int page_addr)
1da177e4 725{
862eba51 726 register struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4
LT
727
728 /* Emulate NAND_CMD_READOOB */
729 if (command == NAND_CMD_READOOB) {
28318776 730 column += mtd->writesize;
1da177e4
LT
731 command = NAND_CMD_READ0;
732 }
61b03bd7 733
7abd3ef9 734 /* Command latch cycle */
fb066ada 735 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
1da177e4
LT
736
737 if (column != -1 || page_addr != -1) {
7abd3ef9 738 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
1da177e4
LT
739
740 /* Serially input address */
741 if (column != -1) {
742 /* Adjust columns for 16 bit buswidth */
3dad2344
BN
743 if (chip->options & NAND_BUSWIDTH_16 &&
744 !nand_opcode_8bits(command))
1da177e4 745 column >>= 1;
ace4dfee 746 chip->cmd_ctrl(mtd, column, ctrl);
7abd3ef9 747 ctrl &= ~NAND_CTRL_CHANGE;
fde85cfd 748
f5b88de2 749 /* Only output a single addr cycle for 8bits opcodes. */
fde85cfd
BB
750 if (!nand_opcode_8bits(command))
751 chip->cmd_ctrl(mtd, column >> 8, ctrl);
61b03bd7 752 }
1da177e4 753 if (page_addr != -1) {
ace4dfee
TG
754 chip->cmd_ctrl(mtd, page_addr, ctrl);
755 chip->cmd_ctrl(mtd, page_addr >> 8,
7abd3ef9 756 NAND_NCE | NAND_ALE);
1da177e4 757 /* One more address cycle for devices > 128MiB */
ace4dfee
TG
758 if (chip->chipsize > (128 << 20))
759 chip->cmd_ctrl(mtd, page_addr >> 16,
7abd3ef9 760 NAND_NCE | NAND_ALE);
1da177e4 761 }
1da177e4 762 }
ace4dfee 763 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
61b03bd7
TG
764
765 /*
8b6e50c9 766 * Program and erase have their own busy handlers status, sequential
7a442f17 767 * in and status need no delay.
30f464b7 768 */
1da177e4 769 switch (command) {
61b03bd7 770
1da177e4
LT
771 case NAND_CMD_CACHEDPROG:
772 case NAND_CMD_PAGEPROG:
773 case NAND_CMD_ERASE1:
774 case NAND_CMD_ERASE2:
775 case NAND_CMD_SEQIN:
7bc3312b 776 case NAND_CMD_RNDIN:
1da177e4 777 case NAND_CMD_STATUS:
30f464b7 778 return;
1da177e4
LT
779
780 case NAND_CMD_RESET:
ace4dfee 781 if (chip->dev_ready)
1da177e4 782 break;
ace4dfee 783 udelay(chip->chip_delay);
12efdde3
TG
784 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
785 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
786 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
787 NAND_NCE | NAND_CTRL_CHANGE);
60c70d66
RQ
788 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
789 nand_wait_status_ready(mtd, 250);
1da177e4
LT
790 return;
791
7bc3312b
TG
792 case NAND_CMD_RNDOUT:
793 /* No ready / busy check necessary */
794 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
795 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
796 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
797 NAND_NCE | NAND_CTRL_CHANGE);
798 return;
799
1da177e4 800 case NAND_CMD_READ0:
12efdde3
TG
801 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
802 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
803 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
804 NAND_NCE | NAND_CTRL_CHANGE);
61b03bd7 805
e0c7d767 806 /* This applies to read commands */
1da177e4 807 default:
61b03bd7 808 /*
1da177e4 809 * If we don't have access to the busy pin, we apply the given
8b6e50c9 810 * command delay.
e0c7d767 811 */
ace4dfee
TG
812 if (!chip->dev_ready) {
813 udelay(chip->chip_delay);
1da177e4 814 return;
61b03bd7 815 }
1da177e4 816 }
3b88775c 817
8b6e50c9
BN
818 /*
819 * Apply this short delay always to ensure that we do wait tWB in
820 * any case on any machine.
821 */
e0c7d767 822 ndelay(100);
3b88775c
TG
823
824 nand_wait_ready(mtd);
1da177e4
LT
825}
826
2af7c653
SK
827/**
828 * panic_nand_get_device - [GENERIC] Get chip for selected access
8b6e50c9
BN
829 * @chip: the nand chip descriptor
830 * @mtd: MTD device structure
831 * @new_state: the state which is requested
2af7c653
SK
832 *
833 * Used when in panic, no locks are taken.
834 */
835static void panic_nand_get_device(struct nand_chip *chip,
836 struct mtd_info *mtd, int new_state)
837{
7854d3f7 838 /* Hardware controller shared among independent devices */
2af7c653
SK
839 chip->controller->active = chip;
840 chip->state = new_state;
841}
842
1da177e4
LT
843/**
844 * nand_get_device - [GENERIC] Get chip for selected access
8b6e50c9
BN
845 * @mtd: MTD device structure
846 * @new_state: the state which is requested
1da177e4
LT
847 *
848 * Get the device and lock it for exclusive access
849 */
2c0a2bed 850static int
6a8214aa 851nand_get_device(struct mtd_info *mtd, int new_state)
1da177e4 852{
862eba51 853 struct nand_chip *chip = mtd_to_nand(mtd);
ace4dfee
TG
854 spinlock_t *lock = &chip->controller->lock;
855 wait_queue_head_t *wq = &chip->controller->wq;
e0c7d767 856 DECLARE_WAITQUEUE(wait, current);
7351d3a5 857retry:
0dfc6246
TG
858 spin_lock(lock);
859
b8b3ee9a 860 /* Hardware controller shared among independent devices */
ace4dfee
TG
861 if (!chip->controller->active)
862 chip->controller->active = chip;
a36ed299 863
ace4dfee
TG
864 if (chip->controller->active == chip && chip->state == FL_READY) {
865 chip->state = new_state;
0dfc6246 866 spin_unlock(lock);
962034f4
VW
867 return 0;
868 }
869 if (new_state == FL_PM_SUSPENDED) {
6b0d9a84
LY
870 if (chip->controller->active->state == FL_PM_SUSPENDED) {
871 chip->state = FL_PM_SUSPENDED;
872 spin_unlock(lock);
873 return 0;
6b0d9a84 874 }
0dfc6246
TG
875 }
876 set_current_state(TASK_UNINTERRUPTIBLE);
877 add_wait_queue(wq, &wait);
878 spin_unlock(lock);
879 schedule();
880 remove_wait_queue(wq, &wait);
1da177e4
LT
881 goto retry;
882}
883
2af7c653 884/**
8b6e50c9
BN
885 * panic_nand_wait - [GENERIC] wait until the command is done
886 * @mtd: MTD device structure
887 * @chip: NAND chip structure
888 * @timeo: timeout
2af7c653
SK
889 *
890 * Wait for command done. This is a helper function for nand_wait used when
891 * we are in interrupt context. May happen when in panic and trying to write
b595076a 892 * an oops through mtdoops.
2af7c653
SK
893 */
894static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
895 unsigned long timeo)
896{
897 int i;
898 for (i = 0; i < timeo; i++) {
899 if (chip->dev_ready) {
900 if (chip->dev_ready(mtd))
901 break;
902 } else {
903 if (chip->read_byte(mtd) & NAND_STATUS_READY)
904 break;
905 }
906 mdelay(1);
f8ac0414 907 }
2af7c653
SK
908}
909
1da177e4 910/**
8b6e50c9
BN
911 * nand_wait - [DEFAULT] wait until the command is done
912 * @mtd: MTD device structure
913 * @chip: NAND chip structure
1da177e4 914 *
b70af9be 915 * Wait for command done. This applies to erase and program only.
844d3b42 916 */
7bc3312b 917static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
1da177e4
LT
918{
919
b70af9be
AS
920 int status;
921 unsigned long timeo = 400;
1da177e4 922
8b6e50c9
BN
923 /*
924 * Apply this short delay always to ensure that we do wait tWB in any
925 * case on any machine.
926 */
e0c7d767 927 ndelay(100);
1da177e4 928
14c65786 929 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1da177e4 930
2af7c653
SK
931 if (in_interrupt() || oops_in_progress)
932 panic_nand_wait(mtd, chip, timeo);
933 else {
6d2559f8 934 timeo = jiffies + msecs_to_jiffies(timeo);
b70af9be 935 do {
2af7c653
SK
936 if (chip->dev_ready) {
937 if (chip->dev_ready(mtd))
938 break;
939 } else {
940 if (chip->read_byte(mtd) & NAND_STATUS_READY)
941 break;
942 }
943 cond_resched();
b70af9be 944 } while (time_before(jiffies, timeo));
1da177e4 945 }
8fe833c1 946
ace4dfee 947 status = (int)chip->read_byte(mtd);
f251b8df
MC
948 /* This can happen if in case of timeout or buggy dev_ready */
949 WARN_ON(!(status & NAND_STATUS_READY));
1da177e4
LT
950 return status;
951}
952
d8e725dd
BB
953/**
954 * nand_reset_data_interface - Reset data interface and timings
955 * @chip: The NAND chip
956 *
957 * Reset the Data interface and timings to ONFI mode 0.
958 *
959 * Returns 0 for success or negative error code otherwise.
960 */
961static int nand_reset_data_interface(struct nand_chip *chip)
962{
963 struct mtd_info *mtd = nand_to_mtd(chip);
964 const struct nand_data_interface *conf;
965 int ret;
966
967 if (!chip->setup_data_interface)
968 return 0;
969
970 /*
971 * The ONFI specification says:
972 * "
973 * To transition from NV-DDR or NV-DDR2 to the SDR data
974 * interface, the host shall use the Reset (FFh) command
975 * using SDR timing mode 0. A device in any timing mode is
976 * required to recognize Reset (FFh) command issued in SDR
977 * timing mode 0.
978 * "
979 *
980 * Configure the data interface in SDR mode and set the
981 * timings to timing mode 0.
982 */
983
984 conf = nand_get_default_data_interface();
985 ret = chip->setup_data_interface(mtd, conf, false);
986 if (ret)
987 pr_err("Failed to configure data interface to SDR timing mode 0\n");
988
989 return ret;
990}
991
992/**
993 * nand_setup_data_interface - Setup the best data interface and timings
994 * @chip: The NAND chip
995 *
996 * Find and configure the best data interface and NAND timings supported by
997 * the chip and the driver.
998 * First tries to retrieve supported timing modes from ONFI information,
999 * and if the NAND chip does not support ONFI, relies on the
1000 * ->onfi_timing_mode_default specified in the nand_ids table.
1001 *
1002 * Returns 0 for success or negative error code otherwise.
1003 */
1004static int nand_setup_data_interface(struct nand_chip *chip)
1005{
1006 struct mtd_info *mtd = nand_to_mtd(chip);
1007 int ret;
1008
1009 if (!chip->setup_data_interface || !chip->data_interface)
1010 return 0;
1011
1012 /*
1013 * Ensure the timing mode has been changed on the chip side
1014 * before changing timings on the controller side.
1015 */
1016 if (chip->onfi_version) {
1017 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1018 chip->onfi_timing_mode_default,
1019 };
1020
1021 ret = chip->onfi_set_features(mtd, chip,
1022 ONFI_FEATURE_ADDR_TIMING_MODE,
1023 tmode_param);
1024 if (ret)
1025 goto err;
1026 }
1027
1028 ret = chip->setup_data_interface(mtd, chip->data_interface, false);
1029err:
1030 return ret;
1031}
1032
1033/**
1034 * nand_init_data_interface - find the best data interface and timings
1035 * @chip: The NAND chip
1036 *
1037 * Find the best data interface and NAND timings supported by the chip
1038 * and the driver.
1039 * First tries to retrieve supported timing modes from ONFI information,
1040 * and if the NAND chip does not support ONFI, relies on the
1041 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1042 * function nand_chip->data_interface is initialized with the best timing mode
1043 * available.
1044 *
1045 * Returns 0 for success or negative error code otherwise.
1046 */
1047static int nand_init_data_interface(struct nand_chip *chip)
1048{
1049 struct mtd_info *mtd = nand_to_mtd(chip);
1050 int modes, mode, ret;
1051
1052 if (!chip->setup_data_interface)
1053 return 0;
1054
1055 /*
1056 * First try to identify the best timings from ONFI parameters and
1057 * if the NAND does not support ONFI, fallback to the default ONFI
1058 * timing mode.
1059 */
1060 modes = onfi_get_async_timing_mode(chip);
1061 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1062 if (!chip->onfi_timing_mode_default)
1063 return 0;
1064
1065 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1066 }
1067
1068 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1069 GFP_KERNEL);
1070 if (!chip->data_interface)
1071 return -ENOMEM;
1072
1073 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1074 ret = onfi_init_data_interface(chip, chip->data_interface,
1075 NAND_SDR_IFACE, mode);
1076 if (ret)
1077 continue;
1078
1079 ret = chip->setup_data_interface(mtd, chip->data_interface,
1080 true);
1081 if (!ret) {
1082 chip->onfi_timing_mode_default = mode;
1083 break;
1084 }
1085 }
1086
1087 return 0;
1088}
1089
1090static void nand_release_data_interface(struct nand_chip *chip)
1091{
1092 kfree(chip->data_interface);
1093}
1094
2f94abfe
SH
1095/**
1096 * nand_reset - Reset and initialize a NAND device
1097 * @chip: The NAND chip
73f907fd 1098 * @chipnr: Internal die id
2f94abfe
SH
1099 *
1100 * Returns 0 for success or negative error code otherwise
1101 */
73f907fd 1102int nand_reset(struct nand_chip *chip, int chipnr)
2f94abfe
SH
1103{
1104 struct mtd_info *mtd = nand_to_mtd(chip);
d8e725dd
BB
1105 int ret;
1106
1107 ret = nand_reset_data_interface(chip);
1108 if (ret)
1109 return ret;
2f94abfe 1110
73f907fd
BB
1111 /*
1112 * The CS line has to be released before we can apply the new NAND
1113 * interface settings, hence this weird ->select_chip() dance.
1114 */
1115 chip->select_chip(mtd, chipnr);
2f94abfe 1116 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
73f907fd 1117 chip->select_chip(mtd, -1);
2f94abfe 1118
73f907fd 1119 chip->select_chip(mtd, chipnr);
d8e725dd 1120 ret = nand_setup_data_interface(chip);
73f907fd 1121 chip->select_chip(mtd, -1);
d8e725dd
BB
1122 if (ret)
1123 return ret;
1124
2f94abfe
SH
1125 return 0;
1126}
1127
7d70f334 1128/**
b6d676db 1129 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
b6d676db
RD
1130 * @mtd: mtd info
1131 * @ofs: offset to start unlock from
1132 * @len: length to unlock
8b6e50c9
BN
1133 * @invert: when = 0, unlock the range of blocks within the lower and
1134 * upper boundary address
1135 * when = 1, unlock the range of blocks outside the boundaries
1136 * of the lower and upper boundary address
7d70f334 1137 *
8b6e50c9 1138 * Returs unlock status.
7d70f334
VS
1139 */
1140static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
1141 uint64_t len, int invert)
1142{
1143 int ret = 0;
1144 int status, page;
862eba51 1145 struct nand_chip *chip = mtd_to_nand(mtd);
7d70f334
VS
1146
1147 /* Submit address of first page to unlock */
1148 page = ofs >> chip->page_shift;
1149 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
1150
1151 /* Submit address of last page to unlock */
1152 page = (ofs + len) >> chip->page_shift;
1153 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
1154 (page | invert) & chip->pagemask);
1155
1156 /* Call wait ready function */
1157 status = chip->waitfunc(mtd, chip);
7d70f334 1158 /* See if device thinks it succeeded */
74830966 1159 if (status & NAND_STATUS_FAIL) {
289c0522 1160 pr_debug("%s: error status = 0x%08x\n",
7d70f334
VS
1161 __func__, status);
1162 ret = -EIO;
1163 }
1164
1165 return ret;
1166}
1167
1168/**
b6d676db 1169 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
b6d676db
RD
1170 * @mtd: mtd info
1171 * @ofs: offset to start unlock from
1172 * @len: length to unlock
7d70f334 1173 *
8b6e50c9 1174 * Returns unlock status.
7d70f334
VS
1175 */
1176int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1177{
1178 int ret = 0;
1179 int chipnr;
862eba51 1180 struct nand_chip *chip = mtd_to_nand(mtd);
7d70f334 1181
289c0522 1182 pr_debug("%s: start = 0x%012llx, len = %llu\n",
7d70f334
VS
1183 __func__, (unsigned long long)ofs, len);
1184
1185 if (check_offs_len(mtd, ofs, len))
b1a2348a 1186 return -EINVAL;
7d70f334
VS
1187
1188 /* Align to last block address if size addresses end of the device */
1189 if (ofs + len == mtd->size)
1190 len -= mtd->erasesize;
1191
6a8214aa 1192 nand_get_device(mtd, FL_UNLOCKING);
7d70f334
VS
1193
1194 /* Shift to get chip number */
1195 chipnr = ofs >> chip->chip_shift;
1196
57d3a9a8
WD
1197 /*
1198 * Reset the chip.
1199 * If we want to check the WP through READ STATUS and check the bit 7
1200 * we must reset the chip
1201 * some operation can also clear the bit 7 of status register
1202 * eg. erase/program a locked block
1203 */
73f907fd
BB
1204 nand_reset(chip, chipnr);
1205
1206 chip->select_chip(mtd, chipnr);
57d3a9a8 1207
7d70f334
VS
1208 /* Check, if it is write protected */
1209 if (nand_check_wp(mtd)) {
289c0522 1210 pr_debug("%s: device is write protected!\n",
7d70f334
VS
1211 __func__);
1212 ret = -EIO;
1213 goto out;
1214 }
1215
1216 ret = __nand_unlock(mtd, ofs, len, 0);
1217
1218out:
b0bb6903 1219 chip->select_chip(mtd, -1);
7d70f334
VS
1220 nand_release_device(mtd);
1221
1222 return ret;
1223}
7351d3a5 1224EXPORT_SYMBOL(nand_unlock);
7d70f334
VS
1225
1226/**
b6d676db 1227 * nand_lock - [REPLACEABLE] locks all blocks present in the device
b6d676db
RD
1228 * @mtd: mtd info
1229 * @ofs: offset to start unlock from
1230 * @len: length to unlock
7d70f334 1231 *
8b6e50c9
BN
1232 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1233 * have this feature, but it allows only to lock all blocks, not for specified
1234 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1235 * now.
7d70f334 1236 *
8b6e50c9 1237 * Returns lock status.
7d70f334
VS
1238 */
1239int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1240{
1241 int ret = 0;
1242 int chipnr, status, page;
862eba51 1243 struct nand_chip *chip = mtd_to_nand(mtd);
7d70f334 1244
289c0522 1245 pr_debug("%s: start = 0x%012llx, len = %llu\n",
7d70f334
VS
1246 __func__, (unsigned long long)ofs, len);
1247
1248 if (check_offs_len(mtd, ofs, len))
b1a2348a 1249 return -EINVAL;
7d70f334 1250
6a8214aa 1251 nand_get_device(mtd, FL_LOCKING);
7d70f334
VS
1252
1253 /* Shift to get chip number */
1254 chipnr = ofs >> chip->chip_shift;
1255
57d3a9a8
WD
1256 /*
1257 * Reset the chip.
1258 * If we want to check the WP through READ STATUS and check the bit 7
1259 * we must reset the chip
1260 * some operation can also clear the bit 7 of status register
1261 * eg. erase/program a locked block
1262 */
73f907fd
BB
1263 nand_reset(chip, chipnr);
1264
1265 chip->select_chip(mtd, chipnr);
57d3a9a8 1266
7d70f334
VS
1267 /* Check, if it is write protected */
1268 if (nand_check_wp(mtd)) {
289c0522 1269 pr_debug("%s: device is write protected!\n",
7d70f334
VS
1270 __func__);
1271 status = MTD_ERASE_FAILED;
1272 ret = -EIO;
1273 goto out;
1274 }
1275
1276 /* Submit address of first page to lock */
1277 page = ofs >> chip->page_shift;
1278 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1279
1280 /* Call wait ready function */
1281 status = chip->waitfunc(mtd, chip);
7d70f334 1282 /* See if device thinks it succeeded */
74830966 1283 if (status & NAND_STATUS_FAIL) {
289c0522 1284 pr_debug("%s: error status = 0x%08x\n",
7d70f334
VS
1285 __func__, status);
1286 ret = -EIO;
1287 goto out;
1288 }
1289
1290 ret = __nand_unlock(mtd, ofs, len, 0x1);
1291
1292out:
b0bb6903 1293 chip->select_chip(mtd, -1);
7d70f334
VS
1294 nand_release_device(mtd);
1295
1296 return ret;
1297}
7351d3a5 1298EXPORT_SYMBOL(nand_lock);
7d70f334 1299
730a43fb
BB
1300/**
1301 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1302 * @buf: buffer to test
1303 * @len: buffer length
1304 * @bitflips_threshold: maximum number of bitflips
1305 *
1306 * Check if a buffer contains only 0xff, which means the underlying region
1307 * has been erased and is ready to be programmed.
1308 * The bitflips_threshold specify the maximum number of bitflips before
1309 * considering the region is not erased.
1310 * Note: The logic of this function has been extracted from the memweight
1311 * implementation, except that nand_check_erased_buf function exit before
1312 * testing the whole buffer if the number of bitflips exceed the
1313 * bitflips_threshold value.
1314 *
1315 * Returns a positive number of bitflips less than or equal to
1316 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1317 * threshold.
1318 */
1319static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1320{
1321 const unsigned char *bitmap = buf;
1322 int bitflips = 0;
1323 int weight;
1324
1325 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1326 len--, bitmap++) {
1327 weight = hweight8(*bitmap);
1328 bitflips += BITS_PER_BYTE - weight;
1329 if (unlikely(bitflips > bitflips_threshold))
1330 return -EBADMSG;
1331 }
1332
1333 for (; len >= sizeof(long);
1334 len -= sizeof(long), bitmap += sizeof(long)) {
1335 weight = hweight_long(*((unsigned long *)bitmap));
1336 bitflips += BITS_PER_LONG - weight;
1337 if (unlikely(bitflips > bitflips_threshold))
1338 return -EBADMSG;
1339 }
1340
1341 for (; len > 0; len--, bitmap++) {
1342 weight = hweight8(*bitmap);
1343 bitflips += BITS_PER_BYTE - weight;
1344 if (unlikely(bitflips > bitflips_threshold))
1345 return -EBADMSG;
1346 }
1347
1348 return bitflips;
1349}
1350
1351/**
1352 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1353 * 0xff data
1354 * @data: data buffer to test
1355 * @datalen: data length
1356 * @ecc: ECC buffer
1357 * @ecclen: ECC length
1358 * @extraoob: extra OOB buffer
1359 * @extraooblen: extra OOB length
1360 * @bitflips_threshold: maximum number of bitflips
1361 *
1362 * Check if a data buffer and its associated ECC and OOB data contains only
1363 * 0xff pattern, which means the underlying region has been erased and is
1364 * ready to be programmed.
1365 * The bitflips_threshold specify the maximum number of bitflips before
1366 * considering the region as not erased.
1367 *
1368 * Note:
1369 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1370 * different from the NAND page size. When fixing bitflips, ECC engines will
1371 * report the number of errors per chunk, and the NAND core infrastructure
1372 * expect you to return the maximum number of bitflips for the whole page.
1373 * This is why you should always use this function on a single chunk and
1374 * not on the whole page. After checking each chunk you should update your
1375 * max_bitflips value accordingly.
1376 * 2/ When checking for bitflips in erased pages you should not only check
1377 * the payload data but also their associated ECC data, because a user might
1378 * have programmed almost all bits to 1 but a few. In this case, we
1379 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1380 * this case.
1381 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1382 * data are protected by the ECC engine.
1383 * It could also be used if you support subpages and want to attach some
1384 * extra OOB data to an ECC chunk.
1385 *
1386 * Returns a positive number of bitflips less than or equal to
1387 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1388 * threshold. In case of success, the passed buffers are filled with 0xff.
1389 */
1390int nand_check_erased_ecc_chunk(void *data, int datalen,
1391 void *ecc, int ecclen,
1392 void *extraoob, int extraooblen,
1393 int bitflips_threshold)
1394{
1395 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1396
1397 data_bitflips = nand_check_erased_buf(data, datalen,
1398 bitflips_threshold);
1399 if (data_bitflips < 0)
1400 return data_bitflips;
1401
1402 bitflips_threshold -= data_bitflips;
1403
1404 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1405 if (ecc_bitflips < 0)
1406 return ecc_bitflips;
1407
1408 bitflips_threshold -= ecc_bitflips;
1409
1410 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1411 bitflips_threshold);
1412 if (extraoob_bitflips < 0)
1413 return extraoob_bitflips;
1414
1415 if (data_bitflips)
1416 memset(data, 0xff, datalen);
1417
1418 if (ecc_bitflips)
1419 memset(ecc, 0xff, ecclen);
1420
1421 if (extraoob_bitflips)
1422 memset(extraoob, 0xff, extraooblen);
1423
1424 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1425}
1426EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1427
8593fbc6 1428/**
7854d3f7 1429 * nand_read_page_raw - [INTERN] read raw page data without ecc
8b6e50c9
BN
1430 * @mtd: mtd info structure
1431 * @chip: nand chip info structure
1432 * @buf: buffer to store read data
1fbb938d 1433 * @oob_required: caller requires OOB data read to chip->oob_poi
8b6e50c9 1434 * @page: page number to read
52ff49df 1435 *
7854d3f7 1436 * Not for syndrome calculating ECC controllers, which use a special oob layout.
8593fbc6
TG
1437 */
1438static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1fbb938d 1439 uint8_t *buf, int oob_required, int page)
8593fbc6
TG
1440{
1441 chip->read_buf(mtd, buf, mtd->writesize);
279f08d4
BN
1442 if (oob_required)
1443 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
8593fbc6
TG
1444 return 0;
1445}
1446
52ff49df 1447/**
7854d3f7 1448 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
8b6e50c9
BN
1449 * @mtd: mtd info structure
1450 * @chip: nand chip info structure
1451 * @buf: buffer to store read data
1fbb938d 1452 * @oob_required: caller requires OOB data read to chip->oob_poi
8b6e50c9 1453 * @page: page number to read
52ff49df
DB
1454 *
1455 * We need a special oob layout and handling even when OOB isn't used.
1456 */
7351d3a5 1457static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1fbb938d
BN
1458 struct nand_chip *chip, uint8_t *buf,
1459 int oob_required, int page)
52ff49df
DB
1460{
1461 int eccsize = chip->ecc.size;
1462 int eccbytes = chip->ecc.bytes;
1463 uint8_t *oob = chip->oob_poi;
1464 int steps, size;
1465
1466 for (steps = chip->ecc.steps; steps > 0; steps--) {
1467 chip->read_buf(mtd, buf, eccsize);
1468 buf += eccsize;
1469
1470 if (chip->ecc.prepad) {
1471 chip->read_buf(mtd, oob, chip->ecc.prepad);
1472 oob += chip->ecc.prepad;
1473 }
1474
1475 chip->read_buf(mtd, oob, eccbytes);
1476 oob += eccbytes;
1477
1478 if (chip->ecc.postpad) {
1479 chip->read_buf(mtd, oob, chip->ecc.postpad);
1480 oob += chip->ecc.postpad;
1481 }
1482 }
1483
1484 size = mtd->oobsize - (oob - chip->oob_poi);
1485 if (size)
1486 chip->read_buf(mtd, oob, size);
1487
1488 return 0;
1489}
1490
1da177e4 1491/**
7854d3f7 1492 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
8b6e50c9
BN
1493 * @mtd: mtd info structure
1494 * @chip: nand chip info structure
1495 * @buf: buffer to store read data
1fbb938d 1496 * @oob_required: caller requires OOB data read to chip->oob_poi
8b6e50c9 1497 * @page: page number to read
068e3c0a 1498 */
f5bbdacc 1499static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1fbb938d 1500 uint8_t *buf, int oob_required, int page)
1da177e4 1501{
846031d3 1502 int i, eccsize = chip->ecc.size, ret;
f5bbdacc
TG
1503 int eccbytes = chip->ecc.bytes;
1504 int eccsteps = chip->ecc.steps;
1505 uint8_t *p = buf;
4bf63fcb
DW
1506 uint8_t *ecc_calc = chip->buffers->ecccalc;
1507 uint8_t *ecc_code = chip->buffers->ecccode;
3f91e94f 1508 unsigned int max_bitflips = 0;
f5bbdacc 1509
1fbb938d 1510 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
f5bbdacc
TG
1511
1512 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1513 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1514
846031d3
BB
1515 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1516 chip->ecc.total);
1517 if (ret)
1518 return ret;
f5bbdacc
TG
1519
1520 eccsteps = chip->ecc.steps;
1521 p = buf;
1522
1523 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1524 int stat;
1525
1526 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
3f91e94f 1527 if (stat < 0) {
f5bbdacc 1528 mtd->ecc_stats.failed++;
3f91e94f 1529 } else {
f5bbdacc 1530 mtd->ecc_stats.corrected += stat;
3f91e94f
MD
1531 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1532 }
f5bbdacc 1533 }
3f91e94f 1534 return max_bitflips;
22c60f5f 1535}
1da177e4 1536
3d459559 1537/**
837a6ba4 1538 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
8b6e50c9
BN
1539 * @mtd: mtd info structure
1540 * @chip: nand chip info structure
1541 * @data_offs: offset of requested data within the page
1542 * @readlen: data length
1543 * @bufpoi: buffer to store read data
e004debd 1544 * @page: page number to read
3d459559 1545 */
7351d3a5 1546static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
e004debd
HS
1547 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1548 int page)
3d459559 1549{
846031d3 1550 int start_step, end_step, num_steps, ret;
3d459559
AK
1551 uint8_t *p;
1552 int data_col_addr, i, gaps = 0;
1553 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1554 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
846031d3 1555 int index, section = 0;
3f91e94f 1556 unsigned int max_bitflips = 0;
846031d3 1557 struct mtd_oob_region oobregion = { };
3d459559 1558
7854d3f7 1559 /* Column address within the page aligned to ECC size (256bytes) */
3d459559
AK
1560 start_step = data_offs / chip->ecc.size;
1561 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1562 num_steps = end_step - start_step + 1;
4a4163ca 1563 index = start_step * chip->ecc.bytes;
3d459559 1564
8b6e50c9 1565 /* Data size aligned to ECC ecc.size */
3d459559
AK
1566 datafrag_len = num_steps * chip->ecc.size;
1567 eccfrag_len = num_steps * chip->ecc.bytes;
1568
1569 data_col_addr = start_step * chip->ecc.size;
1570 /* If we read not a page aligned data */
1571 if (data_col_addr != 0)
1572 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1573
1574 p = bufpoi + data_col_addr;
1575 chip->read_buf(mtd, p, datafrag_len);
1576
8b6e50c9 1577 /* Calculate ECC */
3d459559
AK
1578 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1579 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1580
8b6e50c9
BN
1581 /*
1582 * The performance is faster if we position offsets according to
7854d3f7 1583 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
8b6e50c9 1584 */
846031d3
BB
1585 ret = mtd_ooblayout_find_eccregion(mtd, index, &section, &oobregion);
1586 if (ret)
1587 return ret;
1588
1589 if (oobregion.length < eccfrag_len)
1590 gaps = 1;
1591
3d459559
AK
1592 if (gaps) {
1593 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1594 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1595 } else {
8b6e50c9 1596 /*
7854d3f7 1597 * Send the command to read the particular ECC bytes take care
8b6e50c9
BN
1598 * about buswidth alignment in read_buf.
1599 */
846031d3 1600 aligned_pos = oobregion.offset & ~(busw - 1);
3d459559 1601 aligned_len = eccfrag_len;
846031d3 1602 if (oobregion.offset & (busw - 1))
3d459559 1603 aligned_len++;
846031d3
BB
1604 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1605 (busw - 1))
3d459559
AK
1606 aligned_len++;
1607
7351d3a5 1608 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
846031d3 1609 mtd->writesize + aligned_pos, -1);
3d459559
AK
1610 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1611 }
1612
846031d3
BB
1613 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1614 chip->oob_poi, index, eccfrag_len);
1615 if (ret)
1616 return ret;
3d459559
AK
1617
1618 p = bufpoi + data_col_addr;
1619 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1620 int stat;
1621
7351d3a5
FF
1622 stat = chip->ecc.correct(mtd, p,
1623 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
40cbe6ee
BB
1624 if (stat == -EBADMSG &&
1625 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1626 /* check for empty pages with bitflips */
1627 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1628 &chip->buffers->ecccode[i],
1629 chip->ecc.bytes,
1630 NULL, 0,
1631 chip->ecc.strength);
1632 }
1633
3f91e94f 1634 if (stat < 0) {
3d459559 1635 mtd->ecc_stats.failed++;
3f91e94f 1636 } else {
3d459559 1637 mtd->ecc_stats.corrected += stat;
3f91e94f
MD
1638 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1639 }
3d459559 1640 }
3f91e94f 1641 return max_bitflips;
3d459559
AK
1642}
1643
068e3c0a 1644/**
7854d3f7 1645 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
8b6e50c9
BN
1646 * @mtd: mtd info structure
1647 * @chip: nand chip info structure
1648 * @buf: buffer to store read data
1fbb938d 1649 * @oob_required: caller requires OOB data read to chip->oob_poi
8b6e50c9 1650 * @page: page number to read
068e3c0a 1651 *
7854d3f7 1652 * Not for syndrome calculating ECC controllers which need a special oob layout.
068e3c0a 1653 */
f5bbdacc 1654static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1fbb938d 1655 uint8_t *buf, int oob_required, int page)
1da177e4 1656{
846031d3 1657 int i, eccsize = chip->ecc.size, ret;
f5bbdacc
TG
1658 int eccbytes = chip->ecc.bytes;
1659 int eccsteps = chip->ecc.steps;
1660 uint8_t *p = buf;
4bf63fcb
DW
1661 uint8_t *ecc_calc = chip->buffers->ecccalc;
1662 uint8_t *ecc_code = chip->buffers->ecccode;
3f91e94f 1663 unsigned int max_bitflips = 0;
f5bbdacc
TG
1664
1665 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1666 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1667 chip->read_buf(mtd, p, eccsize);
1668 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1da177e4 1669 }
f75e5097 1670 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1da177e4 1671
846031d3
BB
1672 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1673 chip->ecc.total);
1674 if (ret)
1675 return ret;
1da177e4 1676
f5bbdacc
TG
1677 eccsteps = chip->ecc.steps;
1678 p = buf;
61b03bd7 1679
f5bbdacc
TG
1680 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1681 int stat;
1da177e4 1682
f5bbdacc 1683 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
40cbe6ee
BB
1684 if (stat == -EBADMSG &&
1685 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1686 /* check for empty pages with bitflips */
1687 stat = nand_check_erased_ecc_chunk(p, eccsize,
1688 &ecc_code[i], eccbytes,
1689 NULL, 0,
1690 chip->ecc.strength);
1691 }
1692
3f91e94f 1693 if (stat < 0) {
f5bbdacc 1694 mtd->ecc_stats.failed++;
3f91e94f 1695 } else {
f5bbdacc 1696 mtd->ecc_stats.corrected += stat;
3f91e94f
MD
1697 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1698 }
f5bbdacc 1699 }
3f91e94f 1700 return max_bitflips;
f5bbdacc 1701}
1da177e4 1702
6e0cb135 1703/**
7854d3f7 1704 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
8b6e50c9
BN
1705 * @mtd: mtd info structure
1706 * @chip: nand chip info structure
1707 * @buf: buffer to store read data
1fbb938d 1708 * @oob_required: caller requires OOB data read to chip->oob_poi
8b6e50c9 1709 * @page: page number to read
6e0cb135 1710 *
8b6e50c9
BN
1711 * Hardware ECC for large page chips, require OOB to be read first. For this
1712 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1713 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1714 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1715 * the data area, by overwriting the NAND manufacturer bad block markings.
6e0cb135
SN
1716 */
1717static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1fbb938d 1718 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
6e0cb135 1719{
846031d3 1720 int i, eccsize = chip->ecc.size, ret;
6e0cb135
SN
1721 int eccbytes = chip->ecc.bytes;
1722 int eccsteps = chip->ecc.steps;
1723 uint8_t *p = buf;
1724 uint8_t *ecc_code = chip->buffers->ecccode;
6e0cb135 1725 uint8_t *ecc_calc = chip->buffers->ecccalc;
3f91e94f 1726 unsigned int max_bitflips = 0;
6e0cb135
SN
1727
1728 /* Read the OOB area first */
1729 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1730 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1731 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1732
846031d3
BB
1733 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1734 chip->ecc.total);
1735 if (ret)
1736 return ret;
6e0cb135
SN
1737
1738 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1739 int stat;
1740
1741 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1742 chip->read_buf(mtd, p, eccsize);
1743 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1744
1745 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
40cbe6ee
BB
1746 if (stat == -EBADMSG &&
1747 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1748 /* check for empty pages with bitflips */
1749 stat = nand_check_erased_ecc_chunk(p, eccsize,
1750 &ecc_code[i], eccbytes,
1751 NULL, 0,
1752 chip->ecc.strength);
1753 }
1754
3f91e94f 1755 if (stat < 0) {
6e0cb135 1756 mtd->ecc_stats.failed++;
3f91e94f 1757 } else {
6e0cb135 1758 mtd->ecc_stats.corrected += stat;
3f91e94f
MD
1759 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1760 }
6e0cb135 1761 }
3f91e94f 1762 return max_bitflips;
6e0cb135
SN
1763}
1764
f5bbdacc 1765/**
7854d3f7 1766 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
8b6e50c9
BN
1767 * @mtd: mtd info structure
1768 * @chip: nand chip info structure
1769 * @buf: buffer to store read data
1fbb938d 1770 * @oob_required: caller requires OOB data read to chip->oob_poi
8b6e50c9 1771 * @page: page number to read
f5bbdacc 1772 *
8b6e50c9
BN
1773 * The hw generator calculates the error syndrome automatically. Therefore we
1774 * need a special oob layout and handling.
f5bbdacc
TG
1775 */
1776static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1fbb938d 1777 uint8_t *buf, int oob_required, int page)
f5bbdacc
TG
1778{
1779 int i, eccsize = chip->ecc.size;
1780 int eccbytes = chip->ecc.bytes;
1781 int eccsteps = chip->ecc.steps;
40cbe6ee 1782 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
f5bbdacc 1783 uint8_t *p = buf;
f75e5097 1784 uint8_t *oob = chip->oob_poi;
3f91e94f 1785 unsigned int max_bitflips = 0;
1da177e4 1786
f5bbdacc
TG
1787 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1788 int stat;
61b03bd7 1789
f5bbdacc
TG
1790 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1791 chip->read_buf(mtd, p, eccsize);
1da177e4 1792
f5bbdacc
TG
1793 if (chip->ecc.prepad) {
1794 chip->read_buf(mtd, oob, chip->ecc.prepad);
1795 oob += chip->ecc.prepad;
1796 }
1da177e4 1797
f5bbdacc
TG
1798 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1799 chip->read_buf(mtd, oob, eccbytes);
1800 stat = chip->ecc.correct(mtd, p, oob, NULL);
61b03bd7 1801
f5bbdacc 1802 oob += eccbytes;
1da177e4 1803
f5bbdacc
TG
1804 if (chip->ecc.postpad) {
1805 chip->read_buf(mtd, oob, chip->ecc.postpad);
1806 oob += chip->ecc.postpad;
61b03bd7 1807 }
40cbe6ee
BB
1808
1809 if (stat == -EBADMSG &&
1810 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1811 /* check for empty pages with bitflips */
1812 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1813 oob - eccpadbytes,
1814 eccpadbytes,
1815 NULL, 0,
1816 chip->ecc.strength);
1817 }
1818
1819 if (stat < 0) {
1820 mtd->ecc_stats.failed++;
1821 } else {
1822 mtd->ecc_stats.corrected += stat;
1823 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1824 }
f5bbdacc 1825 }
1da177e4 1826
f5bbdacc 1827 /* Calculate remaining oob bytes */
7e4178f9 1828 i = mtd->oobsize - (oob - chip->oob_poi);
f5bbdacc
TG
1829 if (i)
1830 chip->read_buf(mtd, oob, i);
61b03bd7 1831
3f91e94f 1832 return max_bitflips;
f5bbdacc 1833}
1da177e4 1834
f5bbdacc 1835/**
7854d3f7 1836 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
846031d3 1837 * @mtd: mtd info structure
8b6e50c9
BN
1838 * @oob: oob destination address
1839 * @ops: oob ops structure
1840 * @len: size of oob to transfer
8593fbc6 1841 */
846031d3 1842static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
7014568b 1843 struct mtd_oob_ops *ops, size_t len)
8593fbc6 1844{
846031d3
BB
1845 struct nand_chip *chip = mtd_to_nand(mtd);
1846 int ret;
1847
f8ac0414 1848 switch (ops->mode) {
8593fbc6 1849
0612b9dd
BN
1850 case MTD_OPS_PLACE_OOB:
1851 case MTD_OPS_RAW:
8593fbc6
TG
1852 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1853 return oob + len;
1854
846031d3
BB
1855 case MTD_OPS_AUTO_OOB:
1856 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1857 ops->ooboffs, len);
1858 BUG_ON(ret);
1859 return oob + len;
1860
8593fbc6
TG
1861 default:
1862 BUG();
1863 }
1864 return NULL;
1865}
1866
ba84fb59
BN
1867/**
1868 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1869 * @mtd: MTD device structure
1870 * @retry_mode: the retry mode to use
1871 *
1872 * Some vendors supply a special command to shift the Vt threshold, to be used
1873 * when there are too many bitflips in a page (i.e., ECC error). After setting
1874 * a new threshold, the host should retry reading the page.
1875 */
1876static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1877{
862eba51 1878 struct nand_chip *chip = mtd_to_nand(mtd);
ba84fb59
BN
1879
1880 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1881
1882 if (retry_mode >= chip->read_retries)
1883 return -EINVAL;
1884
1885 if (!chip->setup_read_retry)
1886 return -EOPNOTSUPP;
1887
1888 return chip->setup_read_retry(mtd, retry_mode);
1889}
1890
8593fbc6 1891/**
7854d3f7 1892 * nand_do_read_ops - [INTERN] Read data with ECC
8b6e50c9
BN
1893 * @mtd: MTD device structure
1894 * @from: offset to read from
1895 * @ops: oob ops structure
f5bbdacc
TG
1896 *
1897 * Internal function. Called with chip held.
1898 */
8593fbc6
TG
1899static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1900 struct mtd_oob_ops *ops)
f5bbdacc 1901{
e47f3db4 1902 int chipnr, page, realpage, col, bytes, aligned, oob_required;
862eba51 1903 struct nand_chip *chip = mtd_to_nand(mtd);
f5bbdacc 1904 int ret = 0;
8593fbc6 1905 uint32_t readlen = ops->len;
7014568b 1906 uint32_t oobreadlen = ops->ooblen;
29f1058a 1907 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
9aca334e 1908
8593fbc6 1909 uint8_t *bufpoi, *oob, *buf;
66507c7b 1910 int use_bufpoi;
edbc4540 1911 unsigned int max_bitflips = 0;
ba84fb59 1912 int retry_mode = 0;
b72f3dfb 1913 bool ecc_fail = false;
1da177e4 1914
f5bbdacc
TG
1915 chipnr = (int)(from >> chip->chip_shift);
1916 chip->select_chip(mtd, chipnr);
61b03bd7 1917
f5bbdacc
TG
1918 realpage = (int)(from >> chip->page_shift);
1919 page = realpage & chip->pagemask;
1da177e4 1920
f5bbdacc 1921 col = (int)(from & (mtd->writesize - 1));
61b03bd7 1922
8593fbc6
TG
1923 buf = ops->datbuf;
1924 oob = ops->oobbuf;
e47f3db4 1925 oob_required = oob ? 1 : 0;
8593fbc6 1926
f8ac0414 1927 while (1) {
b72f3dfb
BN
1928 unsigned int ecc_failures = mtd->ecc_stats.failed;
1929
f5bbdacc
TG
1930 bytes = min(mtd->writesize - col, readlen);
1931 aligned = (bytes == mtd->writesize);
61b03bd7 1932
66507c7b
KD
1933 if (!aligned)
1934 use_bufpoi = 1;
1935 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1936 use_bufpoi = !virt_addr_valid(buf);
1937 else
1938 use_bufpoi = 0;
1939
8b6e50c9 1940 /* Is the current page in the buffer? */
8593fbc6 1941 if (realpage != chip->pagebuf || oob) {
66507c7b
KD
1942 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1943
1944 if (use_bufpoi && aligned)
1945 pr_debug("%s: using read bounce buffer for buf@%p\n",
1946 __func__, buf);
61b03bd7 1947
ba84fb59 1948read_retry:
c00a0991 1949 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1da177e4 1950
edbc4540
MD
1951 /*
1952 * Now read the page into the buffer. Absent an error,
1953 * the read methods return max bitflips per ecc step.
1954 */
0612b9dd 1955 if (unlikely(ops->mode == MTD_OPS_RAW))
1fbb938d 1956 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
e47f3db4
BN
1957 oob_required,
1958 page);
a5ff4f10
JW
1959 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1960 !oob)
7351d3a5 1961 ret = chip->ecc.read_subpage(mtd, chip,
e004debd
HS
1962 col, bytes, bufpoi,
1963 page);
956e944c 1964 else
46a8cf2d 1965 ret = chip->ecc.read_page(mtd, chip, bufpoi,
e47f3db4 1966 oob_required, page);
6d77b9d0 1967 if (ret < 0) {
66507c7b 1968 if (use_bufpoi)
6d77b9d0
BN
1969 /* Invalidate page cache */
1970 chip->pagebuf = -1;
1da177e4 1971 break;
6d77b9d0 1972 }
f5bbdacc 1973
edbc4540
MD
1974 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1975
f5bbdacc 1976 /* Transfer not aligned data */
66507c7b 1977 if (use_bufpoi) {
a5ff4f10 1978 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
b72f3dfb 1979 !(mtd->ecc_stats.failed - ecc_failures) &&
edbc4540 1980 (ops->mode != MTD_OPS_RAW)) {
3d459559 1981 chip->pagebuf = realpage;
edbc4540
MD
1982 chip->pagebuf_bitflips = ret;
1983 } else {
6d77b9d0
BN
1984 /* Invalidate page cache */
1985 chip->pagebuf = -1;
edbc4540 1986 }
4bf63fcb 1987 memcpy(buf, chip->buffers->databuf + col, bytes);
f5bbdacc
TG
1988 }
1989
8593fbc6 1990 if (unlikely(oob)) {
b64d39d8
ML
1991 int toread = min(oobreadlen, max_oobsize);
1992
1993 if (toread) {
846031d3 1994 oob = nand_transfer_oob(mtd,
b64d39d8
ML
1995 oob, ops, toread);
1996 oobreadlen -= toread;
1997 }
8593fbc6 1998 }
5bc7c33c
BN
1999
2000 if (chip->options & NAND_NEED_READRDY) {
2001 /* Apply delay or wait for ready/busy pin */
2002 if (!chip->dev_ready)
2003 udelay(chip->chip_delay);
2004 else
2005 nand_wait_ready(mtd);
2006 }
b72f3dfb 2007
ba84fb59 2008 if (mtd->ecc_stats.failed - ecc_failures) {
28fa65e6 2009 if (retry_mode + 1 < chip->read_retries) {
ba84fb59
BN
2010 retry_mode++;
2011 ret = nand_setup_read_retry(mtd,
2012 retry_mode);
2013 if (ret < 0)
2014 break;
2015
2016 /* Reset failures; retry */
2017 mtd->ecc_stats.failed = ecc_failures;
2018 goto read_retry;
2019 } else {
2020 /* No more retry modes; real failure */
2021 ecc_fail = true;
2022 }
2023 }
2024
2025 buf += bytes;
8593fbc6 2026 } else {
4bf63fcb 2027 memcpy(buf, chip->buffers->databuf + col, bytes);
8593fbc6 2028 buf += bytes;
edbc4540
MD
2029 max_bitflips = max_t(unsigned int, max_bitflips,
2030 chip->pagebuf_bitflips);
8593fbc6 2031 }
1da177e4 2032
f5bbdacc 2033 readlen -= bytes;
61b03bd7 2034
ba84fb59
BN
2035 /* Reset to retry mode 0 */
2036 if (retry_mode) {
2037 ret = nand_setup_read_retry(mtd, 0);
2038 if (ret < 0)
2039 break;
2040 retry_mode = 0;
2041 }
2042
f5bbdacc 2043 if (!readlen)
61b03bd7 2044 break;
1da177e4 2045
8b6e50c9 2046 /* For subsequent reads align to page boundary */
1da177e4
LT
2047 col = 0;
2048 /* Increment page address */
2049 realpage++;
2050
ace4dfee 2051 page = realpage & chip->pagemask;
1da177e4
LT
2052 /* Check, if we cross a chip boundary */
2053 if (!page) {
2054 chipnr++;
ace4dfee
TG
2055 chip->select_chip(mtd, -1);
2056 chip->select_chip(mtd, chipnr);
1da177e4 2057 }
1da177e4 2058 }
b0bb6903 2059 chip->select_chip(mtd, -1);
1da177e4 2060
8593fbc6 2061 ops->retlen = ops->len - (size_t) readlen;
7014568b
VW
2062 if (oob)
2063 ops->oobretlen = ops->ooblen - oobreadlen;
1da177e4 2064
3f91e94f 2065 if (ret < 0)
f5bbdacc
TG
2066 return ret;
2067
b72f3dfb 2068 if (ecc_fail)
9a1fcdfd
TG
2069 return -EBADMSG;
2070
edbc4540 2071 return max_bitflips;
f5bbdacc
TG
2072}
2073
2074/**
25985edc 2075 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
8b6e50c9
BN
2076 * @mtd: MTD device structure
2077 * @from: offset to read from
2078 * @len: number of bytes to read
2079 * @retlen: pointer to variable to store the number of read bytes
2080 * @buf: the databuffer to put data
f5bbdacc 2081 *
8b6e50c9 2082 * Get hold of the chip and call nand_do_read.
f5bbdacc
TG
2083 */
2084static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2085 size_t *retlen, uint8_t *buf)
2086{
4a89ff88 2087 struct mtd_oob_ops ops;
f5bbdacc
TG
2088 int ret;
2089
6a8214aa 2090 nand_get_device(mtd, FL_READING);
0ec56dc4 2091 memset(&ops, 0, sizeof(ops));
4a89ff88
BN
2092 ops.len = len;
2093 ops.datbuf = buf;
11041ae6 2094 ops.mode = MTD_OPS_PLACE_OOB;
4a89ff88 2095 ret = nand_do_read_ops(mtd, from, &ops);
4a89ff88 2096 *retlen = ops.retlen;
f5bbdacc 2097 nand_release_device(mtd);
f5bbdacc 2098 return ret;
1da177e4
LT
2099}
2100
7bc3312b 2101/**
7854d3f7 2102 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
8b6e50c9
BN
2103 * @mtd: mtd info structure
2104 * @chip: nand chip info structure
2105 * @page: page number to read
7bc3312b 2106 */
9d02fc2a 2107int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
7bc3312b 2108{
5c2ffb11 2109 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
7bc3312b 2110 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
5c2ffb11 2111 return 0;
7bc3312b 2112}
9d02fc2a 2113EXPORT_SYMBOL(nand_read_oob_std);
7bc3312b
TG
2114
2115/**
7854d3f7 2116 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
7bc3312b 2117 * with syndromes
8b6e50c9
BN
2118 * @mtd: mtd info structure
2119 * @chip: nand chip info structure
2120 * @page: page number to read
7bc3312b 2121 */
9d02fc2a
BB
2122int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2123 int page)
7bc3312b 2124{
7bc3312b
TG
2125 int length = mtd->oobsize;
2126 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2127 int eccsize = chip->ecc.size;
2ea69d21 2128 uint8_t *bufpoi = chip->oob_poi;
7bc3312b
TG
2129 int i, toread, sndrnd = 0, pos;
2130
2131 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2132 for (i = 0; i < chip->ecc.steps; i++) {
2133 if (sndrnd) {
2134 pos = eccsize + i * (eccsize + chunk);
2135 if (mtd->writesize > 512)
2136 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2137 else
2138 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2139 } else
2140 sndrnd = 1;
2141 toread = min_t(int, length, chunk);
2142 chip->read_buf(mtd, bufpoi, toread);
2143 bufpoi += toread;
2144 length -= toread;
2145 }
2146 if (length > 0)
2147 chip->read_buf(mtd, bufpoi, length);
2148
5c2ffb11 2149 return 0;
7bc3312b 2150}
9d02fc2a 2151EXPORT_SYMBOL(nand_read_oob_syndrome);
7bc3312b
TG
2152
2153/**
7854d3f7 2154 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
8b6e50c9
BN
2155 * @mtd: mtd info structure
2156 * @chip: nand chip info structure
2157 * @page: page number to write
7bc3312b 2158 */
9d02fc2a 2159int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
7bc3312b
TG
2160{
2161 int status = 0;
2162 const uint8_t *buf = chip->oob_poi;
2163 int length = mtd->oobsize;
2164
2165 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2166 chip->write_buf(mtd, buf, length);
2167 /* Send command to program the OOB data */
2168 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2169
2170 status = chip->waitfunc(mtd, chip);
2171
0d420f9d 2172 return status & NAND_STATUS_FAIL ? -EIO : 0;
7bc3312b 2173}
9d02fc2a 2174EXPORT_SYMBOL(nand_write_oob_std);
7bc3312b
TG
2175
2176/**
7854d3f7 2177 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
8b6e50c9
BN
2178 * with syndrome - only for large page flash
2179 * @mtd: mtd info structure
2180 * @chip: nand chip info structure
2181 * @page: page number to write
7bc3312b 2182 */
9d02fc2a
BB
2183int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2184 int page)
7bc3312b
TG
2185{
2186 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2187 int eccsize = chip->ecc.size, length = mtd->oobsize;
2188 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2189 const uint8_t *bufpoi = chip->oob_poi;
2190
2191 /*
2192 * data-ecc-data-ecc ... ecc-oob
2193 * or
2194 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2195 */
2196 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2197 pos = steps * (eccsize + chunk);
2198 steps = 0;
2199 } else
8b0036ee 2200 pos = eccsize;
7bc3312b
TG
2201
2202 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2203 for (i = 0; i < steps; i++) {
2204 if (sndcmd) {
2205 if (mtd->writesize <= 512) {
2206 uint32_t fill = 0xFFFFFFFF;
2207
2208 len = eccsize;
2209 while (len > 0) {
2210 int num = min_t(int, len, 4);
2211 chip->write_buf(mtd, (uint8_t *)&fill,
2212 num);
2213 len -= num;
2214 }
2215 } else {
2216 pos = eccsize + i * (eccsize + chunk);
2217 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2218 }
2219 } else
2220 sndcmd = 1;
2221 len = min_t(int, length, chunk);
2222 chip->write_buf(mtd, bufpoi, len);
2223 bufpoi += len;
2224 length -= len;
2225 }
2226 if (length > 0)
2227 chip->write_buf(mtd, bufpoi, length);
2228
2229 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2230 status = chip->waitfunc(mtd, chip);
2231
2232 return status & NAND_STATUS_FAIL ? -EIO : 0;
2233}
9d02fc2a 2234EXPORT_SYMBOL(nand_write_oob_syndrome);
7bc3312b 2235
1da177e4 2236/**
7854d3f7 2237 * nand_do_read_oob - [INTERN] NAND read out-of-band
8b6e50c9
BN
2238 * @mtd: MTD device structure
2239 * @from: offset to read from
2240 * @ops: oob operations description structure
1da177e4 2241 *
8b6e50c9 2242 * NAND read out-of-band data from the spare area.
1da177e4 2243 */
8593fbc6
TG
2244static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2245 struct mtd_oob_ops *ops)
1da177e4 2246{
c00a0991 2247 int page, realpage, chipnr;
862eba51 2248 struct nand_chip *chip = mtd_to_nand(mtd);
041e4575 2249 struct mtd_ecc_stats stats;
7014568b
VW
2250 int readlen = ops->ooblen;
2251 int len;
7bc3312b 2252 uint8_t *buf = ops->oobbuf;
1951f2f7 2253 int ret = 0;
61b03bd7 2254
289c0522 2255 pr_debug("%s: from = 0x%08Lx, len = %i\n",
20d8e248 2256 __func__, (unsigned long long)from, readlen);
1da177e4 2257
041e4575
BN
2258 stats = mtd->ecc_stats;
2259
29f1058a 2260 len = mtd_oobavail(mtd, ops);
03736155
AH
2261
2262 if (unlikely(ops->ooboffs >= len)) {
289c0522
BN
2263 pr_debug("%s: attempt to start read outside oob\n",
2264 __func__);
03736155
AH
2265 return -EINVAL;
2266 }
2267
2268 /* Do not allow reads past end of device */
2269 if (unlikely(from >= mtd->size ||
2270 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2271 (from >> chip->page_shift)) * len)) {
289c0522
BN
2272 pr_debug("%s: attempt to read beyond end of device\n",
2273 __func__);
03736155
AH
2274 return -EINVAL;
2275 }
7014568b 2276
7314e9e7 2277 chipnr = (int)(from >> chip->chip_shift);
ace4dfee 2278 chip->select_chip(mtd, chipnr);
1da177e4 2279
7314e9e7
TG
2280 /* Shift to get page */
2281 realpage = (int)(from >> chip->page_shift);
2282 page = realpage & chip->pagemask;
1da177e4 2283
f8ac0414 2284 while (1) {
0612b9dd 2285 if (ops->mode == MTD_OPS_RAW)
1951f2f7 2286 ret = chip->ecc.read_oob_raw(mtd, chip, page);
c46f6483 2287 else
1951f2f7
SL
2288 ret = chip->ecc.read_oob(mtd, chip, page);
2289
2290 if (ret < 0)
2291 break;
7014568b
VW
2292
2293 len = min(len, readlen);
846031d3 2294 buf = nand_transfer_oob(mtd, buf, ops, len);
8593fbc6 2295
5bc7c33c
BN
2296 if (chip->options & NAND_NEED_READRDY) {
2297 /* Apply delay or wait for ready/busy pin */
2298 if (!chip->dev_ready)
2299 udelay(chip->chip_delay);
2300 else
2301 nand_wait_ready(mtd);
2302 }
2303
7014568b 2304 readlen -= len;
0d420f9d
SZ
2305 if (!readlen)
2306 break;
2307
7314e9e7
TG
2308 /* Increment page address */
2309 realpage++;
2310
2311 page = realpage & chip->pagemask;
2312 /* Check, if we cross a chip boundary */
2313 if (!page) {
2314 chipnr++;
2315 chip->select_chip(mtd, -1);
2316 chip->select_chip(mtd, chipnr);
1da177e4
LT
2317 }
2318 }
b0bb6903 2319 chip->select_chip(mtd, -1);
1da177e4 2320
1951f2f7
SL
2321 ops->oobretlen = ops->ooblen - readlen;
2322
2323 if (ret < 0)
2324 return ret;
041e4575
BN
2325
2326 if (mtd->ecc_stats.failed - stats.failed)
2327 return -EBADMSG;
2328
2329 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
1da177e4
LT
2330}
2331
2332/**
8593fbc6 2333 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
8b6e50c9
BN
2334 * @mtd: MTD device structure
2335 * @from: offset to read from
2336 * @ops: oob operation description structure
1da177e4 2337 *
8b6e50c9 2338 * NAND read data and/or out-of-band data.
1da177e4 2339 */
8593fbc6
TG
2340static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2341 struct mtd_oob_ops *ops)
1da177e4 2342{
fc6b4d12 2343 int ret;
8593fbc6
TG
2344
2345 ops->retlen = 0;
1da177e4
LT
2346
2347 /* Do not allow reads past end of device */
7014568b 2348 if (ops->datbuf && (from + ops->len) > mtd->size) {
289c0522
BN
2349 pr_debug("%s: attempt to read beyond end of device\n",
2350 __func__);
1da177e4
LT
2351 return -EINVAL;
2352 }
2353
fc6b4d12
AS
2354 if (ops->mode != MTD_OPS_PLACE_OOB &&
2355 ops->mode != MTD_OPS_AUTO_OOB &&
2356 ops->mode != MTD_OPS_RAW)
2357 return -ENOTSUPP;
1da177e4 2358
fc6b4d12 2359 nand_get_device(mtd, FL_READING);
1da177e4 2360
8593fbc6
TG
2361 if (!ops->datbuf)
2362 ret = nand_do_read_oob(mtd, from, ops);
2363 else
2364 ret = nand_do_read_ops(mtd, from, ops);
61b03bd7 2365
8593fbc6
TG
2366 nand_release_device(mtd);
2367 return ret;
2368}
61b03bd7 2369
1da177e4 2370
8593fbc6 2371/**
7854d3f7 2372 * nand_write_page_raw - [INTERN] raw page write function
8b6e50c9
BN
2373 * @mtd: mtd info structure
2374 * @chip: nand chip info structure
2375 * @buf: data buffer
1fbb938d 2376 * @oob_required: must write chip->oob_poi to OOB
45aaeff9 2377 * @page: page number to write
52ff49df 2378 *
7854d3f7 2379 * Not for syndrome calculating ECC controllers, which use a special oob layout.
8593fbc6 2380 */
fdbad98d 2381static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
45aaeff9 2382 const uint8_t *buf, int oob_required, int page)
8593fbc6
TG
2383{
2384 chip->write_buf(mtd, buf, mtd->writesize);
279f08d4
BN
2385 if (oob_required)
2386 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
fdbad98d
JW
2387
2388 return 0;
1da177e4
LT
2389}
2390
52ff49df 2391/**
7854d3f7 2392 * nand_write_page_raw_syndrome - [INTERN] raw page write function
8b6e50c9
BN
2393 * @mtd: mtd info structure
2394 * @chip: nand chip info structure
2395 * @buf: data buffer
1fbb938d 2396 * @oob_required: must write chip->oob_poi to OOB
45aaeff9 2397 * @page: page number to write
52ff49df
DB
2398 *
2399 * We need a special oob layout and handling even when ECC isn't checked.
2400 */
fdbad98d 2401static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
7351d3a5 2402 struct nand_chip *chip,
45aaeff9
BB
2403 const uint8_t *buf, int oob_required,
2404 int page)
52ff49df
DB
2405{
2406 int eccsize = chip->ecc.size;
2407 int eccbytes = chip->ecc.bytes;
2408 uint8_t *oob = chip->oob_poi;
2409 int steps, size;
2410
2411 for (steps = chip->ecc.steps; steps > 0; steps--) {
2412 chip->write_buf(mtd, buf, eccsize);
2413 buf += eccsize;
2414
2415 if (chip->ecc.prepad) {
2416 chip->write_buf(mtd, oob, chip->ecc.prepad);
2417 oob += chip->ecc.prepad;
2418 }
2419
60c3bc1f 2420 chip->write_buf(mtd, oob, eccbytes);
52ff49df
DB
2421 oob += eccbytes;
2422
2423 if (chip->ecc.postpad) {
2424 chip->write_buf(mtd, oob, chip->ecc.postpad);
2425 oob += chip->ecc.postpad;
2426 }
2427 }
2428
2429 size = mtd->oobsize - (oob - chip->oob_poi);
2430 if (size)
2431 chip->write_buf(mtd, oob, size);
fdbad98d
JW
2432
2433 return 0;
52ff49df 2434}
9223a456 2435/**
7854d3f7 2436 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
8b6e50c9
BN
2437 * @mtd: mtd info structure
2438 * @chip: nand chip info structure
2439 * @buf: data buffer
1fbb938d 2440 * @oob_required: must write chip->oob_poi to OOB
45aaeff9 2441 * @page: page number to write
9223a456 2442 */
fdbad98d 2443static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
45aaeff9
BB
2444 const uint8_t *buf, int oob_required,
2445 int page)
9223a456 2446{
846031d3 2447 int i, eccsize = chip->ecc.size, ret;
f75e5097
TG
2448 int eccbytes = chip->ecc.bytes;
2449 int eccsteps = chip->ecc.steps;
4bf63fcb 2450 uint8_t *ecc_calc = chip->buffers->ecccalc;
f75e5097 2451 const uint8_t *p = buf;
9223a456 2452
7854d3f7 2453 /* Software ECC calculation */
8593fbc6
TG
2454 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2455 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
9223a456 2456
846031d3
BB
2457 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2458 chip->ecc.total);
2459 if (ret)
2460 return ret;
9223a456 2461
45aaeff9 2462 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
f75e5097 2463}
9223a456 2464
f75e5097 2465/**
7854d3f7 2466 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
8b6e50c9
BN
2467 * @mtd: mtd info structure
2468 * @chip: nand chip info structure
2469 * @buf: data buffer
1fbb938d 2470 * @oob_required: must write chip->oob_poi to OOB
45aaeff9 2471 * @page: page number to write
f75e5097 2472 */
fdbad98d 2473static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
45aaeff9
BB
2474 const uint8_t *buf, int oob_required,
2475 int page)
f75e5097 2476{
846031d3 2477 int i, eccsize = chip->ecc.size, ret;
f75e5097
TG
2478 int eccbytes = chip->ecc.bytes;
2479 int eccsteps = chip->ecc.steps;
4bf63fcb 2480 uint8_t *ecc_calc = chip->buffers->ecccalc;
f75e5097 2481 const uint8_t *p = buf;
9223a456 2482
f75e5097
TG
2483 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2484 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
29da9cea 2485 chip->write_buf(mtd, p, eccsize);
f75e5097 2486 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
9223a456
TG
2487 }
2488
846031d3
BB
2489 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2490 chip->ecc.total);
2491 if (ret)
2492 return ret;
f75e5097
TG
2493
2494 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
fdbad98d
JW
2495
2496 return 0;
9223a456
TG
2497}
2498
837a6ba4
GP
2499
2500/**
73c8aaf4 2501 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
837a6ba4
GP
2502 * @mtd: mtd info structure
2503 * @chip: nand chip info structure
d6a95080 2504 * @offset: column address of subpage within the page
837a6ba4 2505 * @data_len: data length
d6a95080 2506 * @buf: data buffer
837a6ba4 2507 * @oob_required: must write chip->oob_poi to OOB
45aaeff9 2508 * @page: page number to write
837a6ba4
GP
2509 */
2510static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2511 struct nand_chip *chip, uint32_t offset,
d6a95080 2512 uint32_t data_len, const uint8_t *buf,
45aaeff9 2513 int oob_required, int page)
837a6ba4
GP
2514{
2515 uint8_t *oob_buf = chip->oob_poi;
2516 uint8_t *ecc_calc = chip->buffers->ecccalc;
2517 int ecc_size = chip->ecc.size;
2518 int ecc_bytes = chip->ecc.bytes;
2519 int ecc_steps = chip->ecc.steps;
837a6ba4
GP
2520 uint32_t start_step = offset / ecc_size;
2521 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2522 int oob_bytes = mtd->oobsize / ecc_steps;
846031d3 2523 int step, ret;
837a6ba4
GP
2524
2525 for (step = 0; step < ecc_steps; step++) {
2526 /* configure controller for WRITE access */
2527 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2528
2529 /* write data (untouched subpages already masked by 0xFF) */
d6a95080 2530 chip->write_buf(mtd, buf, ecc_size);
837a6ba4
GP
2531
2532 /* mask ECC of un-touched subpages by padding 0xFF */
2533 if ((step < start_step) || (step > end_step))
2534 memset(ecc_calc, 0xff, ecc_bytes);
2535 else
d6a95080 2536 chip->ecc.calculate(mtd, buf, ecc_calc);
837a6ba4
GP
2537
2538 /* mask OOB of un-touched subpages by padding 0xFF */
2539 /* if oob_required, preserve OOB metadata of written subpage */
2540 if (!oob_required || (step < start_step) || (step > end_step))
2541 memset(oob_buf, 0xff, oob_bytes);
2542
d6a95080 2543 buf += ecc_size;
837a6ba4
GP
2544 ecc_calc += ecc_bytes;
2545 oob_buf += oob_bytes;
2546 }
2547
2548 /* copy calculated ECC for whole page to chip->buffer->oob */
2549 /* this include masked-value(0xFF) for unwritten subpages */
2550 ecc_calc = chip->buffers->ecccalc;
846031d3
BB
2551 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2552 chip->ecc.total);
2553 if (ret)
2554 return ret;
837a6ba4
GP
2555
2556 /* write OOB buffer to NAND device */
2557 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2558
2559 return 0;
2560}
2561
2562
61b03bd7 2563/**
7854d3f7 2564 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
8b6e50c9
BN
2565 * @mtd: mtd info structure
2566 * @chip: nand chip info structure
2567 * @buf: data buffer
1fbb938d 2568 * @oob_required: must write chip->oob_poi to OOB
45aaeff9 2569 * @page: page number to write
1da177e4 2570 *
8b6e50c9
BN
2571 * The hw generator calculates the error syndrome automatically. Therefore we
2572 * need a special oob layout and handling.
f75e5097 2573 */
fdbad98d 2574static int nand_write_page_syndrome(struct mtd_info *mtd,
1fbb938d 2575 struct nand_chip *chip,
45aaeff9
BB
2576 const uint8_t *buf, int oob_required,
2577 int page)
1da177e4 2578{
f75e5097
TG
2579 int i, eccsize = chip->ecc.size;
2580 int eccbytes = chip->ecc.bytes;
2581 int eccsteps = chip->ecc.steps;
2582 const uint8_t *p = buf;
2583 uint8_t *oob = chip->oob_poi;
1da177e4 2584
f75e5097 2585 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1da177e4 2586
f75e5097
TG
2587 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2588 chip->write_buf(mtd, p, eccsize);
61b03bd7 2589
f75e5097
TG
2590 if (chip->ecc.prepad) {
2591 chip->write_buf(mtd, oob, chip->ecc.prepad);
2592 oob += chip->ecc.prepad;
2593 }
2594
2595 chip->ecc.calculate(mtd, p, oob);
2596 chip->write_buf(mtd, oob, eccbytes);
2597 oob += eccbytes;
2598
2599 if (chip->ecc.postpad) {
2600 chip->write_buf(mtd, oob, chip->ecc.postpad);
2601 oob += chip->ecc.postpad;
1da177e4 2602 }
1da177e4 2603 }
f75e5097
TG
2604
2605 /* Calculate remaining oob bytes */
7e4178f9 2606 i = mtd->oobsize - (oob - chip->oob_poi);
f75e5097
TG
2607 if (i)
2608 chip->write_buf(mtd, oob, i);
fdbad98d
JW
2609
2610 return 0;
f75e5097
TG
2611}
2612
2613/**
956e944c 2614 * nand_write_page - [REPLACEABLE] write one page
8b6e50c9
BN
2615 * @mtd: MTD device structure
2616 * @chip: NAND chip descriptor
837a6ba4
GP
2617 * @offset: address offset within the page
2618 * @data_len: length of actual data to be written
8b6e50c9 2619 * @buf: the data to write
1fbb938d 2620 * @oob_required: must write chip->oob_poi to OOB
8b6e50c9
BN
2621 * @page: page number to write
2622 * @cached: cached programming
2623 * @raw: use _raw version of write_page
f75e5097
TG
2624 */
2625static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
837a6ba4
GP
2626 uint32_t offset, int data_len, const uint8_t *buf,
2627 int oob_required, int page, int cached, int raw)
f75e5097 2628{
837a6ba4
GP
2629 int status, subpage;
2630
2631 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2632 chip->ecc.write_subpage)
2633 subpage = offset || (data_len < mtd->writesize);
2634 else
2635 subpage = 0;
f75e5097
TG
2636
2637 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2638
956e944c 2639 if (unlikely(raw))
837a6ba4 2640 status = chip->ecc.write_page_raw(mtd, chip, buf,
45aaeff9 2641 oob_required, page);
837a6ba4
GP
2642 else if (subpage)
2643 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
45aaeff9 2644 buf, oob_required, page);
956e944c 2645 else
45aaeff9
BB
2646 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2647 page);
fdbad98d
JW
2648
2649 if (status < 0)
2650 return status;
f75e5097
TG
2651
2652 /*
7854d3f7 2653 * Cached progamming disabled for now. Not sure if it's worth the
8b6e50c9 2654 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
f75e5097
TG
2655 */
2656 cached = 0;
2657
3239a6cd 2658 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
f75e5097
TG
2659
2660 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
7bc3312b 2661 status = chip->waitfunc(mtd, chip);
f75e5097
TG
2662 /*
2663 * See if operation failed and additional status checks are
8b6e50c9 2664 * available.
f75e5097
TG
2665 */
2666 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2667 status = chip->errstat(mtd, chip, FL_WRITING, status,
2668 page);
2669
2670 if (status & NAND_STATUS_FAIL)
2671 return -EIO;
2672 } else {
2673 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
7bc3312b 2674 status = chip->waitfunc(mtd, chip);
f75e5097
TG
2675 }
2676
f75e5097 2677 return 0;
1da177e4
LT
2678}
2679
8593fbc6 2680/**
7854d3f7 2681 * nand_fill_oob - [INTERN] Transfer client buffer to oob
f722013e 2682 * @mtd: MTD device structure
8b6e50c9
BN
2683 * @oob: oob data buffer
2684 * @len: oob data write length
2685 * @ops: oob ops structure
8593fbc6 2686 */
f722013e
TAA
2687static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2688 struct mtd_oob_ops *ops)
8593fbc6 2689{
862eba51 2690 struct nand_chip *chip = mtd_to_nand(mtd);
846031d3 2691 int ret;
f722013e
TAA
2692
2693 /*
2694 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2695 * data from a previous OOB read.
2696 */
2697 memset(chip->oob_poi, 0xff, mtd->oobsize);
2698
f8ac0414 2699 switch (ops->mode) {
8593fbc6 2700
0612b9dd
BN
2701 case MTD_OPS_PLACE_OOB:
2702 case MTD_OPS_RAW:
8593fbc6
TG
2703 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2704 return oob + len;
2705
846031d3
BB
2706 case MTD_OPS_AUTO_OOB:
2707 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2708 ops->ooboffs, len);
2709 BUG_ON(ret);
2710 return oob + len;
2711
8593fbc6
TG
2712 default:
2713 BUG();
2714 }
2715 return NULL;
2716}
2717
f8ac0414 2718#define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
1da177e4
LT
2719
2720/**
7854d3f7 2721 * nand_do_write_ops - [INTERN] NAND write with ECC
8b6e50c9
BN
2722 * @mtd: MTD device structure
2723 * @to: offset to write to
2724 * @ops: oob operations description structure
1da177e4 2725 *
8b6e50c9 2726 * NAND write with ECC.
1da177e4 2727 */
8593fbc6
TG
2728static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2729 struct mtd_oob_ops *ops)
1da177e4 2730{
29072b96 2731 int chipnr, realpage, page, blockmask, column;
862eba51 2732 struct nand_chip *chip = mtd_to_nand(mtd);
8593fbc6 2733 uint32_t writelen = ops->len;
782ce79a
ML
2734
2735 uint32_t oobwritelen = ops->ooblen;
29f1058a 2736 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
782ce79a 2737
8593fbc6
TG
2738 uint8_t *oob = ops->oobbuf;
2739 uint8_t *buf = ops->datbuf;
837a6ba4 2740 int ret;
e47f3db4 2741 int oob_required = oob ? 1 : 0;
1da177e4 2742
8593fbc6 2743 ops->retlen = 0;
29072b96
TG
2744 if (!writelen)
2745 return 0;
1da177e4 2746
8b6e50c9 2747 /* Reject writes, which are not page aligned */
8593fbc6 2748 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
d0370219
BN
2749 pr_notice("%s: attempt to write non page aligned data\n",
2750 __func__);
1da177e4
LT
2751 return -EINVAL;
2752 }
2753
29072b96 2754 column = to & (mtd->writesize - 1);
1da177e4 2755
6a930961
TG
2756 chipnr = (int)(to >> chip->chip_shift);
2757 chip->select_chip(mtd, chipnr);
2758
1da177e4 2759 /* Check, if it is write protected */
b0bb6903
HS
2760 if (nand_check_wp(mtd)) {
2761 ret = -EIO;
2762 goto err_out;
2763 }
1da177e4 2764
f75e5097
TG
2765 realpage = (int)(to >> chip->page_shift);
2766 page = realpage & chip->pagemask;
2767 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2768
2769 /* Invalidate the page cache, when we write to the cached page */
537ab1bd
BN
2770 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2771 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
ace4dfee 2772 chip->pagebuf = -1;
61b03bd7 2773
782ce79a 2774 /* Don't allow multipage oob writes with offset */
b0bb6903
HS
2775 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2776 ret = -EINVAL;
2777 goto err_out;
2778 }
782ce79a 2779
f8ac0414 2780 while (1) {
29072b96 2781 int bytes = mtd->writesize;
f75e5097 2782 int cached = writelen > bytes && page != blockmask;
29072b96 2783 uint8_t *wbuf = buf;
66507c7b 2784 int use_bufpoi;
144f4c98 2785 int part_pagewr = (column || writelen < mtd->writesize);
66507c7b
KD
2786
2787 if (part_pagewr)
2788 use_bufpoi = 1;
2789 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2790 use_bufpoi = !virt_addr_valid(buf);
2791 else
2792 use_bufpoi = 0;
29072b96 2793
66507c7b
KD
2794 /* Partial page write?, or need to use bounce buffer */
2795 if (use_bufpoi) {
2796 pr_debug("%s: using write bounce buffer for buf@%p\n",
2797 __func__, buf);
29072b96 2798 cached = 0;
66507c7b
KD
2799 if (part_pagewr)
2800 bytes = min_t(int, bytes - column, writelen);
29072b96
TG
2801 chip->pagebuf = -1;
2802 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2803 memcpy(&chip->buffers->databuf[column], buf, bytes);
2804 wbuf = chip->buffers->databuf;
2805 }
1da177e4 2806
782ce79a
ML
2807 if (unlikely(oob)) {
2808 size_t len = min(oobwritelen, oobmaxlen);
f722013e 2809 oob = nand_fill_oob(mtd, oob, len, ops);
782ce79a 2810 oobwritelen -= len;
f722013e
TAA
2811 } else {
2812 /* We still need to erase leftover OOB data */
2813 memset(chip->oob_poi, 0xff, mtd->oobsize);
782ce79a 2814 }
837a6ba4
GP
2815 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2816 oob_required, page, cached,
2817 (ops->mode == MTD_OPS_RAW));
f75e5097
TG
2818 if (ret)
2819 break;
2820
2821 writelen -= bytes;
2822 if (!writelen)
2823 break;
2824
29072b96 2825 column = 0;
f75e5097
TG
2826 buf += bytes;
2827 realpage++;
2828
2829 page = realpage & chip->pagemask;
2830 /* Check, if we cross a chip boundary */
2831 if (!page) {
2832 chipnr++;
2833 chip->select_chip(mtd, -1);
2834 chip->select_chip(mtd, chipnr);
1da177e4
LT
2835 }
2836 }
8593fbc6 2837
8593fbc6 2838 ops->retlen = ops->len - writelen;
7014568b
VW
2839 if (unlikely(oob))
2840 ops->oobretlen = ops->ooblen;
b0bb6903
HS
2841
2842err_out:
2843 chip->select_chip(mtd, -1);
1da177e4
LT
2844 return ret;
2845}
2846
2af7c653
SK
2847/**
2848 * panic_nand_write - [MTD Interface] NAND write with ECC
8b6e50c9
BN
2849 * @mtd: MTD device structure
2850 * @to: offset to write to
2851 * @len: number of bytes to write
2852 * @retlen: pointer to variable to store the number of written bytes
2853 * @buf: the data to write
2af7c653
SK
2854 *
2855 * NAND write with ECC. Used when performing writes in interrupt context, this
2856 * may for example be called by mtdoops when writing an oops while in panic.
2857 */
2858static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2859 size_t *retlen, const uint8_t *buf)
2860{
862eba51 2861 struct nand_chip *chip = mtd_to_nand(mtd);
4a89ff88 2862 struct mtd_oob_ops ops;
2af7c653
SK
2863 int ret;
2864
8b6e50c9 2865 /* Wait for the device to get ready */
2af7c653
SK
2866 panic_nand_wait(mtd, chip, 400);
2867
8b6e50c9 2868 /* Grab the device */
2af7c653
SK
2869 panic_nand_get_device(chip, mtd, FL_WRITING);
2870
0ec56dc4 2871 memset(&ops, 0, sizeof(ops));
4a89ff88
BN
2872 ops.len = len;
2873 ops.datbuf = (uint8_t *)buf;
11041ae6 2874 ops.mode = MTD_OPS_PLACE_OOB;
2af7c653 2875
4a89ff88 2876 ret = nand_do_write_ops(mtd, to, &ops);
2af7c653 2877
4a89ff88 2878 *retlen = ops.retlen;
2af7c653
SK
2879 return ret;
2880}
2881
f75e5097 2882/**
8593fbc6 2883 * nand_write - [MTD Interface] NAND write with ECC
8b6e50c9
BN
2884 * @mtd: MTD device structure
2885 * @to: offset to write to
2886 * @len: number of bytes to write
2887 * @retlen: pointer to variable to store the number of written bytes
2888 * @buf: the data to write
f75e5097 2889 *
8b6e50c9 2890 * NAND write with ECC.
f75e5097 2891 */
8593fbc6
TG
2892static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2893 size_t *retlen, const uint8_t *buf)
f75e5097 2894{
4a89ff88 2895 struct mtd_oob_ops ops;
f75e5097
TG
2896 int ret;
2897
6a8214aa 2898 nand_get_device(mtd, FL_WRITING);
0ec56dc4 2899 memset(&ops, 0, sizeof(ops));
4a89ff88
BN
2900 ops.len = len;
2901 ops.datbuf = (uint8_t *)buf;
11041ae6 2902 ops.mode = MTD_OPS_PLACE_OOB;
4a89ff88 2903 ret = nand_do_write_ops(mtd, to, &ops);
4a89ff88 2904 *retlen = ops.retlen;
f75e5097 2905 nand_release_device(mtd);
8593fbc6 2906 return ret;
f75e5097 2907}
7314e9e7 2908
1da177e4 2909/**
8593fbc6 2910 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
8b6e50c9
BN
2911 * @mtd: MTD device structure
2912 * @to: offset to write to
2913 * @ops: oob operation description structure
1da177e4 2914 *
8b6e50c9 2915 * NAND write out-of-band.
1da177e4 2916 */
8593fbc6
TG
2917static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2918 struct mtd_oob_ops *ops)
1da177e4 2919{
03736155 2920 int chipnr, page, status, len;
862eba51 2921 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 2922
289c0522 2923 pr_debug("%s: to = 0x%08x, len = %i\n",
20d8e248 2924 __func__, (unsigned int)to, (int)ops->ooblen);
1da177e4 2925
29f1058a 2926 len = mtd_oobavail(mtd, ops);
03736155 2927
1da177e4 2928 /* Do not allow write past end of page */
03736155 2929 if ((ops->ooboffs + ops->ooblen) > len) {
289c0522
BN
2930 pr_debug("%s: attempt to write past end of page\n",
2931 __func__);
1da177e4
LT
2932 return -EINVAL;
2933 }
2934
03736155 2935 if (unlikely(ops->ooboffs >= len)) {
289c0522
BN
2936 pr_debug("%s: attempt to start write outside oob\n",
2937 __func__);
03736155
AH
2938 return -EINVAL;
2939 }
2940
775adc3d 2941 /* Do not allow write past end of device */
03736155
AH
2942 if (unlikely(to >= mtd->size ||
2943 ops->ooboffs + ops->ooblen >
2944 ((mtd->size >> chip->page_shift) -
2945 (to >> chip->page_shift)) * len)) {
289c0522
BN
2946 pr_debug("%s: attempt to write beyond end of device\n",
2947 __func__);
03736155
AH
2948 return -EINVAL;
2949 }
2950
7314e9e7 2951 chipnr = (int)(to >> chip->chip_shift);
7314e9e7
TG
2952
2953 /*
2954 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2955 * of my DiskOnChip 2000 test units) will clear the whole data page too
2956 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2957 * it in the doc2000 driver in August 1999. dwmw2.
2958 */
73f907fd
BB
2959 nand_reset(chip, chipnr);
2960
2961 chip->select_chip(mtd, chipnr);
2962
2963 /* Shift to get page */
2964 page = (int)(to >> chip->page_shift);
1da177e4
LT
2965
2966 /* Check, if it is write protected */
b0bb6903
HS
2967 if (nand_check_wp(mtd)) {
2968 chip->select_chip(mtd, -1);
8593fbc6 2969 return -EROFS;
b0bb6903 2970 }
61b03bd7 2971
1da177e4 2972 /* Invalidate the page cache, if we write to the cached page */
ace4dfee
TG
2973 if (page == chip->pagebuf)
2974 chip->pagebuf = -1;
1da177e4 2975
f722013e 2976 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
9ce244b3 2977
0612b9dd 2978 if (ops->mode == MTD_OPS_RAW)
9ce244b3
BN
2979 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2980 else
2981 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
1da177e4 2982
b0bb6903
HS
2983 chip->select_chip(mtd, -1);
2984
7bc3312b
TG
2985 if (status)
2986 return status;
1da177e4 2987
7014568b 2988 ops->oobretlen = ops->ooblen;
1da177e4 2989
7bc3312b 2990 return 0;
8593fbc6
TG
2991}
2992
2993/**
2994 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
8b6e50c9
BN
2995 * @mtd: MTD device structure
2996 * @to: offset to write to
2997 * @ops: oob operation description structure
8593fbc6
TG
2998 */
2999static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3000 struct mtd_oob_ops *ops)
3001{
8593fbc6
TG
3002 int ret = -ENOTSUPP;
3003
3004 ops->retlen = 0;
3005
3006 /* Do not allow writes past end of device */
7014568b 3007 if (ops->datbuf && (to + ops->len) > mtd->size) {
289c0522
BN
3008 pr_debug("%s: attempt to write beyond end of device\n",
3009 __func__);
8593fbc6
TG
3010 return -EINVAL;
3011 }
3012
6a8214aa 3013 nand_get_device(mtd, FL_WRITING);
8593fbc6 3014
f8ac0414 3015 switch (ops->mode) {
0612b9dd
BN
3016 case MTD_OPS_PLACE_OOB:
3017 case MTD_OPS_AUTO_OOB:
3018 case MTD_OPS_RAW:
8593fbc6
TG
3019 break;
3020
3021 default:
3022 goto out;
3023 }
3024
3025 if (!ops->datbuf)
3026 ret = nand_do_write_oob(mtd, to, ops);
3027 else
3028 ret = nand_do_write_ops(mtd, to, ops);
3029
7351d3a5 3030out:
1da177e4 3031 nand_release_device(mtd);
1da177e4
LT
3032 return ret;
3033}
3034
1da177e4 3035/**
49c50b97 3036 * single_erase - [GENERIC] NAND standard block erase command function
8b6e50c9
BN
3037 * @mtd: MTD device structure
3038 * @page: the page address of the block which will be erased
1da177e4 3039 *
49c50b97 3040 * Standard erase command for NAND chips. Returns NAND status.
1da177e4 3041 */
49c50b97 3042static int single_erase(struct mtd_info *mtd, int page)
1da177e4 3043{
862eba51 3044 struct nand_chip *chip = mtd_to_nand(mtd);
1da177e4 3045 /* Send commands to erase a block */
ace4dfee
TG
3046 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
3047 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
49c50b97
BN
3048
3049 return chip->waitfunc(mtd, chip);
1da177e4
LT
3050}
3051
1da177e4
LT
3052/**
3053 * nand_erase - [MTD Interface] erase block(s)
8b6e50c9
BN
3054 * @mtd: MTD device structure
3055 * @instr: erase instruction
1da177e4 3056 *
8b6e50c9 3057 * Erase one ore more blocks.
1da177e4 3058 */
e0c7d767 3059static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
1da177e4 3060{
e0c7d767 3061 return nand_erase_nand(mtd, instr, 0);
1da177e4 3062}
61b03bd7 3063
1da177e4 3064/**
7854d3f7 3065 * nand_erase_nand - [INTERN] erase block(s)
8b6e50c9
BN
3066 * @mtd: MTD device structure
3067 * @instr: erase instruction
3068 * @allowbbt: allow erasing the bbt area
1da177e4 3069 *
8b6e50c9 3070 * Erase one ore more blocks.
1da177e4 3071 */
ace4dfee
TG
3072int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3073 int allowbbt)
1da177e4 3074{
69423d99 3075 int page, status, pages_per_block, ret, chipnr;
862eba51 3076 struct nand_chip *chip = mtd_to_nand(mtd);
69423d99 3077 loff_t len;
1da177e4 3078
289c0522
BN
3079 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3080 __func__, (unsigned long long)instr->addr,
3081 (unsigned long long)instr->len);
1da177e4 3082
6fe5a6ac 3083 if (check_offs_len(mtd, instr->addr, instr->len))
1da177e4 3084 return -EINVAL;
1da177e4 3085
1da177e4 3086 /* Grab the lock and see if the device is available */
6a8214aa 3087 nand_get_device(mtd, FL_ERASING);
1da177e4
LT
3088
3089 /* Shift to get first page */
ace4dfee
TG
3090 page = (int)(instr->addr >> chip->page_shift);
3091 chipnr = (int)(instr->addr >> chip->chip_shift);
1da177e4
LT
3092
3093 /* Calculate pages in each block */
ace4dfee 3094 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
1da177e4
LT
3095
3096 /* Select the NAND device */
ace4dfee 3097 chip->select_chip(mtd, chipnr);
1da177e4 3098
1da177e4
LT
3099 /* Check, if it is write protected */
3100 if (nand_check_wp(mtd)) {
289c0522
BN
3101 pr_debug("%s: device is write protected!\n",
3102 __func__);
1da177e4
LT
3103 instr->state = MTD_ERASE_FAILED;
3104 goto erase_exit;
3105 }
3106
3107 /* Loop through the pages */
3108 len = instr->len;
3109
3110 instr->state = MTD_ERASING;
3111
3112 while (len) {
12183a20 3113 /* Check if we have a bad block, we do not erase bad blocks! */
ace4dfee 3114 if (nand_block_checkbad(mtd, ((loff_t) page) <<
9f3e0429 3115 chip->page_shift, allowbbt)) {
d0370219
BN
3116 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3117 __func__, page);
1da177e4
LT
3118 instr->state = MTD_ERASE_FAILED;
3119 goto erase_exit;
3120 }
61b03bd7 3121
ace4dfee
TG
3122 /*
3123 * Invalidate the page cache, if we erase the block which
8b6e50c9 3124 * contains the current cached page.
ace4dfee
TG
3125 */
3126 if (page <= chip->pagebuf && chip->pagebuf <
3127 (page + pages_per_block))
3128 chip->pagebuf = -1;
1da177e4 3129
49c50b97 3130 status = chip->erase(mtd, page & chip->pagemask);
1da177e4 3131
ace4dfee
TG
3132 /*
3133 * See if operation failed and additional status checks are
3134 * available
3135 */
3136 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
3137 status = chip->errstat(mtd, chip, FL_ERASING,
3138 status, page);
068e3c0a 3139
1da177e4 3140 /* See if block erase succeeded */
a4ab4c5d 3141 if (status & NAND_STATUS_FAIL) {
289c0522
BN
3142 pr_debug("%s: failed erase, page 0x%08x\n",
3143 __func__, page);
1da177e4 3144 instr->state = MTD_ERASE_FAILED;
69423d99
AH
3145 instr->fail_addr =
3146 ((loff_t)page << chip->page_shift);
1da177e4
LT
3147 goto erase_exit;
3148 }
30f464b7 3149
1da177e4 3150 /* Increment page address and decrement length */
daae74ca 3151 len -= (1ULL << chip->phys_erase_shift);
1da177e4
LT
3152 page += pages_per_block;
3153
3154 /* Check, if we cross a chip boundary */
ace4dfee 3155 if (len && !(page & chip->pagemask)) {
1da177e4 3156 chipnr++;
ace4dfee
TG
3157 chip->select_chip(mtd, -1);
3158 chip->select_chip(mtd, chipnr);
1da177e4
LT
3159 }
3160 }
3161 instr->state = MTD_ERASE_DONE;
3162
7351d3a5 3163erase_exit:
1da177e4
LT
3164
3165 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
1da177e4
LT
3166
3167 /* Deselect and wake up anyone waiting on the device */
b0bb6903 3168 chip->select_chip(mtd, -1);
1da177e4
LT
3169 nand_release_device(mtd);
3170
49defc01
DW
3171 /* Do call back function */
3172 if (!ret)
3173 mtd_erase_callback(instr);
3174
1da177e4
LT
3175 /* Return more or less happy */
3176 return ret;
3177}
3178
3179/**
3180 * nand_sync - [MTD Interface] sync
8b6e50c9 3181 * @mtd: MTD device structure
1da177e4 3182 *
8b6e50c9 3183 * Sync is actually a wait for chip ready function.
1da177e4 3184 */
e0c7d767 3185static void nand_sync(struct mtd_info *mtd)
1da177e4 3186{
289c0522 3187 pr_debug("%s: called\n", __func__);
1da177e4
LT
3188
3189 /* Grab the lock and see if the device is available */
6a8214aa 3190 nand_get_device(mtd, FL_SYNCING);
1da177e4 3191 /* Release it and go back */
e0c7d767 3192 nand_release_device(mtd);
1da177e4
LT
3193}
3194
1da177e4 3195/**
ace4dfee 3196 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
8b6e50c9
BN
3197 * @mtd: MTD device structure
3198 * @offs: offset relative to mtd start
1da177e4 3199 */
ace4dfee 3200static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
1da177e4 3201{
9f3e0429
AT
3202 struct nand_chip *chip = mtd_to_nand(mtd);
3203 int chipnr = (int)(offs >> chip->chip_shift);
3204 int ret;
3205
3206 /* Select the NAND device */
3207 nand_get_device(mtd, FL_READING);
3208 chip->select_chip(mtd, chipnr);
3209
3210 ret = nand_block_checkbad(mtd, offs, 0);
3211
3212 chip->select_chip(mtd, -1);
3213 nand_release_device(mtd);
3214
3215 return ret;
1da177e4
LT
3216}
3217
3218/**
ace4dfee 3219 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
8b6e50c9
BN
3220 * @mtd: MTD device structure
3221 * @ofs: offset relative to mtd start
1da177e4 3222 */
e0c7d767 3223static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
1da177e4 3224{
1da177e4
LT
3225 int ret;
3226
f8ac0414
FF
3227 ret = nand_block_isbad(mtd, ofs);
3228 if (ret) {
8b6e50c9 3229 /* If it was bad already, return success and do nothing */
1da177e4
LT
3230 if (ret > 0)
3231 return 0;
e0c7d767
DW
3232 return ret;
3233 }
1da177e4 3234
5a0edb25 3235 return nand_block_markbad_lowlevel(mtd, ofs);
1da177e4
LT
3236}
3237
7db03ecc
HS
3238/**
3239 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3240 * @mtd: MTD device structure
3241 * @chip: nand chip info structure
3242 * @addr: feature address.
3243 * @subfeature_param: the subfeature parameters, a four bytes array.
3244 */
3245static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3246 int addr, uint8_t *subfeature_param)
3247{
3248 int status;
05f78359 3249 int i;
7db03ecc 3250
d914c932
DM
3251 if (!chip->onfi_version ||
3252 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3253 & ONFI_OPT_CMD_SET_GET_FEATURES))
7db03ecc
HS
3254 return -EINVAL;
3255
3256 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
05f78359
UKK
3257 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3258 chip->write_byte(mtd, subfeature_param[i]);
3259
7db03ecc
HS
3260 status = chip->waitfunc(mtd, chip);
3261 if (status & NAND_STATUS_FAIL)
3262 return -EIO;
3263 return 0;
3264}
3265
3266/**
3267 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3268 * @mtd: MTD device structure
3269 * @chip: nand chip info structure
3270 * @addr: feature address.
3271 * @subfeature_param: the subfeature parameters, a four bytes array.
3272 */
3273static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3274 int addr, uint8_t *subfeature_param)
3275{
05f78359
UKK
3276 int i;
3277
d914c932
DM
3278 if (!chip->onfi_version ||
3279 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3280 & ONFI_OPT_CMD_SET_GET_FEATURES))
7db03ecc
HS
3281 return -EINVAL;
3282
7db03ecc 3283 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
05f78359
UKK
3284 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3285 *subfeature_param++ = chip->read_byte(mtd);
7db03ecc
HS
3286 return 0;
3287}
3288
962034f4
VW
3289/**
3290 * nand_suspend - [MTD Interface] Suspend the NAND flash
8b6e50c9 3291 * @mtd: MTD device structure
962034f4
VW
3292 */
3293static int nand_suspend(struct mtd_info *mtd)
3294{
6a8214aa 3295 return nand_get_device(mtd, FL_PM_SUSPENDED);
962034f4
VW
3296}
3297
3298/**
3299 * nand_resume - [MTD Interface] Resume the NAND flash
8b6e50c9 3300 * @mtd: MTD device structure
962034f4
VW
3301 */
3302static void nand_resume(struct mtd_info *mtd)
3303{
862eba51 3304 struct nand_chip *chip = mtd_to_nand(mtd);
962034f4 3305
ace4dfee 3306 if (chip->state == FL_PM_SUSPENDED)
962034f4
VW
3307 nand_release_device(mtd);
3308 else
d0370219
BN
3309 pr_err("%s called for a chip which is not in suspended state\n",
3310 __func__);
962034f4
VW
3311}
3312
72ea4036
SB
3313/**
3314 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3315 * prevent further operations
3316 * @mtd: MTD device structure
3317 */
3318static void nand_shutdown(struct mtd_info *mtd)
3319{
9ca641b0 3320 nand_get_device(mtd, FL_PM_SUSPENDED);
72ea4036
SB
3321}
3322
8b6e50c9 3323/* Set default functions */
ace4dfee 3324static void nand_set_defaults(struct nand_chip *chip, int busw)
7aa65bfd 3325{
1da177e4 3326 /* check for proper chip_delay setup, set 20us if not */
ace4dfee
TG
3327 if (!chip->chip_delay)
3328 chip->chip_delay = 20;
1da177e4
LT
3329
3330 /* check, if a user supplied command function given */
ace4dfee
TG
3331 if (chip->cmdfunc == NULL)
3332 chip->cmdfunc = nand_command;
1da177e4
LT
3333
3334 /* check, if a user supplied wait function given */
ace4dfee
TG
3335 if (chip->waitfunc == NULL)
3336 chip->waitfunc = nand_wait;
3337
3338 if (!chip->select_chip)
3339 chip->select_chip = nand_select_chip;
68e80780 3340
4204cccd
HS
3341 /* set for ONFI nand */
3342 if (!chip->onfi_set_features)
3343 chip->onfi_set_features = nand_onfi_set_features;
3344 if (!chip->onfi_get_features)
3345 chip->onfi_get_features = nand_onfi_get_features;
3346
68e80780
BN
3347 /* If called twice, pointers that depend on busw may need to be reset */
3348 if (!chip->read_byte || chip->read_byte == nand_read_byte)
ace4dfee
TG
3349 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3350 if (!chip->read_word)
3351 chip->read_word = nand_read_word;
3352 if (!chip->block_bad)
3353 chip->block_bad = nand_block_bad;
3354 if (!chip->block_markbad)
3355 chip->block_markbad = nand_default_block_markbad;
68e80780 3356 if (!chip->write_buf || chip->write_buf == nand_write_buf)
ace4dfee 3357 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
05f78359
UKK
3358 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3359 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
68e80780 3360 if (!chip->read_buf || chip->read_buf == nand_read_buf)
ace4dfee 3361 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
ace4dfee
TG
3362 if (!chip->scan_bbt)
3363 chip->scan_bbt = nand_default_bbt;
f75e5097
TG
3364
3365 if (!chip->controller) {
3366 chip->controller = &chip->hwcontrol;
d45bc58d 3367 nand_hw_control_init(chip->controller);
f75e5097
TG
3368 }
3369
7aa65bfd
TG
3370}
3371
8b6e50c9 3372/* Sanitize ONFI strings so we can safely print them */
d1e1f4e4
FF
3373static void sanitize_string(uint8_t *s, size_t len)
3374{
3375 ssize_t i;
3376
8b6e50c9 3377 /* Null terminate */
d1e1f4e4
FF
3378 s[len - 1] = 0;
3379
8b6e50c9 3380 /* Remove non printable chars */
d1e1f4e4
FF
3381 for (i = 0; i < len - 1; i++) {
3382 if (s[i] < ' ' || s[i] > 127)
3383 s[i] = '?';
3384 }
3385
8b6e50c9 3386 /* Remove trailing spaces */
d1e1f4e4
FF
3387 strim(s);
3388}
3389
3390static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3391{
3392 int i;
3393 while (len--) {
3394 crc ^= *p++ << 8;
3395 for (i = 0; i < 8; i++)
3396 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3397 }
3398
3399 return crc;
3400}
3401
6dcbe0cd
HS
3402/* Parse the Extended Parameter Page. */
3403static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3404 struct nand_chip *chip, struct nand_onfi_params *p)
3405{
3406 struct onfi_ext_param_page *ep;
3407 struct onfi_ext_section *s;
3408 struct onfi_ext_ecc_info *ecc;
3409 uint8_t *cursor;
3410 int ret = -EINVAL;
3411 int len;
3412 int i;
3413
3414 len = le16_to_cpu(p->ext_param_page_length) * 16;
3415 ep = kmalloc(len, GFP_KERNEL);
5cb13271
BN
3416 if (!ep)
3417 return -ENOMEM;
6dcbe0cd
HS
3418
3419 /* Send our own NAND_CMD_PARAM. */
3420 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3421
3422 /* Use the Change Read Column command to skip the ONFI param pages. */
3423 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3424 sizeof(*p) * p->num_of_param_pages , -1);
3425
3426 /* Read out the Extended Parameter Page. */
3427 chip->read_buf(mtd, (uint8_t *)ep, len);
3428 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3429 != le16_to_cpu(ep->crc))) {
3430 pr_debug("fail in the CRC.\n");
3431 goto ext_out;
3432 }
3433
3434 /*
3435 * Check the signature.
3436 * Do not strictly follow the ONFI spec, maybe changed in future.
3437 */
3438 if (strncmp(ep->sig, "EPPS", 4)) {
3439 pr_debug("The signature is invalid.\n");
3440 goto ext_out;
3441 }
3442
3443 /* find the ECC section. */
3444 cursor = (uint8_t *)(ep + 1);
3445 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3446 s = ep->sections + i;
3447 if (s->type == ONFI_SECTION_TYPE_2)
3448 break;
3449 cursor += s->length * 16;
3450 }
3451 if (i == ONFI_EXT_SECTION_MAX) {
3452 pr_debug("We can not find the ECC section.\n");
3453 goto ext_out;
3454 }
3455
3456 /* get the info we want. */
3457 ecc = (struct onfi_ext_ecc_info *)cursor;
3458
4ae7d228
BN
3459 if (!ecc->codeword_size) {
3460 pr_debug("Invalid codeword size\n");
3461 goto ext_out;
6dcbe0cd
HS
3462 }
3463
4ae7d228
BN
3464 chip->ecc_strength_ds = ecc->ecc_bits;
3465 chip->ecc_step_ds = 1 << ecc->codeword_size;
5cb13271 3466 ret = 0;
6dcbe0cd
HS
3467
3468ext_out:
3469 kfree(ep);
3470 return ret;
3471}
3472
8429bb39
BN
3473static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3474{
862eba51 3475 struct nand_chip *chip = mtd_to_nand(mtd);
8429bb39
BN
3476 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3477
3478 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3479 feature);
3480}
3481
3482/*
3483 * Configure chip properties from Micron vendor-specific ONFI table
3484 */
3485static void nand_onfi_detect_micron(struct nand_chip *chip,
3486 struct nand_onfi_params *p)
3487{
3488 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3489
3490 if (le16_to_cpu(p->vendor_revision) < 1)
3491 return;
3492
3493 chip->read_retries = micron->read_retry_options;
3494 chip->setup_read_retry = nand_setup_read_retry_micron;
3495}
3496
6fb277ba 3497/*
8b6e50c9 3498 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
6fb277ba
FF
3499 */
3500static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
08c248fb 3501 int *busw)
6fb277ba
FF
3502{
3503 struct nand_onfi_params *p = &chip->onfi_params;
bd9c6e99 3504 int i, j;
6fb277ba
FF
3505 int val;
3506
7854d3f7 3507 /* Try ONFI for unknown chip or LP */
6fb277ba
FF
3508 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3509 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3510 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3511 return 0;
3512
6fb277ba
FF
3513 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3514 for (i = 0; i < 3; i++) {
bd9c6e99
BN
3515 for (j = 0; j < sizeof(*p); j++)
3516 ((uint8_t *)p)[j] = chip->read_byte(mtd);
6fb277ba
FF
3517 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3518 le16_to_cpu(p->crc)) {
6fb277ba
FF
3519 break;
3520 }
3521 }
3522
c7f23a70
BN
3523 if (i == 3) {
3524 pr_err("Could not find valid ONFI parameter page; aborting\n");
6fb277ba 3525 return 0;
c7f23a70 3526 }
6fb277ba 3527
8b6e50c9 3528 /* Check version */
6fb277ba 3529 val = le16_to_cpu(p->revision);
b7b1a29d
BN
3530 if (val & (1 << 5))
3531 chip->onfi_version = 23;
3532 else if (val & (1 << 4))
6fb277ba
FF
3533 chip->onfi_version = 22;
3534 else if (val & (1 << 3))
3535 chip->onfi_version = 21;
3536 else if (val & (1 << 2))
3537 chip->onfi_version = 20;
b7b1a29d 3538 else if (val & (1 << 1))
6fb277ba 3539 chip->onfi_version = 10;
b7b1a29d
BN
3540
3541 if (!chip->onfi_version) {
20171642 3542 pr_info("unsupported ONFI version: %d\n", val);
b7b1a29d
BN
3543 return 0;
3544 }
6fb277ba
FF
3545
3546 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3547 sanitize_string(p->model, sizeof(p->model));
3548 if (!mtd->name)
3549 mtd->name = p->model;
4355b70c 3550
6fb277ba 3551 mtd->writesize = le32_to_cpu(p->byte_per_page);
4355b70c
BN
3552
3553 /*
3554 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3555 * (don't ask me who thought of this...). MTD assumes that these
3556 * dimensions will be power-of-2, so just truncate the remaining area.
3557 */
3558 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3559 mtd->erasesize *= mtd->writesize;
3560
6fb277ba 3561 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4355b70c
BN
3562
3563 /* See erasesize comment */
3564 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
63795755 3565 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
13fbd179 3566 chip->bits_per_cell = p->bits_per_cell;
e2985fc1
HS
3567
3568 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
08c248fb 3569 *busw = NAND_BUSWIDTH_16;
e2985fc1
HS
3570 else
3571 *busw = 0;
6fb277ba 3572
10c86bab
HS
3573 if (p->ecc_bits != 0xff) {
3574 chip->ecc_strength_ds = p->ecc_bits;
3575 chip->ecc_step_ds = 512;
6dcbe0cd
HS
3576 } else if (chip->onfi_version >= 21 &&
3577 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3578
3579 /*
3580 * The nand_flash_detect_ext_param_page() uses the
3581 * Change Read Column command which maybe not supported
3582 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3583 * now. We do not replace user supplied command function.
3584 */
3585 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3586 chip->cmdfunc = nand_command_lp;
3587
3588 /* The Extended Parameter Page is supported since ONFI 2.1. */
3589 if (nand_flash_detect_ext_param_page(mtd, chip, p))
c7f23a70
BN
3590 pr_warn("Failed to detect ONFI extended param page\n");
3591 } else {
3592 pr_warn("Could not retrieve ONFI ECC requirements\n");
10c86bab
HS
3593 }
3594
8429bb39
BN
3595 if (p->jedec_id == NAND_MFR_MICRON)
3596 nand_onfi_detect_micron(chip, p);
3597
6fb277ba
FF
3598 return 1;
3599}
3600
91361818
HS
3601/*
3602 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3603 */
3604static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3605 int *busw)
3606{
3607 struct nand_jedec_params *p = &chip->jedec_params;
3608 struct jedec_ecc_info *ecc;
3609 int val;
3610 int i, j;
3611
3612 /* Try JEDEC for unknown chip or LP */
3613 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3614 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3615 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3616 chip->read_byte(mtd) != 'C')
3617 return 0;
3618
3619 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3620 for (i = 0; i < 3; i++) {
3621 for (j = 0; j < sizeof(*p); j++)
3622 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3623
3624 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3625 le16_to_cpu(p->crc))
3626 break;
3627 }
3628
3629 if (i == 3) {
3630 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3631 return 0;
3632 }
3633
3634 /* Check version */
3635 val = le16_to_cpu(p->revision);
3636 if (val & (1 << 2))
3637 chip->jedec_version = 10;
3638 else if (val & (1 << 1))
3639 chip->jedec_version = 1; /* vendor specific version */
3640
3641 if (!chip->jedec_version) {
3642 pr_info("unsupported JEDEC version: %d\n", val);
3643 return 0;
3644 }
3645
3646 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3647 sanitize_string(p->model, sizeof(p->model));
3648 if (!mtd->name)
3649 mtd->name = p->model;
3650
3651 mtd->writesize = le32_to_cpu(p->byte_per_page);
3652
3653 /* Please reference to the comment for nand_flash_detect_onfi. */
3654 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3655 mtd->erasesize *= mtd->writesize;
3656
3657 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3658
3659 /* Please reference to the comment for nand_flash_detect_onfi. */
3660 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3661 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3662 chip->bits_per_cell = p->bits_per_cell;
3663
3664 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3665 *busw = NAND_BUSWIDTH_16;
3666 else
3667 *busw = 0;
3668
3669 /* ECC info */
3670 ecc = &p->ecc_info[0];
3671
3672 if (ecc->codeword_size >= 9) {
3673 chip->ecc_strength_ds = ecc->ecc_bits;
3674 chip->ecc_step_ds = 1 << ecc->codeword_size;
3675 } else {
3676 pr_warn("Invalid codeword size\n");
3677 }
3678
3679 return 1;
3680}
3681
e3b88bd6
BN
3682/*
3683 * nand_id_has_period - Check if an ID string has a given wraparound period
3684 * @id_data: the ID string
3685 * @arrlen: the length of the @id_data array
3686 * @period: the period of repitition
3687 *
3688 * Check if an ID string is repeated within a given sequence of bytes at
3689 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
d4d4f1bf 3690 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
e3b88bd6
BN
3691 * if the repetition has a period of @period; otherwise, returns zero.
3692 */
3693static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3694{
3695 int i, j;
3696 for (i = 0; i < period; i++)
3697 for (j = i + period; j < arrlen; j += period)
3698 if (id_data[i] != id_data[j])
3699 return 0;
3700 return 1;
3701}
3702
3703/*
3704 * nand_id_len - Get the length of an ID string returned by CMD_READID
3705 * @id_data: the ID string
3706 * @arrlen: the length of the @id_data array
3707
3708 * Returns the length of the ID string, according to known wraparound/trailing
3709 * zero patterns. If no pattern exists, returns the length of the array.
3710 */
3711static int nand_id_len(u8 *id_data, int arrlen)
3712{
3713 int last_nonzero, period;
3714
3715 /* Find last non-zero byte */
3716 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3717 if (id_data[last_nonzero])
3718 break;
3719
3720 /* All zeros */
3721 if (last_nonzero < 0)
3722 return 0;
3723
3724 /* Calculate wraparound period */
3725 for (period = 1; period < arrlen; period++)
3726 if (nand_id_has_period(id_data, arrlen, period))
3727 break;
3728
3729 /* There's a repeated pattern */
3730 if (period < arrlen)
3731 return period;
3732
3733 /* There are trailing zeros */
3734 if (last_nonzero < arrlen - 1)
3735 return last_nonzero + 1;
3736
3737 /* No pattern detected */
3738 return arrlen;
3739}
3740
7db906b7
HS
3741/* Extract the bits of per cell from the 3rd byte of the extended ID */
3742static int nand_get_bits_per_cell(u8 cellinfo)
3743{
3744 int bits;
3745
3746 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3747 bits >>= NAND_CI_CELLTYPE_SHIFT;
3748 return bits + 1;
3749}
3750
fc09bbc0
BN
3751/*
3752 * Many new NAND share similar device ID codes, which represent the size of the
3753 * chip. The rest of the parameters must be decoded according to generic or
3754 * manufacturer-specific "extended ID" decoding patterns.
3755 */
3756static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3757 u8 id_data[8], int *busw)
3758{
e3b88bd6 3759 int extid, id_len;
fc09bbc0 3760 /* The 3rd id byte holds MLC / multichip data */
7db906b7 3761 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
fc09bbc0
BN
3762 /* The 4th id byte is the important one */
3763 extid = id_data[3];
3764
e3b88bd6
BN
3765 id_len = nand_id_len(id_data, 8);
3766
fc09bbc0
BN
3767 /*
3768 * Field definitions are in the following datasheets:
3769 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
af451af4 3770 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
73ca392f 3771 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
fc09bbc0 3772 *
af451af4
BN
3773 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3774 * ID to decide what to do.
fc09bbc0 3775 */
af451af4 3776 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
1d0ed69d 3777 !nand_is_slc(chip) && id_data[5] != 0x00) {
fc09bbc0
BN
3778 /* Calc pagesize */
3779 mtd->writesize = 2048 << (extid & 0x03);
3780 extid >>= 2;
3781 /* Calc oobsize */
e2d3a35e 3782 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
fc09bbc0
BN
3783 case 1:
3784 mtd->oobsize = 128;
3785 break;
3786 case 2:
3787 mtd->oobsize = 218;
3788 break;
3789 case 3:
3790 mtd->oobsize = 400;
3791 break;
e2d3a35e 3792 case 4:
fc09bbc0
BN
3793 mtd->oobsize = 436;
3794 break;
e2d3a35e
BN
3795 case 5:
3796 mtd->oobsize = 512;
3797 break;
3798 case 6:
e2d3a35e
BN
3799 mtd->oobsize = 640;
3800 break;
94d04e82
HS
3801 case 7:
3802 default: /* Other cases are "reserved" (unknown) */
3803 mtd->oobsize = 1024;
3804 break;
fc09bbc0
BN
3805 }
3806 extid >>= 2;
3807 /* Calc blocksize */
3808 mtd->erasesize = (128 * 1024) <<
3809 (((extid >> 1) & 0x04) | (extid & 0x03));
3810 *busw = 0;
73ca392f 3811 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
1d0ed69d 3812 !nand_is_slc(chip)) {
73ca392f
BN
3813 unsigned int tmp;
3814
3815 /* Calc pagesize */
3816 mtd->writesize = 2048 << (extid & 0x03);
3817 extid >>= 2;
3818 /* Calc oobsize */
3819 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3820 case 0:
3821 mtd->oobsize = 128;
3822 break;
3823 case 1:
3824 mtd->oobsize = 224;
3825 break;
3826 case 2:
3827 mtd->oobsize = 448;
3828 break;
3829 case 3:
3830 mtd->oobsize = 64;
3831 break;
3832 case 4:
3833 mtd->oobsize = 32;
3834 break;
3835 case 5:
3836 mtd->oobsize = 16;
3837 break;
3838 default:
3839 mtd->oobsize = 640;
3840 break;
3841 }
3842 extid >>= 2;
3843 /* Calc blocksize */
3844 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3845 if (tmp < 0x03)
3846 mtd->erasesize = (128 * 1024) << tmp;
3847 else if (tmp == 0x03)
3848 mtd->erasesize = 768 * 1024;
3849 else
3850 mtd->erasesize = (64 * 1024) << tmp;
3851 *busw = 0;
fc09bbc0
BN
3852 } else {
3853 /* Calc pagesize */
3854 mtd->writesize = 1024 << (extid & 0x03);
3855 extid >>= 2;
3856 /* Calc oobsize */
3857 mtd->oobsize = (8 << (extid & 0x01)) *
3858 (mtd->writesize >> 9);
3859 extid >>= 2;
3860 /* Calc blocksize. Blocksize is multiples of 64KiB */
3861 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3862 extid >>= 2;
3863 /* Get buswidth information */
3864 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
60c67382
BN
3865
3866 /*
3867 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3868 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3869 * follows:
3870 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3871 * 110b -> 24nm
3872 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3873 */
3874 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
1d0ed69d 3875 nand_is_slc(chip) &&
60c67382
BN
3876 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3877 !(id_data[4] & 0x80) /* !BENAND */) {
3878 mtd->oobsize = 32 * mtd->writesize >> 9;
3879 }
3880
fc09bbc0
BN
3881 }
3882}
3883
f23a481c
BN
3884/*
3885 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3886 * decodes a matching ID table entry and assigns the MTD size parameters for
3887 * the chip.
3888 */
3889static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3890 struct nand_flash_dev *type, u8 id_data[8],
3891 int *busw)
3892{
3893 int maf_id = id_data[0];
3894
3895 mtd->erasesize = type->erasesize;
3896 mtd->writesize = type->pagesize;
3897 mtd->oobsize = mtd->writesize / 32;
3898 *busw = type->options & NAND_BUSWIDTH_16;
3899
1c195e90
HS
3900 /* All legacy ID NAND are small-page, SLC */
3901 chip->bits_per_cell = 1;
3902
f23a481c
BN
3903 /*
3904 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3905 * some Spansion chips have erasesize that conflicts with size
3906 * listed in nand_ids table.
3907 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3908 */
3909 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3910 && id_data[6] == 0x00 && id_data[7] == 0x00
3911 && mtd->writesize == 512) {
3912 mtd->erasesize = 128 * 1024;
3913 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3914 }
3915}
3916
7e74c2d7
BN
3917/*
3918 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3919 * heuristic patterns using various detected parameters (e.g., manufacturer,
3920 * page size, cell-type information).
3921 */
3922static void nand_decode_bbm_options(struct mtd_info *mtd,
3923 struct nand_chip *chip, u8 id_data[8])
3924{
3925 int maf_id = id_data[0];
3926
3927 /* Set the bad block position */
3928 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3929 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3930 else
3931 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3932
3933 /*
3934 * Bad block marker is stored in the last page of each block on Samsung
3935 * and Hynix MLC devices; stored in first two pages of each block on
3936 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3937 * AMD/Spansion, and Macronix. All others scan only the first page.
3938 */
1d0ed69d 3939 if (!nand_is_slc(chip) &&
7e74c2d7
BN
3940 (maf_id == NAND_MFR_SAMSUNG ||
3941 maf_id == NAND_MFR_HYNIX))
3942 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
1d0ed69d 3943 else if ((nand_is_slc(chip) &&
7e74c2d7
BN
3944 (maf_id == NAND_MFR_SAMSUNG ||
3945 maf_id == NAND_MFR_HYNIX ||
3946 maf_id == NAND_MFR_TOSHIBA ||
3947 maf_id == NAND_MFR_AMD ||
3948 maf_id == NAND_MFR_MACRONIX)) ||
3949 (mtd->writesize == 2048 &&
3950 maf_id == NAND_MFR_MICRON))
3951 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3952}
3953
ec6e87e3
HS
3954static inline bool is_full_id_nand(struct nand_flash_dev *type)
3955{
3956 return type->id_len;
3957}
3958
3959static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3960 struct nand_flash_dev *type, u8 *id_data, int *busw)
3961{
3962 if (!strncmp(type->id, id_data, type->id_len)) {
3963 mtd->writesize = type->pagesize;
3964 mtd->erasesize = type->erasesize;
3965 mtd->oobsize = type->oobsize;
3966
7db906b7 3967 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
ec6e87e3
HS
3968 chip->chipsize = (uint64_t)type->chipsize << 20;
3969 chip->options |= type->options;
57219342
HS
3970 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3971 chip->ecc_step_ds = NAND_ECC_STEP(type);
57a94e24
BB
3972 chip->onfi_timing_mode_default =
3973 type->onfi_timing_mode_default;
ec6e87e3
HS
3974
3975 *busw = type->options & NAND_BUSWIDTH_16;
3976
092b6a1d
CZ
3977 if (!mtd->name)
3978 mtd->name = type->name;
3979
ec6e87e3
HS
3980 return true;
3981 }
3982 return false;
3983}
3984
7aa65bfd 3985/*
8b6e50c9 3986 * Get the flash and manufacturer id and lookup if the type is supported.
7aa65bfd
TG
3987 */
3988static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
ace4dfee 3989 struct nand_chip *chip,
7351d3a5 3990 int *maf_id, int *dev_id,
5e81e88a 3991 struct nand_flash_dev *type)
7aa65bfd 3992{
bb77082f 3993 int busw;
d1e1f4e4 3994 int i, maf_idx;
426c457a 3995 u8 id_data[8];
1da177e4 3996
ef89a880
KB
3997 /*
3998 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
8b6e50c9 3999 * after power-up.
ef89a880 4000 */
73f907fd
BB
4001 nand_reset(chip, 0);
4002
4003 /* Select the device */
4004 chip->select_chip(mtd, 0);
ef89a880 4005
1da177e4 4006 /* Send the command for reading device ID */
ace4dfee 4007 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
1da177e4
LT
4008
4009 /* Read manufacturer and device IDs */
ace4dfee 4010 *maf_id = chip->read_byte(mtd);
d1e1f4e4 4011 *dev_id = chip->read_byte(mtd);
1da177e4 4012
8b6e50c9
BN
4013 /*
4014 * Try again to make sure, as some systems the bus-hold or other
ed8165c7
BD
4015 * interface concerns can cause random data which looks like a
4016 * possibly credible NAND flash to appear. If the two results do
4017 * not match, ignore the device completely.
4018 */
4019
4020 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4021
4aef9b78
BN
4022 /* Read entire ID string */
4023 for (i = 0; i < 8; i++)
426c457a 4024 id_data[i] = chip->read_byte(mtd);
ed8165c7 4025
d1e1f4e4 4026 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
20171642 4027 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
d0370219 4028 *maf_id, *dev_id, id_data[0], id_data[1]);
ed8165c7
BD
4029 return ERR_PTR(-ENODEV);
4030 }
4031
7aa65bfd 4032 if (!type)
5e81e88a
DW
4033 type = nand_flash_ids;
4034
ec6e87e3
HS
4035 for (; type->name != NULL; type++) {
4036 if (is_full_id_nand(type)) {
4037 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4038 goto ident_done;
4039 } else if (*dev_id == type->dev_id) {
db5b09f6 4040 break;
ec6e87e3
HS
4041 }
4042 }
5e81e88a 4043
d1e1f4e4
FF
4044 chip->onfi_version = 0;
4045 if (!type->name || !type->pagesize) {
35fc5195 4046 /* Check if the chip is ONFI compliant */
47450b35 4047 if (nand_flash_detect_onfi(mtd, chip, &busw))
6fb277ba 4048 goto ident_done;
91361818
HS
4049
4050 /* Check if the chip is JEDEC compliant */
4051 if (nand_flash_detect_jedec(mtd, chip, &busw))
4052 goto ident_done;
d1e1f4e4
FF
4053 }
4054
5e81e88a 4055 if (!type->name)
7aa65bfd
TG
4056 return ERR_PTR(-ENODEV);
4057
ba0251fe
TG
4058 if (!mtd->name)
4059 mtd->name = type->name;
4060
69423d99 4061 chip->chipsize = (uint64_t)type->chipsize << 20;
7aa65bfd 4062
a7f5ba40 4063 if (!type->pagesize) {
fc09bbc0
BN
4064 /* Decode parameters from extended ID */
4065 nand_decode_ext_id(mtd, chip, id_data, &busw);
7aa65bfd 4066 } else {
f23a481c 4067 nand_decode_id(mtd, chip, type, id_data, &busw);
7aa65bfd 4068 }
bf7a01bf
BN
4069 /* Get chip options */
4070 chip->options |= type->options;
d1e1f4e4 4071
8b6e50c9
BN
4072 /*
4073 * Check if chip is not a Samsung device. Do not clear the
4074 * options for chips which do not have an extended id.
d1e1f4e4
FF
4075 */
4076 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4077 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4078ident_done:
4079
7aa65bfd 4080 /* Try to identify manufacturer */
9a909867 4081 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
7aa65bfd
TG
4082 if (nand_manuf_ids[maf_idx].id == *maf_id)
4083 break;
4084 }
0ea4a755 4085
64b37b2a
MC
4086 if (chip->options & NAND_BUSWIDTH_AUTO) {
4087 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4088 chip->options |= busw;
4089 nand_set_defaults(chip, busw);
4090 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4091 /*
4092 * Check, if buswidth is correct. Hardware drivers should set
4093 * chip correct!
4094 */
20171642
EG
4095 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4096 *maf_id, *dev_id);
4097 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4098 pr_warn("bus width %d instead %d bit\n",
d0370219
BN
4099 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4100 busw ? 16 : 8);
7aa65bfd
TG
4101 return ERR_PTR(-EINVAL);
4102 }
61b03bd7 4103
7e74c2d7
BN
4104 nand_decode_bbm_options(mtd, chip, id_data);
4105
7aa65bfd 4106 /* Calculate the address shift from the page size */
ace4dfee 4107 chip->page_shift = ffs(mtd->writesize) - 1;
8b6e50c9 4108 /* Convert chipsize to number of pages per chip -1 */
ace4dfee 4109 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
61b03bd7 4110
ace4dfee 4111 chip->bbt_erase_shift = chip->phys_erase_shift =
7aa65bfd 4112 ffs(mtd->erasesize) - 1;
69423d99
AH
4113 if (chip->chipsize & 0xffffffff)
4114 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
7351d3a5
FF
4115 else {
4116 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4117 chip->chip_shift += 32 - 1;
4118 }
1da177e4 4119
26d9be11 4120 chip->badblockbits = 8;
49c50b97 4121 chip->erase = single_erase;
7aa65bfd 4122
8b6e50c9 4123 /* Do not replace user supplied command function! */
ace4dfee
TG
4124 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4125 chip->cmdfunc = nand_command_lp;
7aa65bfd 4126
20171642
EG
4127 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4128 *maf_id, *dev_id);
ffdac6cd
HS
4129
4130 if (chip->onfi_version)
4131 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4132 chip->onfi_params.model);
4133 else if (chip->jedec_version)
4134 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4135 chip->jedec_params.model);
4136 else
4137 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4138 type->name);
4139
3755a991 4140 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3723e93c 4141 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3755a991 4142 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
7aa65bfd
TG
4143 return type;
4144}
4145
d48f62b9
BB
4146static const char * const nand_ecc_modes[] = {
4147 [NAND_ECC_NONE] = "none",
4148 [NAND_ECC_SOFT] = "soft",
4149 [NAND_ECC_HW] = "hw",
4150 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4151 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
d48f62b9
BB
4152};
4153
4154static int of_get_nand_ecc_mode(struct device_node *np)
4155{
4156 const char *pm;
4157 int err, i;
4158
4159 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4160 if (err < 0)
4161 return err;
4162
4163 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4164 if (!strcasecmp(pm, nand_ecc_modes[i]))
4165 return i;
4166
ae211bcf
RM
4167 /*
4168 * For backward compatibility we support few obsoleted values that don't
4169 * have their mappings into nand_ecc_modes_t anymore (they were merged
4170 * with other enums).
4171 */
4172 if (!strcasecmp(pm, "soft_bch"))
4173 return NAND_ECC_SOFT;
4174
d48f62b9
BB
4175 return -ENODEV;
4176}
4177
ba4f46b2
RM
4178static const char * const nand_ecc_algos[] = {
4179 [NAND_ECC_HAMMING] = "hamming",
4180 [NAND_ECC_BCH] = "bch",
4181};
4182
d48f62b9
BB
4183static int of_get_nand_ecc_algo(struct device_node *np)
4184{
4185 const char *pm;
ba4f46b2 4186 int err, i;
d48f62b9 4187
ba4f46b2
RM
4188 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4189 if (!err) {
4190 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4191 if (!strcasecmp(pm, nand_ecc_algos[i]))
4192 return i;
4193 return -ENODEV;
4194 }
d48f62b9
BB
4195
4196 /*
4197 * For backward compatibility we also read "nand-ecc-mode" checking
4198 * for some obsoleted values that were specifying ECC algorithm.
4199 */
4200 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4201 if (err < 0)
4202 return err;
4203
4204 if (!strcasecmp(pm, "soft"))
4205 return NAND_ECC_HAMMING;
4206 else if (!strcasecmp(pm, "soft_bch"))
4207 return NAND_ECC_BCH;
4208
4209 return -ENODEV;
4210}
4211
4212static int of_get_nand_ecc_step_size(struct device_node *np)
4213{
4214 int ret;
4215 u32 val;
4216
4217 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4218 return ret ? ret : val;
4219}
4220
4221static int of_get_nand_ecc_strength(struct device_node *np)
4222{
4223 int ret;
4224 u32 val;
4225
4226 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4227 return ret ? ret : val;
4228}
4229
4230static int of_get_nand_bus_width(struct device_node *np)
4231{
4232 u32 val;
4233
4234 if (of_property_read_u32(np, "nand-bus-width", &val))
4235 return 8;
4236
4237 switch (val) {
4238 case 8:
4239 case 16:
4240 return val;
4241 default:
4242 return -EIO;
4243 }
4244}
4245
4246static bool of_get_nand_on_flash_bbt(struct device_node *np)
4247{
4248 return of_property_read_bool(np, "nand-on-flash-bbt");
4249}
4250
7194a29a 4251static int nand_dt_init(struct nand_chip *chip)
5844feea 4252{
7194a29a 4253 struct device_node *dn = nand_get_flash_node(chip);
79082457 4254 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
5844feea 4255
7194a29a
BB
4256 if (!dn)
4257 return 0;
4258
5844feea
BN
4259 if (of_get_nand_bus_width(dn) == 16)
4260 chip->options |= NAND_BUSWIDTH_16;
4261
4262 if (of_get_nand_on_flash_bbt(dn))
4263 chip->bbt_options |= NAND_BBT_USE_FLASH;
4264
4265 ecc_mode = of_get_nand_ecc_mode(dn);
79082457 4266 ecc_algo = of_get_nand_ecc_algo(dn);
5844feea
BN
4267 ecc_strength = of_get_nand_ecc_strength(dn);
4268 ecc_step = of_get_nand_ecc_step_size(dn);
4269
4270 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4271 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4272 pr_err("must set both strength and step size in DT\n");
4273 return -EINVAL;
4274 }
4275
4276 if (ecc_mode >= 0)
4277 chip->ecc.mode = ecc_mode;
4278
79082457
RM
4279 if (ecc_algo >= 0)
4280 chip->ecc.algo = ecc_algo;
4281
5844feea
BN
4282 if (ecc_strength >= 0)
4283 chip->ecc.strength = ecc_strength;
4284
4285 if (ecc_step > 0)
4286 chip->ecc.size = ecc_step;
4287
ba78ee00
BB
4288 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4289 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4290
5844feea
BN
4291 return 0;
4292}
4293
7aa65bfd 4294/**
3b85c321 4295 * nand_scan_ident - [NAND Interface] Scan for the NAND device
8b6e50c9
BN
4296 * @mtd: MTD device structure
4297 * @maxchips: number of chips to scan for
4298 * @table: alternative NAND ID table
7aa65bfd 4299 *
8b6e50c9
BN
4300 * This is the first phase of the normal nand_scan() function. It reads the
4301 * flash ID and sets up MTD fields accordingly.
7aa65bfd
TG
4302 *
4303 */
5e81e88a
DW
4304int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4305 struct nand_flash_dev *table)
7aa65bfd 4306{
bb77082f 4307 int i, nand_maf_id, nand_dev_id;
862eba51 4308 struct nand_chip *chip = mtd_to_nand(mtd);
7aa65bfd 4309 struct nand_flash_dev *type;
5844feea
BN
4310 int ret;
4311
7194a29a
BB
4312 ret = nand_dt_init(chip);
4313 if (ret)
4314 return ret;
7aa65bfd 4315
f7a8e38f
BN
4316 if (!mtd->name && mtd->dev.parent)
4317 mtd->name = dev_name(mtd->dev.parent);
4318
76fe334f
AS
4319 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4320 /*
4321 * Default functions assigned for chip_select() and
4322 * cmdfunc() both expect cmd_ctrl() to be populated,
4323 * so we need to check that that's the case
4324 */
4325 pr_err("chip.cmd_ctrl() callback is not provided");
4326 return -EINVAL;
4327 }
7aa65bfd 4328 /* Set the default functions */
bb77082f 4329 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
7aa65bfd
TG
4330
4331 /* Read the flash type */
bb77082f
CZ
4332 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4333 &nand_dev_id, table);
7aa65bfd
TG
4334
4335 if (IS_ERR(type)) {
b1c6e6db 4336 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
d0370219 4337 pr_warn("No NAND device found\n");
ace4dfee 4338 chip->select_chip(mtd, -1);
7aa65bfd 4339 return PTR_ERR(type);
1da177e4
LT
4340 }
4341
73f907fd 4342 /* Initialize the ->data_interface field. */
d8e725dd
BB
4343 ret = nand_init_data_interface(chip);
4344 if (ret)
4345 return ret;
4346
73f907fd
BB
4347 /*
4348 * Setup the data interface correctly on the chip and controller side.
4349 * This explicit call to nand_setup_data_interface() is only required
4350 * for the first die, because nand_reset() has been called before
4351 * ->data_interface and ->default_onfi_timing_mode were set.
4352 * For the other dies, nand_reset() will automatically switch to the
4353 * best mode for us.
4354 */
4355 ret = nand_setup_data_interface(chip);
4356 if (ret)
4357 return ret;
4358
07300164
HS
4359 chip->select_chip(mtd, -1);
4360
7aa65bfd 4361 /* Check for a chip array */
e0c7d767 4362 for (i = 1; i < maxchips; i++) {
ef89a880 4363 /* See comment in nand_get_flash_type for reset */
73f907fd
BB
4364 nand_reset(chip, i);
4365
4366 chip->select_chip(mtd, i);
1da177e4 4367 /* Send the command for reading device ID */
ace4dfee 4368 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
1da177e4 4369 /* Read manufacturer and device IDs */
ace4dfee 4370 if (nand_maf_id != chip->read_byte(mtd) ||
07300164
HS
4371 nand_dev_id != chip->read_byte(mtd)) {
4372 chip->select_chip(mtd, -1);
1da177e4 4373 break;
07300164
HS
4374 }
4375 chip->select_chip(mtd, -1);
1da177e4
LT
4376 }
4377 if (i > 1)
20171642 4378 pr_info("%d chips detected\n", i);
61b03bd7 4379
1da177e4 4380 /* Store the number of chips and calc total size for mtd */
ace4dfee
TG
4381 chip->numchips = i;
4382 mtd->size = i * chip->chipsize;
7aa65bfd 4383
3b85c321
DW
4384 return 0;
4385}
7351d3a5 4386EXPORT_SYMBOL(nand_scan_ident);
3b85c321 4387
06f384c9
RM
4388static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4389{
4390 struct nand_chip *chip = mtd_to_nand(mtd);
4391 struct nand_ecc_ctrl *ecc = &chip->ecc;
4392
e4225ae8 4393 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
06f384c9
RM
4394 return -EINVAL;
4395
4396 switch (ecc->algo) {
4397 case NAND_ECC_HAMMING:
4398 ecc->calculate = nand_calculate_ecc;
4399 ecc->correct = nand_correct_data;
4400 ecc->read_page = nand_read_page_swecc;
4401 ecc->read_subpage = nand_read_subpage;
4402 ecc->write_page = nand_write_page_swecc;
4403 ecc->read_page_raw = nand_read_page_raw;
4404 ecc->write_page_raw = nand_write_page_raw;
4405 ecc->read_oob = nand_read_oob_std;
4406 ecc->write_oob = nand_write_oob_std;
4407 if (!ecc->size)
4408 ecc->size = 256;
4409 ecc->bytes = 3;
4410 ecc->strength = 1;
4411 return 0;
4412 case NAND_ECC_BCH:
4413 if (!mtd_nand_has_bch()) {
4414 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4415 return -EINVAL;
4416 }
4417 ecc->calculate = nand_bch_calculate_ecc;
4418 ecc->correct = nand_bch_correct_data;
4419 ecc->read_page = nand_read_page_swecc;
4420 ecc->read_subpage = nand_read_subpage;
4421 ecc->write_page = nand_write_page_swecc;
4422 ecc->read_page_raw = nand_read_page_raw;
4423 ecc->write_page_raw = nand_write_page_raw;
4424 ecc->read_oob = nand_read_oob_std;
4425 ecc->write_oob = nand_write_oob_std;
8bbba481 4426
06f384c9
RM
4427 /*
4428 * Board driver should supply ecc.size and ecc.strength
4429 * values to select how many bits are correctable.
4430 * Otherwise, default to 4 bits for large page devices.
4431 */
4432 if (!ecc->size && (mtd->oobsize >= 64)) {
4433 ecc->size = 512;
4434 ecc->strength = 4;
4435 }
4436
4437 /*
4438 * if no ecc placement scheme was provided pickup the default
4439 * large page one.
4440 */
4441 if (!mtd->ooblayout) {
4442 /* handle large page devices only */
4443 if (mtd->oobsize < 64) {
4444 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4445 return -EINVAL;
4446 }
4447
4448 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
8bbba481
BB
4449
4450 }
4451
4452 /*
4453 * We can only maximize ECC config when the default layout is
4454 * used, otherwise we don't know how many bytes can really be
4455 * used.
4456 */
4457 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
4458 ecc->options & NAND_ECC_MAXIMIZE) {
4459 int steps, bytes;
4460
4461 /* Always prefer 1k blocks over 512bytes ones */
4462 ecc->size = 1024;
4463 steps = mtd->writesize / ecc->size;
4464
4465 /* Reserve 2 bytes for the BBM */
4466 bytes = (mtd->oobsize - 2) / steps;
4467 ecc->strength = bytes * 8 / fls(8 * ecc->size);
06f384c9
RM
4468 }
4469
4470 /* See nand_bch_init() for details. */
4471 ecc->bytes = 0;
4472 ecc->priv = nand_bch_init(mtd);
4473 if (!ecc->priv) {
4474 WARN(1, "BCH ECC initialization failed!\n");
4475 return -EINVAL;
4476 }
4477 return 0;
4478 default:
4479 WARN(1, "Unsupported ECC algorithm!\n");
4480 return -EINVAL;
4481 }
4482}
4483
67a9ad9b
EG
4484/*
4485 * Check if the chip configuration meet the datasheet requirements.
4486
4487 * If our configuration corrects A bits per B bytes and the minimum
4488 * required correction level is X bits per Y bytes, then we must ensure
4489 * both of the following are true:
4490 *
4491 * (1) A / B >= X / Y
4492 * (2) A >= X
4493 *
4494 * Requirement (1) ensures we can correct for the required bitflip density.
4495 * Requirement (2) ensures we can correct even when all bitflips are clumped
4496 * in the same sector.
4497 */
4498static bool nand_ecc_strength_good(struct mtd_info *mtd)
4499{
862eba51 4500 struct nand_chip *chip = mtd_to_nand(mtd);
67a9ad9b
EG
4501 struct nand_ecc_ctrl *ecc = &chip->ecc;
4502 int corr, ds_corr;
4503
4504 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4505 /* Not enough information */
4506 return true;
4507
4508 /*
4509 * We get the number of corrected bits per page to compare
4510 * the correction density.
4511 */
4512 corr = (mtd->writesize * ecc->strength) / ecc->size;
4513 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4514
4515 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4516}
3b85c321
DW
4517
4518/**
4519 * nand_scan_tail - [NAND Interface] Scan for the NAND device
8b6e50c9 4520 * @mtd: MTD device structure
3b85c321 4521 *
8b6e50c9
BN
4522 * This is the second phase of the normal nand_scan() function. It fills out
4523 * all the uninitialized function pointers with the defaults and scans for a
4524 * bad block table if appropriate.
3b85c321
DW
4525 */
4526int nand_scan_tail(struct mtd_info *mtd)
4527{
862eba51 4528 struct nand_chip *chip = mtd_to_nand(mtd);
97de79e0 4529 struct nand_ecc_ctrl *ecc = &chip->ecc;
f02ea4e6 4530 struct nand_buffers *nbuf;
11eaf6df 4531 int ret;
3b85c321 4532
e2414f4c 4533 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
11eaf6df
EG
4534 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4535 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4536 return -EINVAL;
e2414f4c 4537
f02ea4e6
HS
4538 if (!(chip->options & NAND_OWN_BUFFERS)) {
4539 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4540 + mtd->oobsize * 3, GFP_KERNEL);
4541 if (!nbuf)
4542 return -ENOMEM;
4543 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4544 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4545 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4546
4547 chip->buffers = nbuf;
4548 } else {
4549 if (!chip->buffers)
4550 return -ENOMEM;
4551 }
4bf63fcb 4552
7dcdcbef 4553 /* Set the internal oob buffer location, just after the page data */
784f4d5e 4554 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
1da177e4 4555
7aa65bfd 4556 /*
8b6e50c9 4557 * If no default placement scheme is given, select an appropriate one.
7aa65bfd 4558 */
06f384c9 4559 if (!mtd->ooblayout &&
e4225ae8 4560 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
61b03bd7 4561 switch (mtd->oobsize) {
1da177e4 4562 case 8:
1da177e4 4563 case 16:
41b207a7 4564 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
1da177e4
LT
4565 break;
4566 case 64:
81ec5364 4567 case 128:
41b207a7 4568 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
81ec5364 4569 break;
1da177e4 4570 default:
11eaf6df
EG
4571 WARN(1, "No oob scheme defined for oobsize %d\n",
4572 mtd->oobsize);
4573 ret = -EINVAL;
4574 goto err_free;
1da177e4
LT
4575 }
4576 }
61b03bd7 4577
956e944c
DW
4578 if (!chip->write_page)
4579 chip->write_page = nand_write_page;
4580
61b03bd7 4581 /*
8b6e50c9 4582 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
7aa65bfd 4583 * selected and we have 256 byte pagesize fallback to software ECC
e0c7d767 4584 */
956e944c 4585
97de79e0 4586 switch (ecc->mode) {
6e0cb135
SN
4587 case NAND_ECC_HW_OOB_FIRST:
4588 /* Similar to NAND_ECC_HW, but a separate read_page handle */
97de79e0 4589 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
11eaf6df
EG
4590 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4591 ret = -EINVAL;
4592 goto err_free;
6e0cb135 4593 }
97de79e0
HS
4594 if (!ecc->read_page)
4595 ecc->read_page = nand_read_page_hwecc_oob_first;
6e0cb135 4596
6dfc6d25 4597 case NAND_ECC_HW:
8b6e50c9 4598 /* Use standard hwecc read page function? */
97de79e0
HS
4599 if (!ecc->read_page)
4600 ecc->read_page = nand_read_page_hwecc;
4601 if (!ecc->write_page)
4602 ecc->write_page = nand_write_page_hwecc;
4603 if (!ecc->read_page_raw)
4604 ecc->read_page_raw = nand_read_page_raw;
4605 if (!ecc->write_page_raw)
4606 ecc->write_page_raw = nand_write_page_raw;
4607 if (!ecc->read_oob)
4608 ecc->read_oob = nand_read_oob_std;
4609 if (!ecc->write_oob)
4610 ecc->write_oob = nand_write_oob_std;
4611 if (!ecc->read_subpage)
4612 ecc->read_subpage = nand_read_subpage;
44991b3d 4613 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
97de79e0 4614 ecc->write_subpage = nand_write_subpage_hwecc;
f5bbdacc 4615
6dfc6d25 4616 case NAND_ECC_HW_SYNDROME:
97de79e0
HS
4617 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4618 (!ecc->read_page ||
4619 ecc->read_page == nand_read_page_hwecc ||
4620 !ecc->write_page ||
4621 ecc->write_page == nand_write_page_hwecc)) {
11eaf6df
EG
4622 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4623 ret = -EINVAL;
4624 goto err_free;
6dfc6d25 4625 }
8b6e50c9 4626 /* Use standard syndrome read/write page function? */
97de79e0
HS
4627 if (!ecc->read_page)
4628 ecc->read_page = nand_read_page_syndrome;
4629 if (!ecc->write_page)
4630 ecc->write_page = nand_write_page_syndrome;
4631 if (!ecc->read_page_raw)
4632 ecc->read_page_raw = nand_read_page_raw_syndrome;
4633 if (!ecc->write_page_raw)
4634 ecc->write_page_raw = nand_write_page_raw_syndrome;
4635 if (!ecc->read_oob)
4636 ecc->read_oob = nand_read_oob_syndrome;
4637 if (!ecc->write_oob)
4638 ecc->write_oob = nand_write_oob_syndrome;
4639
4640 if (mtd->writesize >= ecc->size) {
4641 if (!ecc->strength) {
11eaf6df
EG
4642 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4643 ret = -EINVAL;
4644 goto err_free;
e2788c98 4645 }
6dfc6d25 4646 break;
e2788c98 4647 }
2ac63d90
RM
4648 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4649 ecc->size, mtd->writesize);
97de79e0 4650 ecc->mode = NAND_ECC_SOFT;
e9d4faed 4651 ecc->algo = NAND_ECC_HAMMING;
61b03bd7 4652
6dfc6d25 4653 case NAND_ECC_SOFT:
06f384c9
RM
4654 ret = nand_set_ecc_soft_ops(mtd);
4655 if (ret) {
11eaf6df
EG
4656 ret = -EINVAL;
4657 goto err_free;
193bd400
ID
4658 }
4659 break;
4660
61b03bd7 4661 case NAND_ECC_NONE:
2ac63d90 4662 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
97de79e0
HS
4663 ecc->read_page = nand_read_page_raw;
4664 ecc->write_page = nand_write_page_raw;
4665 ecc->read_oob = nand_read_oob_std;
4666 ecc->read_page_raw = nand_read_page_raw;
4667 ecc->write_page_raw = nand_write_page_raw;
4668 ecc->write_oob = nand_write_oob_std;
4669 ecc->size = mtd->writesize;
4670 ecc->bytes = 0;
4671 ecc->strength = 0;
1da177e4 4672 break;
956e944c 4673
1da177e4 4674 default:
11eaf6df
EG
4675 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4676 ret = -EINVAL;
4677 goto err_free;
1da177e4 4678 }
61b03bd7 4679
9ce244b3 4680 /* For many systems, the standard OOB write also works for raw */
97de79e0
HS
4681 if (!ecc->read_oob_raw)
4682 ecc->read_oob_raw = ecc->read_oob;
4683 if (!ecc->write_oob_raw)
4684 ecc->write_oob_raw = ecc->write_oob;
9ce244b3 4685
846031d3 4686 /* propagate ecc info to mtd_info */
846031d3
BB
4687 mtd->ecc_strength = ecc->strength;
4688 mtd->ecc_step_size = ecc->size;
67a9ad9b 4689
7aa65bfd
TG
4690 /*
4691 * Set the number of read / write steps for one page depending on ECC
8b6e50c9 4692 * mode.
7aa65bfd 4693 */
97de79e0
HS
4694 ecc->steps = mtd->writesize / ecc->size;
4695 if (ecc->steps * ecc->size != mtd->writesize) {
11eaf6df
EG
4696 WARN(1, "Invalid ECC parameters\n");
4697 ret = -EINVAL;
4698 goto err_free;
1da177e4 4699 }
97de79e0 4700 ecc->total = ecc->steps * ecc->bytes;
61b03bd7 4701
846031d3
BB
4702 /*
4703 * The number of bytes available for a client to place data into
4704 * the out of band area.
4705 */
4706 ret = mtd_ooblayout_count_freebytes(mtd);
4707 if (ret < 0)
4708 ret = 0;
4709
4710 mtd->oobavail = ret;
4711
4712 /* ECC sanity check: warn if it's too weak */
4713 if (!nand_ecc_strength_good(mtd))
4714 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4715 mtd->name);
4716
8b6e50c9 4717 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
1d0ed69d 4718 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
97de79e0 4719 switch (ecc->steps) {
29072b96
TG
4720 case 2:
4721 mtd->subpage_sft = 1;
4722 break;
4723 case 4:
4724 case 8:
81ec5364 4725 case 16:
29072b96
TG
4726 mtd->subpage_sft = 2;
4727 break;
4728 }
4729 }
4730 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4731
04bbd0ea 4732 /* Initialize state */
ace4dfee 4733 chip->state = FL_READY;
1da177e4 4734
1da177e4 4735 /* Invalidate the pagebuffer reference */
ace4dfee 4736 chip->pagebuf = -1;
1da177e4 4737
a5ff4f10 4738 /* Large page NAND with SOFT_ECC should support subpage reads */
4007e2d1
RL
4739 switch (ecc->mode) {
4740 case NAND_ECC_SOFT:
4007e2d1
RL
4741 if (chip->page_shift > 9)
4742 chip->options |= NAND_SUBPAGE_READ;
4743 break;
4744
4745 default:
4746 break;
4747 }
a5ff4f10 4748
1da177e4 4749 /* Fill in remaining MTD driver data */
963d1c28 4750 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
93edbad6
ML
4751 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4752 MTD_CAP_NANDFLASH;
3c3c10bb
AB
4753 mtd->_erase = nand_erase;
4754 mtd->_point = NULL;
4755 mtd->_unpoint = NULL;
4756 mtd->_read = nand_read;
4757 mtd->_write = nand_write;
4758 mtd->_panic_write = panic_nand_write;
4759 mtd->_read_oob = nand_read_oob;
4760 mtd->_write_oob = nand_write_oob;
4761 mtd->_sync = nand_sync;
4762 mtd->_lock = NULL;
4763 mtd->_unlock = NULL;
4764 mtd->_suspend = nand_suspend;
4765 mtd->_resume = nand_resume;
72ea4036 4766 mtd->_reboot = nand_shutdown;
8471bb73 4767 mtd->_block_isreserved = nand_block_isreserved;
3c3c10bb
AB
4768 mtd->_block_isbad = nand_block_isbad;
4769 mtd->_block_markbad = nand_block_markbad;
cbcab65a 4770 mtd->writebufsize = mtd->writesize;
1da177e4 4771
ea3b2ea2
SL
4772 /*
4773 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4774 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4775 * properly set.
4776 */
4777 if (!mtd->bitflip_threshold)
240181fd 4778 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
1da177e4 4779
0040bf38 4780 /* Check, if we should skip the bad block table scan */
ace4dfee 4781 if (chip->options & NAND_SKIP_BBTSCAN)
0040bf38 4782 return 0;
1da177e4
LT
4783
4784 /* Build bad block table */
ace4dfee 4785 return chip->scan_bbt(mtd);
11eaf6df
EG
4786err_free:
4787 if (!(chip->options & NAND_OWN_BUFFERS))
4788 kfree(chip->buffers);
4789 return ret;
1da177e4 4790}
7351d3a5 4791EXPORT_SYMBOL(nand_scan_tail);
1da177e4 4792
8b6e50c9
BN
4793/*
4794 * is_module_text_address() isn't exported, and it's mostly a pointless
7351d3a5 4795 * test if this is a module _anyway_ -- they'd have to try _really_ hard
8b6e50c9
BN
4796 * to call us from in-kernel code if the core NAND support is modular.
4797 */
3b85c321
DW
4798#ifdef MODULE
4799#define caller_is_module() (1)
4800#else
4801#define caller_is_module() \
a6e6abd5 4802 is_module_text_address((unsigned long)__builtin_return_address(0))
3b85c321
DW
4803#endif
4804
4805/**
4806 * nand_scan - [NAND Interface] Scan for the NAND device
8b6e50c9
BN
4807 * @mtd: MTD device structure
4808 * @maxchips: number of chips to scan for
3b85c321 4809 *
8b6e50c9
BN
4810 * This fills out all the uninitialized function pointers with the defaults.
4811 * The flash ID is read and the mtd/chip structures are filled with the
20c07a5b 4812 * appropriate values.
3b85c321
DW
4813 */
4814int nand_scan(struct mtd_info *mtd, int maxchips)
4815{
4816 int ret;
4817
5e81e88a 4818 ret = nand_scan_ident(mtd, maxchips, NULL);
3b85c321
DW
4819 if (!ret)
4820 ret = nand_scan_tail(mtd);
4821 return ret;
4822}
7351d3a5 4823EXPORT_SYMBOL(nand_scan);
3b85c321 4824
1da177e4 4825/**
d44154f9
RW
4826 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
4827 * @chip: NAND chip object
8b6e50c9 4828 */
d44154f9 4829void nand_cleanup(struct nand_chip *chip)
1da177e4 4830{
e4225ae8 4831 if (chip->ecc.mode == NAND_ECC_SOFT &&
06f384c9 4832 chip->ecc.algo == NAND_ECC_BCH)
193bd400
ID
4833 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4834
d8e725dd
BB
4835 nand_release_data_interface(chip);
4836
fa671646 4837 /* Free bad block table memory */
ace4dfee 4838 kfree(chip->bbt);
4bf63fcb
DW
4839 if (!(chip->options & NAND_OWN_BUFFERS))
4840 kfree(chip->buffers);
58373ff0
BN
4841
4842 /* Free bad block descriptor memory */
4843 if (chip->badblock_pattern && chip->badblock_pattern->options
4844 & NAND_BBT_DYNAMICSTRUCT)
4845 kfree(chip->badblock_pattern);
1da177e4 4846}
d44154f9
RW
4847EXPORT_SYMBOL_GPL(nand_cleanup);
4848
4849/**
4850 * nand_release - [NAND Interface] Unregister the MTD device and free resources
4851 * held by the NAND device
4852 * @mtd: MTD device structure
4853 */
4854void nand_release(struct mtd_info *mtd)
4855{
4856 mtd_device_unregister(mtd);
4857 nand_cleanup(mtd_to_nand(mtd));
4858}
e0c7d767 4859EXPORT_SYMBOL_GPL(nand_release);
8fe833c1 4860
e0c7d767 4861MODULE_LICENSE("GPL");
7351d3a5
FF
4862MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4863MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
e0c7d767 4864MODULE_DESCRIPTION("Generic NAND flash driver code");