blob: 29e3a5b04778d16fd80a140991e257a2e2927133 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Overview:
4 * This is the generic MTD driver for NAND flash devices. It should be
5 * capable of working with almost all NAND chips currently available.
6 *
7 * Additional technical information is available on
8 * http://www.linux-mtd.infradead.org/doc/nand.html
9 *
10 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
11 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
12 *
13 * Credits:
14 * David Woodhouse for adding multichip support
15 *
16 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
17 * rework for 2K page size chips
18 *
19 * TODO:
20 * Enable cached programming for 2k page size chips
21 * Check, if mtd->ecctype should be set to MTD_ECC_HW
22 * if we have HW ECC support.
23 * BBT table is not serialized, has to be fixed
24 */
25
26#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27
28#include <linux/module.h>
29#include <linux/delay.h>
30#include <linux/errno.h>
31#include <linux/err.h>
32#include <linux/sched.h>
33#include <linux/slab.h>
34#include <linux/mm.h>
35#include <linux/types.h>
36#include <linux/mtd/mtd.h>
37#include <linux/mtd/nand_ecc.h>
38#include <linux/mtd/nand_bch.h>
39#include <linux/interrupt.h>
40#include <linux/bitops.h>
41#include <linux/io.h>
42#include <linux/mtd/partitions.h>
43#include <linux/of.h>
44#include <linux/gpio/consumer.h>
45
46#include "internals.h"
47
48/* Define default oob placement schemes for large and small page devices */
49static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
50 struct mtd_oob_region *oobregion)
51{
52 struct nand_chip *chip = mtd_to_nand(mtd);
53 struct nand_ecc_ctrl *ecc = &chip->ecc;
54
55 if (section > 1)
56 return -ERANGE;
57
58 if (!section) {
59 oobregion->offset = 0;
60 if (mtd->oobsize == 16)
61 oobregion->length = 4;
62 else
63 oobregion->length = 3;
64 } else {
65 if (mtd->oobsize == 8)
66 return -ERANGE;
67
68 oobregion->offset = 6;
69 oobregion->length = ecc->total - 4;
70 }
71
72 return 0;
73}
74
75static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
76 struct mtd_oob_region *oobregion)
77{
78 if (section > 1)
79 return -ERANGE;
80
81 if (mtd->oobsize == 16) {
82 if (section)
83 return -ERANGE;
84
85 oobregion->length = 8;
86 oobregion->offset = 8;
87 } else {
88 oobregion->length = 2;
89 if (!section)
90 oobregion->offset = 3;
91 else
92 oobregion->offset = 6;
93 }
94
95 return 0;
96}
97
98const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
99 .ecc = nand_ooblayout_ecc_sp,
100 .free = nand_ooblayout_free_sp,
101};
102EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
103
104static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
105 struct mtd_oob_region *oobregion)
106{
107 struct nand_chip *chip = mtd_to_nand(mtd);
108 struct nand_ecc_ctrl *ecc = &chip->ecc;
109
110 if (section || !ecc->total)
111 return -ERANGE;
112
113 oobregion->length = ecc->total;
114 oobregion->offset = mtd->oobsize - oobregion->length;
115
116 return 0;
117}
118
119static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
120 struct mtd_oob_region *oobregion)
121{
122 struct nand_chip *chip = mtd_to_nand(mtd);
123 struct nand_ecc_ctrl *ecc = &chip->ecc;
124
125 if (section)
126 return -ERANGE;
127
128 oobregion->length = mtd->oobsize - ecc->total - 2;
129 oobregion->offset = 2;
130
131 return 0;
132}
133
134const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
135 .ecc = nand_ooblayout_ecc_lp,
136 .free = nand_ooblayout_free_lp,
137};
138EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
139
140/*
141 * Support the old "large page" layout used for 1-bit Hamming ECC where ECC
142 * are placed at a fixed offset.
143 */
144static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
145 struct mtd_oob_region *oobregion)
146{
147 struct nand_chip *chip = mtd_to_nand(mtd);
148 struct nand_ecc_ctrl *ecc = &chip->ecc;
149
150 if (section)
151 return -ERANGE;
152
153 switch (mtd->oobsize) {
154 case 64:
155 oobregion->offset = 40;
156 break;
157 case 128:
158 oobregion->offset = 80;
159 break;
160 default:
161 return -EINVAL;
162 }
163
164 oobregion->length = ecc->total;
165 if (oobregion->offset + oobregion->length > mtd->oobsize)
166 return -ERANGE;
167
168 return 0;
169}
170
171static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
172 struct mtd_oob_region *oobregion)
173{
174 struct nand_chip *chip = mtd_to_nand(mtd);
175 struct nand_ecc_ctrl *ecc = &chip->ecc;
176 int ecc_offset = 0;
177
178 if (section < 0 || section > 1)
179 return -ERANGE;
180
181 switch (mtd->oobsize) {
182 case 64:
183 ecc_offset = 40;
184 break;
185 case 128:
186 ecc_offset = 80;
187 break;
188 default:
189 return -EINVAL;
190 }
191
192 if (section == 0) {
193 oobregion->offset = 2;
194 oobregion->length = ecc_offset - 2;
195 } else {
196 oobregion->offset = ecc_offset + ecc->total;
197 oobregion->length = mtd->oobsize - oobregion->offset;
198 }
199
200 return 0;
201}
202
203static const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
204 .ecc = nand_ooblayout_ecc_lp_hamming,
205 .free = nand_ooblayout_free_lp_hamming,
206};
207
208static int check_offs_len(struct nand_chip *chip, loff_t ofs, uint64_t len)
209{
210 int ret = 0;
211
212 /* Start address must align on block boundary */
213 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
214 pr_debug("%s: unaligned address\n", __func__);
215 ret = -EINVAL;
216 }
217
218 /* Length must align on block boundary */
219 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
220 pr_debug("%s: length not block aligned\n", __func__);
221 ret = -EINVAL;
222 }
223
224 return ret;
225}
226
227/**
228 * nand_select_target() - Select a NAND target (A.K.A. die)
229 * @chip: NAND chip object
230 * @cs: the CS line to select. Note that this CS id is always from the chip
231 * PoV, not the controller one
232 *
233 * Select a NAND target so that further operations executed on @chip go to the
234 * selected NAND target.
235 */
236void nand_select_target(struct nand_chip *chip, unsigned int cs)
237{
238 /*
239 * cs should always lie between 0 and nanddev_ntargets(), when that's
240 * not the case it's a bug and the caller should be fixed.
241 */
242 if (WARN_ON(cs > nanddev_ntargets(&chip->base)))
243 return;
244
245 chip->cur_cs = cs;
246
247 if (chip->legacy.select_chip)
248 chip->legacy.select_chip(chip, cs);
249}
250EXPORT_SYMBOL_GPL(nand_select_target);
251
252/**
253 * nand_deselect_target() - Deselect the currently selected target
254 * @chip: NAND chip object
255 *
256 * Deselect the currently selected NAND target. The result of operations
257 * executed on @chip after the target has been deselected is undefined.
258 */
259void nand_deselect_target(struct nand_chip *chip)
260{
261 if (chip->legacy.select_chip)
262 chip->legacy.select_chip(chip, -1);
263
264 chip->cur_cs = -1;
265}
266EXPORT_SYMBOL_GPL(nand_deselect_target);
267
268/**
269 * nand_release_device - [GENERIC] release chip
270 * @chip: NAND chip object
271 *
272 * Release chip lock and wake up anyone waiting on the device.
273 */
274static void nand_release_device(struct nand_chip *chip)
275{
276 /* Release the controller and the chip */
277 mutex_unlock(&chip->controller->lock);
278 mutex_unlock(&chip->lock);
279}
280
281/**
282 * nand_bbm_get_next_page - Get the next page for bad block markers
283 * @chip: NAND chip object
284 * @page: First page to start checking for bad block marker usage
285 *
286 * Returns an integer that corresponds to the page offset within a block, for
287 * a page that is used to store bad block markers. If no more pages are
288 * available, -EINVAL is returned.
289 */
290int nand_bbm_get_next_page(struct nand_chip *chip, int page)
291{
292 struct mtd_info *mtd = nand_to_mtd(chip);
293 int last_page = ((mtd->erasesize - mtd->writesize) >>
294 chip->page_shift) & chip->pagemask;
295 unsigned int bbm_flags = NAND_BBM_FIRSTPAGE | NAND_BBM_SECONDPAGE
296 | NAND_BBM_LASTPAGE;
297
298 if (page == 0 && !(chip->options & bbm_flags))
299 return 0;
300 if (page == 0 && chip->options & NAND_BBM_FIRSTPAGE)
301 return 0;
302 if (page <= 1 && chip->options & NAND_BBM_SECONDPAGE)
303 return 1;
304 if (page <= last_page && chip->options & NAND_BBM_LASTPAGE)
305 return last_page;
306
307 return -EINVAL;
308}
309
310/**
311 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
312 * @chip: NAND chip object
313 * @ofs: offset from device start
314 *
315 * Check, if the block is bad.
316 */
317static int nand_block_bad(struct nand_chip *chip, loff_t ofs)
318{
319 int first_page, page_offset;
320 int res;
321 u8 bad;
322
323 first_page = (int)(ofs >> chip->page_shift) & chip->pagemask;
324 page_offset = nand_bbm_get_next_page(chip, 0);
325
326 while (page_offset >= 0) {
327 res = chip->ecc.read_oob(chip, first_page + page_offset);
328 if (res < 0)
329 return res;
330
331 bad = chip->oob_poi[chip->badblockpos];
332
333 if (likely(chip->badblockbits == 8))
334 res = bad != 0xFF;
335 else
336 res = hweight8(bad) < chip->badblockbits;
337 if (res)
338 return res;
339
340 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
341 }
342
343 return 0;
344}
345
346static int nand_isbad_bbm(struct nand_chip *chip, loff_t ofs)
347{
348 if (chip->legacy.block_bad)
349 return chip->legacy.block_bad(chip, ofs);
350
351 return nand_block_bad(chip, ofs);
352}
353
354/**
355 * nand_get_device - [GENERIC] Get chip for selected access
356 * @chip: NAND chip structure
357 *
358 * Lock the device and its controller for exclusive access
359 *
360 * Return: -EBUSY if the chip has been suspended, 0 otherwise
361 */
362static void nand_get_device(struct nand_chip *chip)
363{
364 /* Wait until the device is resumed. */
365 while (1) {
366 mutex_lock(&chip->lock);
367 if (!chip->suspended) {
368 mutex_lock(&chip->controller->lock);
369 return;
370 }
371 mutex_unlock(&chip->lock);
372
373 wait_event(chip->resume_wq, !chip->suspended);
374 }
375}
376
377/**
378 * nand_check_wp - [GENERIC] check if the chip is write protected
379 * @chip: NAND chip object
380 *
381 * Check, if the device is write protected. The function expects, that the
382 * device is already selected.
383 */
384static int nand_check_wp(struct nand_chip *chip)
385{
386 u8 status;
387 int ret;
388
389 /* Broken xD cards report WP despite being writable */
390 if (chip->options & NAND_BROKEN_XD)
391 return 0;
392
393 /* Check the WP bit */
394 ret = nand_status_op(chip, &status);
395 if (ret)
396 return ret;
397
398 return status & NAND_STATUS_WP ? 0 : 1;
399}
400
401/**
402 * nand_fill_oob - [INTERN] Transfer client buffer to oob
403 * @chip: NAND chip object
404 * @oob: oob data buffer
405 * @len: oob data write length
406 * @ops: oob ops structure
407 */
408static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
409 struct mtd_oob_ops *ops)
410{
411 struct mtd_info *mtd = nand_to_mtd(chip);
412 int ret;
413
414 /*
415 * Initialise to all 0xFF, to avoid the possibility of left over OOB
416 * data from a previous OOB read.
417 */
418 memset(chip->oob_poi, 0xff, mtd->oobsize);
419
420 switch (ops->mode) {
421
422 case MTD_OPS_PLACE_OOB:
423 case MTD_OPS_RAW:
424 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
425 return oob + len;
426
427 case MTD_OPS_AUTO_OOB:
428 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
429 ops->ooboffs, len);
430 BUG_ON(ret);
431 return oob + len;
432
433 default:
434 BUG();
435 }
436 return NULL;
437}
438
439/**
440 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
441 * @chip: NAND chip object
442 * @to: offset to write to
443 * @ops: oob operation description structure
444 *
445 * NAND write out-of-band.
446 */
447static int nand_do_write_oob(struct nand_chip *chip, loff_t to,
448 struct mtd_oob_ops *ops)
449{
450 struct mtd_info *mtd = nand_to_mtd(chip);
451 int chipnr, page, status, len, ret;
452
453 pr_debug("%s: to = 0x%08x, len = %i\n",
454 __func__, (unsigned int)to, (int)ops->ooblen);
455
456 len = mtd_oobavail(mtd, ops);
457
458 /* Do not allow write past end of page */
459 if ((ops->ooboffs + ops->ooblen) > len) {
460 pr_debug("%s: attempt to write past end of page\n",
461 __func__);
462 return -EINVAL;
463 }
464
465 chipnr = (int)(to >> chip->chip_shift);
466
467 /*
468 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
469 * of my DiskOnChip 2000 test units) will clear the whole data page too
470 * if we don't do this. I have no clue why, but I seem to have 'fixed'
471 * it in the doc2000 driver in August 1999. dwmw2.
472 */
473 ret = nand_reset(chip, chipnr);
474 if (ret)
475 return ret;
476
477 nand_select_target(chip, chipnr);
478
479 /* Shift to get page */
480 page = (int)(to >> chip->page_shift);
481
482 /* Check, if it is write protected */
483 if (nand_check_wp(chip)) {
484 nand_deselect_target(chip);
485 return -EROFS;
486 }
487
488 /* Invalidate the page cache, if we write to the cached page */
489 if (page == chip->pagecache.page)
490 chip->pagecache.page = -1;
491
492 nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
493
494 if (ops->mode == MTD_OPS_RAW)
495 status = chip->ecc.write_oob_raw(chip, page & chip->pagemask);
496 else
497 status = chip->ecc.write_oob(chip, page & chip->pagemask);
498
499 nand_deselect_target(chip);
500
501 if (status)
502 return status;
503
504 ops->oobretlen = ops->ooblen;
505
506 return 0;
507}
508
509/**
510 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
511 * @chip: NAND chip object
512 * @ofs: offset from device start
513 *
514 * This is the default implementation, which can be overridden by a hardware
515 * specific driver. It provides the details for writing a bad block marker to a
516 * block.
517 */
518static int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
519{
520 struct mtd_info *mtd = nand_to_mtd(chip);
521 struct mtd_oob_ops ops;
522 uint8_t buf[2] = { 0, 0 };
523 int ret = 0, res, page_offset;
524
525 memset(&ops, 0, sizeof(ops));
526 ops.oobbuf = buf;
527 ops.ooboffs = chip->badblockpos;
528 if (chip->options & NAND_BUSWIDTH_16) {
529 ops.ooboffs &= ~0x01;
530 ops.len = ops.ooblen = 2;
531 } else {
532 ops.len = ops.ooblen = 1;
533 }
534 ops.mode = MTD_OPS_PLACE_OOB;
535
536 page_offset = nand_bbm_get_next_page(chip, 0);
537
538 while (page_offset >= 0) {
539 res = nand_do_write_oob(chip,
540 ofs + (page_offset * mtd->writesize),
541 &ops);
542
543 if (!ret)
544 ret = res;
545
546 page_offset = nand_bbm_get_next_page(chip, page_offset + 1);
547 }
548
549 return ret;
550}
551
552/**
553 * nand_markbad_bbm - mark a block by updating the BBM
554 * @chip: NAND chip object
555 * @ofs: offset of the block to mark bad
556 */
557int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
558{
559 if (chip->legacy.block_markbad)
560 return chip->legacy.block_markbad(chip, ofs);
561
562 return nand_default_block_markbad(chip, ofs);
563}
564
565/**
566 * nand_block_markbad_lowlevel - mark a block bad
567 * @chip: NAND chip object
568 * @ofs: offset from device start
569 *
570 * This function performs the generic NAND bad block marking steps (i.e., bad
571 * block table(s) and/or marker(s)). We only allow the hardware driver to
572 * specify how to write bad block markers to OOB (chip->legacy.block_markbad).
573 *
574 * We try operations in the following order:
575 *
576 * (1) erase the affected block, to allow OOB marker to be written cleanly
577 * (2) write bad block marker to OOB area of affected block (unless flag
578 * NAND_BBT_NO_OOB_BBM is present)
579 * (3) update the BBT
580 *
581 * Note that we retain the first error encountered in (2) or (3), finish the
582 * procedures, and dump the error in the end.
583*/
584static int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
585{
586 struct mtd_info *mtd = nand_to_mtd(chip);
587 int res, ret = 0;
588
589 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
590 struct erase_info einfo;
591
592 /* Attempt erase before marking OOB */
593 memset(&einfo, 0, sizeof(einfo));
594 einfo.addr = ofs;
595 einfo.len = 1ULL << chip->phys_erase_shift;
596 nand_erase_nand(chip, &einfo, 0);
597
598 /* Write bad block marker to OOB */
599 nand_get_device(chip);
600
601 ret = nand_markbad_bbm(chip, ofs);
602 nand_release_device(chip);
603 }
604
605 /* Mark block bad in BBT */
606 if (chip->bbt) {
607 res = nand_markbad_bbt(chip, ofs);
608 if (!ret)
609 ret = res;
610 }
611
612 if (!ret)
613 mtd->ecc_stats.badblocks++;
614
615 return ret;
616}
617
618/**
619 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
620 * @mtd: MTD device structure
621 * @ofs: offset from device start
622 *
623 * Check if the block is marked as reserved.
624 */
625static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
626{
627 struct nand_chip *chip = mtd_to_nand(mtd);
628
629 if (!chip->bbt)
630 return 0;
631 /* Return info from the table */
632 return nand_isreserved_bbt(chip, ofs);
633}
634
635/**
636 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
637 * @chip: NAND chip object
638 * @ofs: offset from device start
639 * @allowbbt: 1, if its allowed to access the bbt area
640 *
641 * Check, if the block is bad. Either by reading the bad block table or
642 * calling of the scan function.
643 */
644static int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
645{
646 /* Return info from the table */
647 if (chip->bbt)
648 return nand_isbad_bbt(chip, ofs, allowbbt);
649
650 return nand_isbad_bbm(chip, ofs);
651}
652
653/**
654 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
655 * @chip: NAND chip structure
656 * @timeout_ms: Timeout in ms
657 *
658 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
659 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
660 * returned.
661 *
662 * This helper is intended to be used when the controller does not have access
663 * to the NAND R/B pin.
664 *
665 * Be aware that calling this helper from an ->exec_op() implementation means
666 * ->exec_op() must be re-entrant.
667 *
668 * Return 0 if the NAND chip is ready, a negative error otherwise.
669 */
670int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
671{
672 const struct nand_sdr_timings *timings;
673 u8 status = 0;
674 int ret;
675
676 if (!nand_has_exec_op(chip))
677 return -ENOTSUPP;
678
679 /* Wait tWB before polling the STATUS reg. */
680 timings = nand_get_sdr_timings(&chip->data_interface);
681 ndelay(PSEC_TO_NSEC(timings->tWB_max));
682
683 ret = nand_status_op(chip, NULL);
684 if (ret)
685 return ret;
686
687 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms);
688 do {
689 ret = nand_read_data_op(chip, &status, sizeof(status), true);
690 if (ret)
691 break;
692
693 if (status & NAND_STATUS_READY)
694 break;
695
696 /*
697 * Typical lowest execution time for a tR on most NANDs is 10us,
698 * use this as polling delay before doing something smarter (ie.
699 * deriving a delay from the timeout value, timeout_ms/ratio).
700 */
701 udelay(10);
702 } while (time_before(jiffies, timeout_ms));
703
704 /*
705 * We have to exit READ_STATUS mode in order to read real data on the
706 * bus in case the WAITRDY instruction is preceding a DATA_IN
707 * instruction.
708 */
709 nand_exit_status_op(chip);
710
711 if (ret)
712 return ret;
713
714 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
715};
716EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
717
718/**
719 * nand_gpio_waitrdy - Poll R/B GPIO pin until ready
720 * @chip: NAND chip structure
721 * @gpiod: GPIO descriptor of R/B pin
722 * @timeout_ms: Timeout in ms
723 *
724 * Poll the R/B GPIO pin until it becomes ready. If that does not happen
725 * whitin the specified timeout, -ETIMEDOUT is returned.
726 *
727 * This helper is intended to be used when the controller has access to the
728 * NAND R/B pin over GPIO.
729 *
730 * Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
731 */
732int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
733 unsigned long timeout_ms)
734{
735
736 /*
737 * Wait until R/B pin indicates chip is ready or timeout occurs.
738 * +1 below is necessary because if we are now in the last fraction
739 * of jiffy and msecs_to_jiffies is 1 then we will wait only that
740 * small jiffy fraction - possibly leading to false timeout.
741 */
742 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms) + 1;
743 do {
744 if (gpiod_get_value_cansleep(gpiod))
745 return 0;
746
747 cond_resched();
748 } while (time_before(jiffies, timeout_ms));
749
750 return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
751};
752EXPORT_SYMBOL_GPL(nand_gpio_waitrdy);
753
754/**
755 * panic_nand_wait - [GENERIC] wait until the command is done
756 * @chip: NAND chip structure
757 * @timeo: timeout
758 *
759 * Wait for command done. This is a helper function for nand_wait used when
760 * we are in interrupt context. May happen when in panic and trying to write
761 * an oops through mtdoops.
762 */
763void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
764{
765 int i;
766 for (i = 0; i < timeo; i++) {
767 if (chip->legacy.dev_ready) {
768 if (chip->legacy.dev_ready(chip))
769 break;
770 } else {
771 int ret;
772 u8 status;
773
774 ret = nand_read_data_op(chip, &status, sizeof(status),
775 true);
776 if (ret)
777 return;
778
779 if (status & NAND_STATUS_READY)
780 break;
781 }
782 mdelay(1);
783 }
784}
785
786static bool nand_supports_get_features(struct nand_chip *chip, int addr)
787{
788 return (chip->parameters.supports_set_get_features &&
789 test_bit(addr, chip->parameters.get_feature_list));
790}
791
792static bool nand_supports_set_features(struct nand_chip *chip, int addr)
793{
794 return (chip->parameters.supports_set_get_features &&
795 test_bit(addr, chip->parameters.set_feature_list));
796}
797
798/**
799 * nand_reset_data_interface - Reset data interface and timings
800 * @chip: The NAND chip
801 * @chipnr: Internal die id
802 *
803 * Reset the Data interface and timings to ONFI mode 0.
804 *
805 * Returns 0 for success or negative error code otherwise.
806 */
807static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
808{
809 int ret;
810
811 if (!nand_has_setup_data_iface(chip))
812 return 0;
813
814 /*
815 * The ONFI specification says:
816 * "
817 * To transition from NV-DDR or NV-DDR2 to the SDR data
818 * interface, the host shall use the Reset (FFh) command
819 * using SDR timing mode 0. A device in any timing mode is
820 * required to recognize Reset (FFh) command issued in SDR
821 * timing mode 0.
822 * "
823 *
824 * Configure the data interface in SDR mode and set the
825 * timings to timing mode 0.
826 */
827
828 onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
829 ret = chip->controller->ops->setup_data_interface(chip, chipnr,
830 &chip->data_interface);
831 if (ret)
832 pr_err("Failed to configure data interface to SDR timing mode 0\n");
833
834 return ret;
835}
836
837/**
838 * nand_setup_data_interface - Setup the best data interface and timings
839 * @chip: The NAND chip
840 * @chipnr: Internal die id
841 *
842 * Find and configure the best data interface and NAND timings supported by
843 * the chip and the driver.
844 * First tries to retrieve supported timing modes from ONFI information,
845 * and if the NAND chip does not support ONFI, relies on the
846 * ->onfi_timing_mode_default specified in the nand_ids table.
847 *
848 * Returns 0 for success or negative error code otherwise.
849 */
850static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
851{
852 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
853 chip->onfi_timing_mode_default,
854 };
855 int ret;
856
857 if (!nand_has_setup_data_iface(chip))
858 return 0;
859
860 /* Change the mode on the chip side (if supported by the NAND chip) */
861 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
862 nand_select_target(chip, chipnr);
863 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
864 tmode_param);
865 nand_deselect_target(chip);
866 if (ret)
867 return ret;
868 }
869
870 /* Change the mode on the controller side */
871 ret = chip->controller->ops->setup_data_interface(chip, chipnr,
872 &chip->data_interface);
873 if (ret)
874 return ret;
875
876 /* Check the mode has been accepted by the chip, if supported */
877 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
878 return 0;
879
880 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
881 nand_select_target(chip, chipnr);
882 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
883 tmode_param);
884 nand_deselect_target(chip);
885 if (ret)
886 goto err_reset_chip;
887
888 if (tmode_param[0] != chip->onfi_timing_mode_default) {
889 pr_warn("timing mode %d not acknowledged by the NAND chip\n",
890 chip->onfi_timing_mode_default);
891 goto err_reset_chip;
892 }
893
894 return 0;
895
896err_reset_chip:
897 /*
898 * Fallback to mode 0 if the chip explicitly did not ack the chosen
899 * timing mode.
900 */
901 nand_reset_data_interface(chip, chipnr);
902 nand_select_target(chip, chipnr);
903 nand_reset_op(chip);
904 nand_deselect_target(chip);
905
906 return ret;
907}
908
909/**
910 * nand_init_data_interface - find the best data interface and timings
911 * @chip: The NAND chip
912 *
913 * Find the best data interface and NAND timings supported by the chip
914 * and the driver.
915 * First tries to retrieve supported timing modes from ONFI information,
916 * and if the NAND chip does not support ONFI, relies on the
917 * ->onfi_timing_mode_default specified in the nand_ids table. After this
918 * function nand_chip->data_interface is initialized with the best timing mode
919 * available.
920 *
921 * Returns 0 for success or negative error code otherwise.
922 */
923static int nand_init_data_interface(struct nand_chip *chip)
924{
925 int modes, mode, ret;
926
927 if (!nand_has_setup_data_iface(chip))
928 return 0;
929
930 /*
931 * First try to identify the best timings from ONFI parameters and
932 * if the NAND does not support ONFI, fallback to the default ONFI
933 * timing mode.
934 */
935 if (chip->parameters.onfi) {
936 modes = chip->parameters.onfi->async_timing_mode;
937 } else {
938 if (!chip->onfi_timing_mode_default)
939 return 0;
940
941 modes = GENMASK(chip->onfi_timing_mode_default, 0);
942 }
943
944 for (mode = fls(modes) - 1; mode >= 0; mode--) {
945 ret = onfi_fill_data_interface(chip, NAND_SDR_IFACE, mode);
946 if (ret)
947 continue;
948
949 /*
950 * Pass NAND_DATA_IFACE_CHECK_ONLY to only check if the
951 * controller supports the requested timings.
952 */
953 ret = chip->controller->ops->setup_data_interface(chip,
954 NAND_DATA_IFACE_CHECK_ONLY,
955 &chip->data_interface);
956 if (!ret) {
957 chip->onfi_timing_mode_default = mode;
958 break;
959 }
960 }
961
962 return 0;
963}
964
965/**
966 * nand_fill_column_cycles - fill the column cycles of an address
967 * @chip: The NAND chip
968 * @addrs: Array of address cycles to fill
969 * @offset_in_page: The offset in the page
970 *
971 * Fills the first or the first two bytes of the @addrs field depending
972 * on the NAND bus width and the page size.
973 *
974 * Returns the number of cycles needed to encode the column, or a negative
975 * error code in case one of the arguments is invalid.
976 */
977static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
978 unsigned int offset_in_page)
979{
980 struct mtd_info *mtd = nand_to_mtd(chip);
981
982 /* Make sure the offset is less than the actual page size. */
983 if (offset_in_page > mtd->writesize + mtd->oobsize)
984 return -EINVAL;
985
986 /*
987 * On small page NANDs, there's a dedicated command to access the OOB
988 * area, and the column address is relative to the start of the OOB
989 * area, not the start of the page. Asjust the address accordingly.
990 */
991 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
992 offset_in_page -= mtd->writesize;
993
994 /*
995 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
996 * wide, then it must be divided by 2.
997 */
998 if (chip->options & NAND_BUSWIDTH_16) {
999 if (WARN_ON(offset_in_page % 2))
1000 return -EINVAL;
1001
1002 offset_in_page /= 2;
1003 }
1004
1005 addrs[0] = offset_in_page;
1006
1007 /*
1008 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1009 * need 2
1010 */
1011 if (mtd->writesize <= 512)
1012 return 1;
1013
1014 addrs[1] = offset_in_page >> 8;
1015
1016 return 2;
1017}
1018
1019static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1020 unsigned int offset_in_page, void *buf,
1021 unsigned int len)
1022{
1023 struct mtd_info *mtd = nand_to_mtd(chip);
1024 const struct nand_sdr_timings *sdr =
1025 nand_get_sdr_timings(&chip->data_interface);
1026 u8 addrs[4];
1027 struct nand_op_instr instrs[] = {
1028 NAND_OP_CMD(NAND_CMD_READ0, 0),
1029 NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
1030 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1031 PSEC_TO_NSEC(sdr->tRR_min)),
1032 NAND_OP_DATA_IN(len, buf, 0),
1033 };
1034 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1035 int ret;
1036
1037 /* Drop the DATA_IN instruction if len is set to 0. */
1038 if (!len)
1039 op.ninstrs--;
1040
1041 if (offset_in_page >= mtd->writesize)
1042 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1043 else if (offset_in_page >= 256 &&
1044 !(chip->options & NAND_BUSWIDTH_16))
1045 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1046
1047 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1048 if (ret < 0)
1049 return ret;
1050
1051 addrs[1] = page;
1052 addrs[2] = page >> 8;
1053
1054 if (chip->options & NAND_ROW_ADDR_3) {
1055 addrs[3] = page >> 16;
1056 instrs[1].ctx.addr.naddrs++;
1057 }
1058
1059 return nand_exec_op(chip, &op);
1060}
1061
1062static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1063 unsigned int offset_in_page, void *buf,
1064 unsigned int len)
1065{
1066 const struct nand_sdr_timings *sdr =
1067 nand_get_sdr_timings(&chip->data_interface);
1068 u8 addrs[5];
1069 struct nand_op_instr instrs[] = {
1070 NAND_OP_CMD(NAND_CMD_READ0, 0),
1071 NAND_OP_ADDR(4, addrs, 0),
1072 NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
1073 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1074 PSEC_TO_NSEC(sdr->tRR_min)),
1075 NAND_OP_DATA_IN(len, buf, 0),
1076 };
1077 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1078 int ret;
1079
1080 /* Drop the DATA_IN instruction if len is set to 0. */
1081 if (!len)
1082 op.ninstrs--;
1083
1084 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1085 if (ret < 0)
1086 return ret;
1087
1088 addrs[2] = page;
1089 addrs[3] = page >> 8;
1090
1091 if (chip->options & NAND_ROW_ADDR_3) {
1092 addrs[4] = page >> 16;
1093 instrs[1].ctx.addr.naddrs++;
1094 }
1095
1096 return nand_exec_op(chip, &op);
1097}
1098
1099/**
1100 * nand_read_page_op - Do a READ PAGE operation
1101 * @chip: The NAND chip
1102 * @page: page to read
1103 * @offset_in_page: offset within the page
1104 * @buf: buffer used to store the data
1105 * @len: length of the buffer
1106 *
1107 * This function issues a READ PAGE operation.
1108 * This function does not select/unselect the CS line.
1109 *
1110 * Returns 0 on success, a negative error code otherwise.
1111 */
1112int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1113 unsigned int offset_in_page, void *buf, unsigned int len)
1114{
1115 struct mtd_info *mtd = nand_to_mtd(chip);
1116
1117 if (len && !buf)
1118 return -EINVAL;
1119
1120 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1121 return -EINVAL;
1122
1123 if (nand_has_exec_op(chip)) {
1124 if (mtd->writesize > 512)
1125 return nand_lp_exec_read_page_op(chip, page,
1126 offset_in_page, buf,
1127 len);
1128
1129 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1130 buf, len);
1131 }
1132
1133 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, offset_in_page, page);
1134 if (len)
1135 chip->legacy.read_buf(chip, buf, len);
1136
1137 return 0;
1138}
1139EXPORT_SYMBOL_GPL(nand_read_page_op);
1140
1141/**
1142 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1143 * @chip: The NAND chip
1144 * @page: parameter page to read
1145 * @buf: buffer used to store the data
1146 * @len: length of the buffer
1147 *
1148 * This function issues a READ PARAMETER PAGE operation.
1149 * This function does not select/unselect the CS line.
1150 *
1151 * Returns 0 on success, a negative error code otherwise.
1152 */
1153int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1154 unsigned int len)
1155{
1156 unsigned int i;
1157 u8 *p = buf;
1158
1159 if (len && !buf)
1160 return -EINVAL;
1161
1162 if (nand_has_exec_op(chip)) {
1163 const struct nand_sdr_timings *sdr =
1164 nand_get_sdr_timings(&chip->data_interface);
1165 struct nand_op_instr instrs[] = {
1166 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1167 NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
1168 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1169 PSEC_TO_NSEC(sdr->tRR_min)),
1170 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1171 };
1172 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1173
1174 /* Drop the DATA_IN instruction if len is set to 0. */
1175 if (!len)
1176 op.ninstrs--;
1177
1178 return nand_exec_op(chip, &op);
1179 }
1180
1181 chip->legacy.cmdfunc(chip, NAND_CMD_PARAM, page, -1);
1182 for (i = 0; i < len; i++)
1183 p[i] = chip->legacy.read_byte(chip);
1184
1185 return 0;
1186}
1187
1188/**
1189 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1190 * @chip: The NAND chip
1191 * @offset_in_page: offset within the page
1192 * @buf: buffer used to store the data
1193 * @len: length of the buffer
1194 * @force_8bit: force 8-bit bus access
1195 *
1196 * This function issues a CHANGE READ COLUMN operation.
1197 * This function does not select/unselect the CS line.
1198 *
1199 * Returns 0 on success, a negative error code otherwise.
1200 */
1201int nand_change_read_column_op(struct nand_chip *chip,
1202 unsigned int offset_in_page, void *buf,
1203 unsigned int len, bool force_8bit)
1204{
1205 struct mtd_info *mtd = nand_to_mtd(chip);
1206
1207 if (len && !buf)
1208 return -EINVAL;
1209
1210 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1211 return -EINVAL;
1212
1213 /* Small page NANDs do not support column change. */
1214 if (mtd->writesize <= 512)
1215 return -ENOTSUPP;
1216
1217 if (nand_has_exec_op(chip)) {
1218 const struct nand_sdr_timings *sdr =
1219 nand_get_sdr_timings(&chip->data_interface);
1220 u8 addrs[2] = {};
1221 struct nand_op_instr instrs[] = {
1222 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1223 NAND_OP_ADDR(2, addrs, 0),
1224 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1225 PSEC_TO_NSEC(sdr->tCCS_min)),
1226 NAND_OP_DATA_IN(len, buf, 0),
1227 };
1228 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1229 int ret;
1230
1231 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1232 if (ret < 0)
1233 return ret;
1234
1235 /* Drop the DATA_IN instruction if len is set to 0. */
1236 if (!len)
1237 op.ninstrs--;
1238
1239 instrs[3].ctx.data.force_8bit = force_8bit;
1240
1241 return nand_exec_op(chip, &op);
1242 }
1243
1244 chip->legacy.cmdfunc(chip, NAND_CMD_RNDOUT, offset_in_page, -1);
1245 if (len)
1246 chip->legacy.read_buf(chip, buf, len);
1247
1248 return 0;
1249}
1250EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1251
1252/**
1253 * nand_read_oob_op - Do a READ OOB operation
1254 * @chip: The NAND chip
1255 * @page: page to read
1256 * @offset_in_oob: offset within the OOB area
1257 * @buf: buffer used to store the data
1258 * @len: length of the buffer
1259 *
1260 * This function issues a READ OOB operation.
1261 * This function does not select/unselect the CS line.
1262 *
1263 * Returns 0 on success, a negative error code otherwise.
1264 */
1265int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1266 unsigned int offset_in_oob, void *buf, unsigned int len)
1267{
1268 struct mtd_info *mtd = nand_to_mtd(chip);
1269
1270 if (len && !buf)
1271 return -EINVAL;
1272
1273 if (offset_in_oob + len > mtd->oobsize)
1274 return -EINVAL;
1275
1276 if (nand_has_exec_op(chip))
1277 return nand_read_page_op(chip, page,
1278 mtd->writesize + offset_in_oob,
1279 buf, len);
1280
1281 chip->legacy.cmdfunc(chip, NAND_CMD_READOOB, offset_in_oob, page);
1282 if (len)
1283 chip->legacy.read_buf(chip, buf, len);
1284
1285 return 0;
1286}
1287EXPORT_SYMBOL_GPL(nand_read_oob_op);
1288
1289static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1290 unsigned int offset_in_page, const void *buf,
1291 unsigned int len, bool prog)
1292{
1293 struct mtd_info *mtd = nand_to_mtd(chip);
1294 const struct nand_sdr_timings *sdr =
1295 nand_get_sdr_timings(&chip->data_interface);
1296 u8 addrs[5] = {};
1297 struct nand_op_instr instrs[] = {
1298 /*
1299 * The first instruction will be dropped if we're dealing
1300 * with a large page NAND and adjusted if we're dealing
1301 * with a small page NAND and the page offset is > 255.
1302 */
1303 NAND_OP_CMD(NAND_CMD_READ0, 0),
1304 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1305 NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
1306 NAND_OP_DATA_OUT(len, buf, 0),
1307 NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
1308 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1309 };
1310 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1311 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1312 int ret;
1313 u8 status;
1314
1315 if (naddrs < 0)
1316 return naddrs;
1317
1318 addrs[naddrs++] = page;
1319 addrs[naddrs++] = page >> 8;
1320 if (chip->options & NAND_ROW_ADDR_3)
1321 addrs[naddrs++] = page >> 16;
1322
1323 instrs[2].ctx.addr.naddrs = naddrs;
1324
1325 /* Drop the last two instructions if we're not programming the page. */
1326 if (!prog) {
1327 op.ninstrs -= 2;
1328 /* Also drop the DATA_OUT instruction if empty. */
1329 if (!len)
1330 op.ninstrs--;
1331 }
1332
1333 if (mtd->writesize <= 512) {
1334 /*
1335 * Small pages need some more tweaking: we have to adjust the
1336 * first instruction depending on the page offset we're trying
1337 * to access.
1338 */
1339 if (offset_in_page >= mtd->writesize)
1340 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1341 else if (offset_in_page >= 256 &&
1342 !(chip->options & NAND_BUSWIDTH_16))
1343 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1344 } else {
1345 /*
1346 * Drop the first command if we're dealing with a large page
1347 * NAND.
1348 */
1349 op.instrs++;
1350 op.ninstrs--;
1351 }
1352
1353 ret = nand_exec_op(chip, &op);
1354 if (!prog || ret)
1355 return ret;
1356
1357 ret = nand_status_op(chip, &status);
1358 if (ret)
1359 return ret;
1360
1361 return status;
1362}
1363
1364/**
1365 * nand_prog_page_begin_op - starts a PROG PAGE operation
1366 * @chip: The NAND chip
1367 * @page: page to write
1368 * @offset_in_page: offset within the page
1369 * @buf: buffer containing the data to write to the page
1370 * @len: length of the buffer
1371 *
1372 * This function issues the first half of a PROG PAGE operation.
1373 * This function does not select/unselect the CS line.
1374 *
1375 * Returns 0 on success, a negative error code otherwise.
1376 */
1377int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1378 unsigned int offset_in_page, const void *buf,
1379 unsigned int len)
1380{
1381 struct mtd_info *mtd = nand_to_mtd(chip);
1382
1383 if (len && !buf)
1384 return -EINVAL;
1385
1386 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1387 return -EINVAL;
1388
1389 if (nand_has_exec_op(chip))
1390 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1391 len, false);
1392
1393 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page, page);
1394
1395 if (buf)
1396 chip->legacy.write_buf(chip, buf, len);
1397
1398 return 0;
1399}
1400EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1401
1402/**
1403 * nand_prog_page_end_op - ends a PROG PAGE operation
1404 * @chip: The NAND chip
1405 *
1406 * This function issues the second half of a PROG PAGE operation.
1407 * This function does not select/unselect the CS line.
1408 *
1409 * Returns 0 on success, a negative error code otherwise.
1410 */
1411int nand_prog_page_end_op(struct nand_chip *chip)
1412{
1413 int ret;
1414 u8 status;
1415
1416 if (nand_has_exec_op(chip)) {
1417 const struct nand_sdr_timings *sdr =
1418 nand_get_sdr_timings(&chip->data_interface);
1419 struct nand_op_instr instrs[] = {
1420 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1421 PSEC_TO_NSEC(sdr->tWB_max)),
1422 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1423 };
1424 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1425
1426 ret = nand_exec_op(chip, &op);
1427 if (ret)
1428 return ret;
1429
1430 ret = nand_status_op(chip, &status);
1431 if (ret)
1432 return ret;
1433 } else {
1434 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1435 ret = chip->legacy.waitfunc(chip);
1436 if (ret < 0)
1437 return ret;
1438
1439 status = ret;
1440 }
1441
1442 if (status & NAND_STATUS_FAIL)
1443 return -EIO;
1444
1445 return 0;
1446}
1447EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1448
1449/**
1450 * nand_prog_page_op - Do a full PROG PAGE operation
1451 * @chip: The NAND chip
1452 * @page: page to write
1453 * @offset_in_page: offset within the page
1454 * @buf: buffer containing the data to write to the page
1455 * @len: length of the buffer
1456 *
1457 * This function issues a full PROG PAGE operation.
1458 * This function does not select/unselect the CS line.
1459 *
1460 * Returns 0 on success, a negative error code otherwise.
1461 */
1462int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1463 unsigned int offset_in_page, const void *buf,
1464 unsigned int len)
1465{
1466 struct mtd_info *mtd = nand_to_mtd(chip);
1467 int status;
1468
1469 if (!len || !buf)
1470 return -EINVAL;
1471
1472 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1473 return -EINVAL;
1474
1475 if (nand_has_exec_op(chip)) {
1476 status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1477 len, true);
1478 } else {
1479 chip->legacy.cmdfunc(chip, NAND_CMD_SEQIN, offset_in_page,
1480 page);
1481 chip->legacy.write_buf(chip, buf, len);
1482 chip->legacy.cmdfunc(chip, NAND_CMD_PAGEPROG, -1, -1);
1483 status = chip->legacy.waitfunc(chip);
1484 }
1485
1486 if (status & NAND_STATUS_FAIL)
1487 return -EIO;
1488
1489 return 0;
1490}
1491EXPORT_SYMBOL_GPL(nand_prog_page_op);
1492
1493/**
1494 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1495 * @chip: The NAND chip
1496 * @offset_in_page: offset within the page
1497 * @buf: buffer containing the data to send to the NAND
1498 * @len: length of the buffer
1499 * @force_8bit: force 8-bit bus access
1500 *
1501 * This function issues a CHANGE WRITE COLUMN operation.
1502 * This function does not select/unselect the CS line.
1503 *
1504 * Returns 0 on success, a negative error code otherwise.
1505 */
1506int nand_change_write_column_op(struct nand_chip *chip,
1507 unsigned int offset_in_page,
1508 const void *buf, unsigned int len,
1509 bool force_8bit)
1510{
1511 struct mtd_info *mtd = nand_to_mtd(chip);
1512
1513 if (len && !buf)
1514 return -EINVAL;
1515
1516 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1517 return -EINVAL;
1518
1519 /* Small page NANDs do not support column change. */
1520 if (mtd->writesize <= 512)
1521 return -ENOTSUPP;
1522
1523 if (nand_has_exec_op(chip)) {
1524 const struct nand_sdr_timings *sdr =
1525 nand_get_sdr_timings(&chip->data_interface);
1526 u8 addrs[2];
1527 struct nand_op_instr instrs[] = {
1528 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1529 NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
1530 NAND_OP_DATA_OUT(len, buf, 0),
1531 };
1532 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1533 int ret;
1534
1535 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1536 if (ret < 0)
1537 return ret;
1538
1539 instrs[2].ctx.data.force_8bit = force_8bit;
1540
1541 /* Drop the DATA_OUT instruction if len is set to 0. */
1542 if (!len)
1543 op.ninstrs--;
1544
1545 return nand_exec_op(chip, &op);
1546 }
1547
1548 chip->legacy.cmdfunc(chip, NAND_CMD_RNDIN, offset_in_page, -1);
1549 if (len)
1550 chip->legacy.write_buf(chip, buf, len);
1551
1552 return 0;
1553}
1554EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1555
1556/**
1557 * nand_readid_op - Do a READID operation
1558 * @chip: The NAND chip
1559 * @addr: address cycle to pass after the READID command
1560 * @buf: buffer used to store the ID
1561 * @len: length of the buffer
1562 *
1563 * This function sends a READID command and reads back the ID returned by the
1564 * NAND.
1565 * This function does not select/unselect the CS line.
1566 *
1567 * Returns 0 on success, a negative error code otherwise.
1568 */
1569int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1570 unsigned int len)
1571{
1572 unsigned int i;
1573 u8 *id = buf;
1574
1575 if (len && !buf)
1576 return -EINVAL;
1577
1578 if (nand_has_exec_op(chip)) {
1579 const struct nand_sdr_timings *sdr =
1580 nand_get_sdr_timings(&chip->data_interface);
1581 struct nand_op_instr instrs[] = {
1582 NAND_OP_CMD(NAND_CMD_READID, 0),
1583 NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
1584 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1585 };
1586 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1587
1588 /* Drop the DATA_IN instruction if len is set to 0. */
1589 if (!len)
1590 op.ninstrs--;
1591
1592 return nand_exec_op(chip, &op);
1593 }
1594
1595 chip->legacy.cmdfunc(chip, NAND_CMD_READID, addr, -1);
1596
1597 for (i = 0; i < len; i++)
1598 id[i] = chip->legacy.read_byte(chip);
1599
1600 return 0;
1601}
1602EXPORT_SYMBOL_GPL(nand_readid_op);
1603
1604/**
1605 * nand_status_op - Do a STATUS operation
1606 * @chip: The NAND chip
1607 * @status: out variable to store the NAND status
1608 *
1609 * This function sends a STATUS command and reads back the status returned by
1610 * the NAND.
1611 * This function does not select/unselect the CS line.
1612 *
1613 * Returns 0 on success, a negative error code otherwise.
1614 */
1615int nand_status_op(struct nand_chip *chip, u8 *status)
1616{
1617 if (nand_has_exec_op(chip)) {
1618 const struct nand_sdr_timings *sdr =
1619 nand_get_sdr_timings(&chip->data_interface);
1620 struct nand_op_instr instrs[] = {
1621 NAND_OP_CMD(NAND_CMD_STATUS,
1622 PSEC_TO_NSEC(sdr->tADL_min)),
1623 NAND_OP_8BIT_DATA_IN(1, status, 0),
1624 };
1625 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1626
1627 if (!status)
1628 op.ninstrs--;
1629
1630 return nand_exec_op(chip, &op);
1631 }
1632
1633 chip->legacy.cmdfunc(chip, NAND_CMD_STATUS, -1, -1);
1634 if (status)
1635 *status = chip->legacy.read_byte(chip);
1636
1637 return 0;
1638}
1639EXPORT_SYMBOL_GPL(nand_status_op);
1640
1641/**
1642 * nand_exit_status_op - Exit a STATUS operation
1643 * @chip: The NAND chip
1644 *
1645 * This function sends a READ0 command to cancel the effect of the STATUS
1646 * command to avoid reading only the status until a new read command is sent.
1647 *
1648 * This function does not select/unselect the CS line.
1649 *
1650 * Returns 0 on success, a negative error code otherwise.
1651 */
1652int nand_exit_status_op(struct nand_chip *chip)
1653{
1654 if (nand_has_exec_op(chip)) {
1655 struct nand_op_instr instrs[] = {
1656 NAND_OP_CMD(NAND_CMD_READ0, 0),
1657 };
1658 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1659
1660 return nand_exec_op(chip, &op);
1661 }
1662
1663 chip->legacy.cmdfunc(chip, NAND_CMD_READ0, -1, -1);
1664
1665 return 0;
1666}
1667
1668/**
1669 * nand_erase_op - Do an erase operation
1670 * @chip: The NAND chip
1671 * @eraseblock: block to erase
1672 *
1673 * This function sends an ERASE command and waits for the NAND to be ready
1674 * before returning.
1675 * This function does not select/unselect the CS line.
1676 *
1677 * Returns 0 on success, a negative error code otherwise.
1678 */
1679int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1680{
1681 unsigned int page = eraseblock <<
1682 (chip->phys_erase_shift - chip->page_shift);
1683 int ret;
1684 u8 status;
1685
1686 if (nand_has_exec_op(chip)) {
1687 const struct nand_sdr_timings *sdr =
1688 nand_get_sdr_timings(&chip->data_interface);
1689 u8 addrs[3] = { page, page >> 8, page >> 16 };
1690 struct nand_op_instr instrs[] = {
1691 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
1692 NAND_OP_ADDR(2, addrs, 0),
1693 NAND_OP_CMD(NAND_CMD_ERASE2,
1694 PSEC_TO_MSEC(sdr->tWB_max)),
1695 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
1696 };
1697 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1698
1699 if (chip->options & NAND_ROW_ADDR_3)
1700 instrs[1].ctx.addr.naddrs++;
1701
1702 ret = nand_exec_op(chip, &op);
1703 if (ret)
1704 return ret;
1705
1706 ret = nand_status_op(chip, &status);
1707 if (ret)
1708 return ret;
1709 } else {
1710 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE1, -1, page);
1711 chip->legacy.cmdfunc(chip, NAND_CMD_ERASE2, -1, -1);
1712
1713 ret = chip->legacy.waitfunc(chip);
1714 if (ret < 0)
1715 return ret;
1716
1717 status = ret;
1718 }
1719
1720 if (status & NAND_STATUS_FAIL)
1721 return -EIO;
1722
1723 return 0;
1724}
1725EXPORT_SYMBOL_GPL(nand_erase_op);
1726
1727/**
1728 * nand_set_features_op - Do a SET FEATURES operation
1729 * @chip: The NAND chip
1730 * @feature: feature id
1731 * @data: 4 bytes of data
1732 *
1733 * This function sends a SET FEATURES command and waits for the NAND to be
1734 * ready before returning.
1735 * This function does not select/unselect the CS line.
1736 *
1737 * Returns 0 on success, a negative error code otherwise.
1738 */
1739static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1740 const void *data)
1741{
1742 const u8 *params = data;
1743 int i, ret;
1744
1745 if (nand_has_exec_op(chip)) {
1746 const struct nand_sdr_timings *sdr =
1747 nand_get_sdr_timings(&chip->data_interface);
1748 struct nand_op_instr instrs[] = {
1749 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
1750 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
1751 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
1752 PSEC_TO_NSEC(sdr->tWB_max)),
1753 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
1754 };
1755 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1756
1757 return nand_exec_op(chip, &op);
1758 }
1759
1760 chip->legacy.cmdfunc(chip, NAND_CMD_SET_FEATURES, feature, -1);
1761 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1762 chip->legacy.write_byte(chip, params[i]);
1763
1764 ret = chip->legacy.waitfunc(chip);
1765 if (ret < 0)
1766 return ret;
1767
1768 if (ret & NAND_STATUS_FAIL)
1769 return -EIO;
1770
1771 return 0;
1772}
1773
1774/**
1775 * nand_get_features_op - Do a GET FEATURES operation
1776 * @chip: The NAND chip
1777 * @feature: feature id
1778 * @data: 4 bytes of data
1779 *
1780 * This function sends a GET FEATURES command and waits for the NAND to be
1781 * ready before returning.
1782 * This function does not select/unselect the CS line.
1783 *
1784 * Returns 0 on success, a negative error code otherwise.
1785 */
1786static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1787 void *data)
1788{
1789 u8 *params = data;
1790 int i;
1791
1792 if (nand_has_exec_op(chip)) {
1793 const struct nand_sdr_timings *sdr =
1794 nand_get_sdr_timings(&chip->data_interface);
1795 struct nand_op_instr instrs[] = {
1796 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
1797 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
1798 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
1799 PSEC_TO_NSEC(sdr->tRR_min)),
1800 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
1801 data, 0),
1802 };
1803 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1804
1805 return nand_exec_op(chip, &op);
1806 }
1807
1808 chip->legacy.cmdfunc(chip, NAND_CMD_GET_FEATURES, feature, -1);
1809 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1810 params[i] = chip->legacy.read_byte(chip);
1811
1812 return 0;
1813}
1814
1815static int nand_wait_rdy_op(struct nand_chip *chip, unsigned int timeout_ms,
1816 unsigned int delay_ns)
1817{
1818 if (nand_has_exec_op(chip)) {
1819 struct nand_op_instr instrs[] = {
1820 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(timeout_ms),
1821 PSEC_TO_NSEC(delay_ns)),
1822 };
1823 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1824
1825 return nand_exec_op(chip, &op);
1826 }
1827
1828 /* Apply delay or wait for ready/busy pin */
1829 if (!chip->legacy.dev_ready)
1830 udelay(chip->legacy.chip_delay);
1831 else
1832 nand_wait_ready(chip);
1833
1834 return 0;
1835}
1836
1837/**
1838 * nand_reset_op - Do a reset operation
1839 * @chip: The NAND chip
1840 *
1841 * This function sends a RESET command and waits for the NAND to be ready
1842 * before returning.
1843 * This function does not select/unselect the CS line.
1844 *
1845 * Returns 0 on success, a negative error code otherwise.
1846 */
1847int nand_reset_op(struct nand_chip *chip)
1848{
1849 if (nand_has_exec_op(chip)) {
1850 const struct nand_sdr_timings *sdr =
1851 nand_get_sdr_timings(&chip->data_interface);
1852 struct nand_op_instr instrs[] = {
1853 NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
1854 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
1855 };
1856 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1857
1858 return nand_exec_op(chip, &op);
1859 }
1860
1861 chip->legacy.cmdfunc(chip, NAND_CMD_RESET, -1, -1);
1862
1863 return 0;
1864}
1865EXPORT_SYMBOL_GPL(nand_reset_op);
1866
1867/**
1868 * nand_read_data_op - Read data from the NAND
1869 * @chip: The NAND chip
1870 * @buf: buffer used to store the data
1871 * @len: length of the buffer
1872 * @force_8bit: force 8-bit bus access
1873 *
1874 * This function does a raw data read on the bus. Usually used after launching
1875 * another NAND operation like nand_read_page_op().
1876 * This function does not select/unselect the CS line.
1877 *
1878 * Returns 0 on success, a negative error code otherwise.
1879 */
1880int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1881 bool force_8bit)
1882{
1883 if (!len || !buf)
1884 return -EINVAL;
1885
1886 if (nand_has_exec_op(chip)) {
1887 struct nand_op_instr instrs[] = {
1888 NAND_OP_DATA_IN(len, buf, 0),
1889 };
1890 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1891
1892 instrs[0].ctx.data.force_8bit = force_8bit;
1893
1894 return nand_exec_op(chip, &op);
1895 }
1896
1897 if (force_8bit) {
1898 u8 *p = buf;
1899 unsigned int i;
1900
1901 for (i = 0; i < len; i++)
1902 p[i] = chip->legacy.read_byte(chip);
1903 } else {
1904 chip->legacy.read_buf(chip, buf, len);
1905 }
1906
1907 return 0;
1908}
1909EXPORT_SYMBOL_GPL(nand_read_data_op);
1910
1911/**
1912 * nand_write_data_op - Write data from the NAND
1913 * @chip: The NAND chip
1914 * @buf: buffer containing the data to send on the bus
1915 * @len: length of the buffer
1916 * @force_8bit: force 8-bit bus access
1917 *
1918 * This function does a raw data write on the bus. Usually used after launching
1919 * another NAND operation like nand_write_page_begin_op().
1920 * This function does not select/unselect the CS line.
1921 *
1922 * Returns 0 on success, a negative error code otherwise.
1923 */
1924int nand_write_data_op(struct nand_chip *chip, const void *buf,
1925 unsigned int len, bool force_8bit)
1926{
1927 if (!len || !buf)
1928 return -EINVAL;
1929
1930 if (nand_has_exec_op(chip)) {
1931 struct nand_op_instr instrs[] = {
1932 NAND_OP_DATA_OUT(len, buf, 0),
1933 };
1934 struct nand_operation op = NAND_OPERATION(chip->cur_cs, instrs);
1935
1936 instrs[0].ctx.data.force_8bit = force_8bit;
1937
1938 return nand_exec_op(chip, &op);
1939 }
1940
1941 if (force_8bit) {
1942 const u8 *p = buf;
1943 unsigned int i;
1944
1945 for (i = 0; i < len; i++)
1946 chip->legacy.write_byte(chip, p[i]);
1947 } else {
1948 chip->legacy.write_buf(chip, buf, len);
1949 }
1950
1951 return 0;
1952}
1953EXPORT_SYMBOL_GPL(nand_write_data_op);
1954
1955/**
1956 * struct nand_op_parser_ctx - Context used by the parser
1957 * @instrs: array of all the instructions that must be addressed
1958 * @ninstrs: length of the @instrs array
1959 * @subop: Sub-operation to be passed to the NAND controller
1960 *
1961 * This structure is used by the core to split NAND operations into
1962 * sub-operations that can be handled by the NAND controller.
1963 */
1964struct nand_op_parser_ctx {
1965 const struct nand_op_instr *instrs;
1966 unsigned int ninstrs;
1967 struct nand_subop subop;
1968};
1969
1970/**
1971 * nand_op_parser_must_split_instr - Checks if an instruction must be split
1972 * @pat: the parser pattern element that matches @instr
1973 * @instr: pointer to the instruction to check
1974 * @start_offset: this is an in/out parameter. If @instr has already been
1975 * split, then @start_offset is the offset from which to start
1976 * (either an address cycle or an offset in the data buffer).
1977 * Conversely, if the function returns true (ie. instr must be
1978 * split), this parameter is updated to point to the first
1979 * data/address cycle that has not been taken care of.
1980 *
1981 * Some NAND controllers are limited and cannot send X address cycles with a
1982 * unique operation, or cannot read/write more than Y bytes at the same time.
1983 * In this case, split the instruction that does not fit in a single
1984 * controller-operation into two or more chunks.
1985 *
1986 * Returns true if the instruction must be split, false otherwise.
1987 * The @start_offset parameter is also updated to the offset at which the next
1988 * bundle of instruction must start (if an address or a data instruction).
1989 */
1990static bool
1991nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
1992 const struct nand_op_instr *instr,
1993 unsigned int *start_offset)
1994{
1995 switch (pat->type) {
1996 case NAND_OP_ADDR_INSTR:
1997 if (!pat->ctx.addr.maxcycles)
1998 break;
1999
2000 if (instr->ctx.addr.naddrs - *start_offset >
2001 pat->ctx.addr.maxcycles) {
2002 *start_offset += pat->ctx.addr.maxcycles;
2003 return true;
2004 }
2005 break;
2006
2007 case NAND_OP_DATA_IN_INSTR:
2008 case NAND_OP_DATA_OUT_INSTR:
2009 if (!pat->ctx.data.maxlen)
2010 break;
2011
2012 if (instr->ctx.data.len - *start_offset >
2013 pat->ctx.data.maxlen) {
2014 *start_offset += pat->ctx.data.maxlen;
2015 return true;
2016 }
2017 break;
2018
2019 default:
2020 break;
2021 }
2022
2023 return false;
2024}
2025
2026/**
2027 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2028 * remaining in the parser context
2029 * @pat: the pattern to test
2030 * @ctx: the parser context structure to match with the pattern @pat
2031 *
2032 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2033 * Returns true if this is the case, false ortherwise. When true is returned,
2034 * @ctx->subop is updated with the set of instructions to be passed to the
2035 * controller driver.
2036 */
2037static bool
2038nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2039 struct nand_op_parser_ctx *ctx)
2040{
2041 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2042 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2043 const struct nand_op_instr *instr = ctx->subop.instrs;
2044 unsigned int i, ninstrs;
2045
2046 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2047 /*
2048 * The pattern instruction does not match the operation
2049 * instruction. If the instruction is marked optional in the
2050 * pattern definition, we skip the pattern element and continue
2051 * to the next one. If the element is mandatory, there's no
2052 * match and we can return false directly.
2053 */
2054 if (instr->type != pat->elems[i].type) {
2055 if (!pat->elems[i].optional)
2056 return false;
2057
2058 continue;
2059 }
2060
2061 /*
2062 * Now check the pattern element constraints. If the pattern is
2063 * not able to handle the whole instruction in a single step,
2064 * we have to split it.
2065 * The last_instr_end_off value comes back updated to point to
2066 * the position where we have to split the instruction (the
2067 * start of the next subop chunk).
2068 */
2069 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2070 &instr_offset)) {
2071 ninstrs++;
2072 i++;
2073 break;
2074 }
2075
2076 instr++;
2077 ninstrs++;
2078 instr_offset = 0;
2079 }
2080
2081 /*
2082 * This can happen if all instructions of a pattern are optional.
2083 * Still, if there's not at least one instruction handled by this
2084 * pattern, this is not a match, and we should try the next one (if
2085 * any).
2086 */
2087 if (!ninstrs)
2088 return false;
2089
2090 /*
2091 * We had a match on the pattern head, but the pattern may be longer
2092 * than the instructions we're asked to execute. We need to make sure
2093 * there's no mandatory elements in the pattern tail.
2094 */
2095 for (; i < pat->nelems; i++) {
2096 if (!pat->elems[i].optional)
2097 return false;
2098 }
2099
2100 /*
2101 * We have a match: update the subop structure accordingly and return
2102 * true.
2103 */
2104 ctx->subop.ninstrs = ninstrs;
2105 ctx->subop.last_instr_end_off = instr_offset;
2106
2107 return true;
2108}
2109
2110#if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2111static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2112{
2113 const struct nand_op_instr *instr;
2114 char *prefix = " ";
2115 unsigned int i;
2116
2117 pr_debug("executing subop:\n");
2118
2119 for (i = 0; i < ctx->ninstrs; i++) {
2120 instr = &ctx->instrs[i];
2121
2122 if (instr == &ctx->subop.instrs[0])
2123 prefix = " ->";
2124
2125 nand_op_trace(prefix, instr);
2126
2127 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2128 prefix = " ";
2129 }
2130}
2131#else
2132static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2133{
2134 /* NOP */
2135}
2136#endif
2137
2138static int nand_op_parser_cmp_ctx(const struct nand_op_parser_ctx *a,
2139 const struct nand_op_parser_ctx *b)
2140{
2141 if (a->subop.ninstrs < b->subop.ninstrs)
2142 return -1;
2143 else if (a->subop.ninstrs > b->subop.ninstrs)
2144 return 1;
2145
2146 if (a->subop.last_instr_end_off < b->subop.last_instr_end_off)
2147 return -1;
2148 else if (a->subop.last_instr_end_off > b->subop.last_instr_end_off)
2149 return 1;
2150
2151 return 0;
2152}
2153
2154/**
2155 * nand_op_parser_exec_op - exec_op parser
2156 * @chip: the NAND chip
2157 * @parser: patterns description provided by the controller driver
2158 * @op: the NAND operation to address
2159 * @check_only: when true, the function only checks if @op can be handled but
2160 * does not execute the operation
2161 *
2162 * Helper function designed to ease integration of NAND controller drivers that
2163 * only support a limited set of instruction sequences. The supported sequences
2164 * are described in @parser, and the framework takes care of splitting @op into
2165 * multiple sub-operations (if required) and pass them back to the ->exec()
2166 * callback of the matching pattern if @check_only is set to false.
2167 *
2168 * NAND controller drivers should call this function from their own ->exec_op()
2169 * implementation.
2170 *
2171 * Returns 0 on success, a negative error code otherwise. A failure can be
2172 * caused by an unsupported operation (none of the supported patterns is able
2173 * to handle the requested operation), or an error returned by one of the
2174 * matching pattern->exec() hook.
2175 */
2176int nand_op_parser_exec_op(struct nand_chip *chip,
2177 const struct nand_op_parser *parser,
2178 const struct nand_operation *op, bool check_only)
2179{
2180 struct nand_op_parser_ctx ctx = {
2181 .subop.instrs = op->instrs,
2182 .instrs = op->instrs,
2183 .ninstrs = op->ninstrs,
2184 };
2185 unsigned int i;
2186
2187 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2188 const struct nand_op_parser_pattern *pattern;
2189 struct nand_op_parser_ctx best_ctx;
2190 int ret, best_pattern = -1;
2191
2192 for (i = 0; i < parser->npatterns; i++) {
2193 struct nand_op_parser_ctx test_ctx = ctx;
2194
2195 pattern = &parser->patterns[i];
2196 if (!nand_op_parser_match_pat(pattern, &test_ctx))
2197 continue;
2198
2199 if (best_pattern >= 0 &&
2200 nand_op_parser_cmp_ctx(&test_ctx, &best_ctx) <= 0)
2201 continue;
2202
2203 best_pattern = i;
2204 best_ctx = test_ctx;
2205 }
2206
2207 if (best_pattern < 0) {
2208 pr_debug("->exec_op() parser: pattern not found!\n");
2209 return -ENOTSUPP;
2210 }
2211
2212 ctx = best_ctx;
2213 nand_op_parser_trace(&ctx);
2214
2215 if (!check_only) {
2216 pattern = &parser->patterns[best_pattern];
2217 ret = pattern->exec(chip, &ctx.subop);
2218 if (ret)
2219 return ret;
2220 }
2221
2222 /*
2223 * Update the context structure by pointing to the start of the
2224 * next subop.
2225 */
2226 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2227 if (ctx.subop.last_instr_end_off)
2228 ctx.subop.instrs -= 1;
2229
2230 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2231 }
2232
2233 return 0;
2234}
2235EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2236
2237static bool nand_instr_is_data(const struct nand_op_instr *instr)
2238{
2239 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2240 instr->type == NAND_OP_DATA_OUT_INSTR);
2241}
2242
2243static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2244 unsigned int instr_idx)
2245{
2246 return subop && instr_idx < subop->ninstrs;
2247}
2248
2249static unsigned int nand_subop_get_start_off(const struct nand_subop *subop,
2250 unsigned int instr_idx)
2251{
2252 if (instr_idx)
2253 return 0;
2254
2255 return subop->first_instr_start_off;
2256}
2257
2258/**
2259 * nand_subop_get_addr_start_off - Get the start offset in an address array
2260 * @subop: The entire sub-operation
2261 * @instr_idx: Index of the instruction inside the sub-operation
2262 *
2263 * During driver development, one could be tempted to directly use the
2264 * ->addr.addrs field of address instructions. This is wrong as address
2265 * instructions might be split.
2266 *
2267 * Given an address instruction, returns the offset of the first cycle to issue.
2268 */
2269unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2270 unsigned int instr_idx)
2271{
2272 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2273 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2274 return 0;
2275
2276 return nand_subop_get_start_off(subop, instr_idx);
2277}
2278EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2279
2280/**
2281 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2282 * @subop: The entire sub-operation
2283 * @instr_idx: Index of the instruction inside the sub-operation
2284 *
2285 * During driver development, one could be tempted to directly use the
2286 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2287 * might be split.
2288 *
2289 * Given an address instruction, returns the number of address cycle to issue.
2290 */
2291unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2292 unsigned int instr_idx)
2293{
2294 int start_off, end_off;
2295
2296 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2297 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR))
2298 return 0;
2299
2300 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2301
2302 if (instr_idx == subop->ninstrs - 1 &&
2303 subop->last_instr_end_off)
2304 end_off = subop->last_instr_end_off;
2305 else
2306 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2307
2308 return end_off - start_off;
2309}
2310EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2311
2312/**
2313 * nand_subop_get_data_start_off - Get the start offset in a data array
2314 * @subop: The entire sub-operation
2315 * @instr_idx: Index of the instruction inside the sub-operation
2316 *
2317 * During driver development, one could be tempted to directly use the
2318 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2319 * instructions might be split.
2320 *
2321 * Given a data instruction, returns the offset to start from.
2322 */
2323unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop,
2324 unsigned int instr_idx)
2325{
2326 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2327 !nand_instr_is_data(&subop->instrs[instr_idx])))
2328 return 0;
2329
2330 return nand_subop_get_start_off(subop, instr_idx);
2331}
2332EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2333
2334/**
2335 * nand_subop_get_data_len - Get the number of bytes to retrieve
2336 * @subop: The entire sub-operation
2337 * @instr_idx: Index of the instruction inside the sub-operation
2338 *
2339 * During driver development, one could be tempted to directly use the
2340 * ->data->len field of a data instruction. This is wrong as data instructions
2341 * might be split.
2342 *
2343 * Returns the length of the chunk of data to send/receive.
2344 */
2345unsigned int nand_subop_get_data_len(const struct nand_subop *subop,
2346 unsigned int instr_idx)
2347{
2348 int start_off = 0, end_off;
2349
2350 if (WARN_ON(!nand_subop_instr_is_valid(subop, instr_idx) ||
2351 !nand_instr_is_data(&subop->instrs[instr_idx])))
2352 return 0;
2353
2354 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2355
2356 if (instr_idx == subop->ninstrs - 1 &&
2357 subop->last_instr_end_off)
2358 end_off = subop->last_instr_end_off;
2359 else
2360 end_off = subop->instrs[instr_idx].ctx.data.len;
2361
2362 return end_off - start_off;
2363}
2364EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2365
2366/**
2367 * nand_reset - Reset and initialize a NAND device
2368 * @chip: The NAND chip
2369 * @chipnr: Internal die id
2370 *
2371 * Save the timings data structure, then apply SDR timings mode 0 (see
2372 * nand_reset_data_interface for details), do the reset operation, and
2373 * apply back the previous timings.
2374 *
2375 * Returns 0 on success, a negative error code otherwise.
2376 */
2377int nand_reset(struct nand_chip *chip, int chipnr)
2378{
2379 struct nand_data_interface saved_data_intf = chip->data_interface;
2380 int ret;
2381
2382 ret = nand_reset_data_interface(chip, chipnr);
2383 if (ret)
2384 return ret;
2385
2386 /*
2387 * The CS line has to be released before we can apply the new NAND
2388 * interface settings, hence this weird nand_select_target()
2389 * nand_deselect_target() dance.
2390 */
2391 nand_select_target(chip, chipnr);
2392 ret = nand_reset_op(chip);
2393 nand_deselect_target(chip);
2394 if (ret)
2395 return ret;
2396
2397 /*
2398 * A nand_reset_data_interface() put both the NAND chip and the NAND
2399 * controller in timings mode 0. If the default mode for this chip is
2400 * also 0, no need to proceed to the change again. Plus, at probe time,
2401 * nand_setup_data_interface() uses ->set/get_features() which would
2402 * fail anyway as the parameter page is not available yet.
2403 */
2404 if (!chip->onfi_timing_mode_default)
2405 return 0;
2406
2407 chip->data_interface = saved_data_intf;
2408 ret = nand_setup_data_interface(chip, chipnr);
2409 if (ret)
2410 return ret;
2411
2412 return 0;
2413}
2414EXPORT_SYMBOL_GPL(nand_reset);
2415
2416/**
2417 * nand_get_features - wrapper to perform a GET_FEATURE
2418 * @chip: NAND chip info structure
2419 * @addr: feature address
2420 * @subfeature_param: the subfeature parameters, a four bytes array
2421 *
2422 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2423 * operation cannot be handled.
2424 */
2425int nand_get_features(struct nand_chip *chip, int addr,
2426 u8 *subfeature_param)
2427{
2428 if (!nand_supports_get_features(chip, addr))
2429 return -ENOTSUPP;
2430
2431 if (chip->legacy.get_features)
2432 return chip->legacy.get_features(chip, addr, subfeature_param);
2433
2434 return nand_get_features_op(chip, addr, subfeature_param);
2435}
2436
2437/**
2438 * nand_set_features - wrapper to perform a SET_FEATURE
2439 * @chip: NAND chip info structure
2440 * @addr: feature address
2441 * @subfeature_param: the subfeature parameters, a four bytes array
2442 *
2443 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
2444 * operation cannot be handled.
2445 */
2446int nand_set_features(struct nand_chip *chip, int addr,
2447 u8 *subfeature_param)
2448{
2449 if (!nand_supports_set_features(chip, addr))
2450 return -ENOTSUPP;
2451
2452 if (chip->legacy.set_features)
2453 return chip->legacy.set_features(chip, addr, subfeature_param);
2454
2455 return nand_set_features_op(chip, addr, subfeature_param);
2456}
2457
2458/**
2459 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2460 * @buf: buffer to test
2461 * @len: buffer length
2462 * @bitflips_threshold: maximum number of bitflips
2463 *
2464 * Check if a buffer contains only 0xff, which means the underlying region
2465 * has been erased and is ready to be programmed.
2466 * The bitflips_threshold specify the maximum number of bitflips before
2467 * considering the region is not erased.
2468 * Note: The logic of this function has been extracted from the memweight
2469 * implementation, except that nand_check_erased_buf function exit before
2470 * testing the whole buffer if the number of bitflips exceed the
2471 * bitflips_threshold value.
2472 *
2473 * Returns a positive number of bitflips less than or equal to
2474 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2475 * threshold.
2476 */
2477static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2478{
2479 const unsigned char *bitmap = buf;
2480 int bitflips = 0;
2481 int weight;
2482
2483 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2484 len--, bitmap++) {
2485 weight = hweight8(*bitmap);
2486 bitflips += BITS_PER_BYTE - weight;
2487 if (unlikely(bitflips > bitflips_threshold))
2488 return -EBADMSG;
2489 }
2490
2491 for (; len >= sizeof(long);
2492 len -= sizeof(long), bitmap += sizeof(long)) {
2493 unsigned long d = *((unsigned long *)bitmap);
2494 if (d == ~0UL)
2495 continue;
2496 weight = hweight_long(d);
2497 bitflips += BITS_PER_LONG - weight;
2498 if (unlikely(bitflips > bitflips_threshold))
2499 return -EBADMSG;
2500 }
2501
2502 for (; len > 0; len--, bitmap++) {
2503 weight = hweight8(*bitmap);
2504 bitflips += BITS_PER_BYTE - weight;
2505 if (unlikely(bitflips > bitflips_threshold))
2506 return -EBADMSG;
2507 }
2508
2509 return bitflips;
2510}
2511
2512/**
2513 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2514 * 0xff data
2515 * @data: data buffer to test
2516 * @datalen: data length
2517 * @ecc: ECC buffer
2518 * @ecclen: ECC length
2519 * @extraoob: extra OOB buffer
2520 * @extraooblen: extra OOB length
2521 * @bitflips_threshold: maximum number of bitflips
2522 *
2523 * Check if a data buffer and its associated ECC and OOB data contains only
2524 * 0xff pattern, which means the underlying region has been erased and is
2525 * ready to be programmed.
2526 * The bitflips_threshold specify the maximum number of bitflips before
2527 * considering the region as not erased.
2528 *
2529 * Note:
2530 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2531 * different from the NAND page size. When fixing bitflips, ECC engines will
2532 * report the number of errors per chunk, and the NAND core infrastructure
2533 * expect you to return the maximum number of bitflips for the whole page.
2534 * This is why you should always use this function on a single chunk and
2535 * not on the whole page. After checking each chunk you should update your
2536 * max_bitflips value accordingly.
2537 * 2/ When checking for bitflips in erased pages you should not only check
2538 * the payload data but also their associated ECC data, because a user might
2539 * have programmed almost all bits to 1 but a few. In this case, we
2540 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2541 * this case.
2542 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2543 * data are protected by the ECC engine.
2544 * It could also be used if you support subpages and want to attach some
2545 * extra OOB data to an ECC chunk.
2546 *
2547 * Returns a positive number of bitflips less than or equal to
2548 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2549 * threshold. In case of success, the passed buffers are filled with 0xff.
2550 */
2551int nand_check_erased_ecc_chunk(void *data, int datalen,
2552 void *ecc, int ecclen,
2553 void *extraoob, int extraooblen,
2554 int bitflips_threshold)
2555{
2556 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2557
2558 data_bitflips = nand_check_erased_buf(data, datalen,
2559 bitflips_threshold);
2560 if (data_bitflips < 0)
2561 return data_bitflips;
2562
2563 bitflips_threshold -= data_bitflips;
2564
2565 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2566 if (ecc_bitflips < 0)
2567 return ecc_bitflips;
2568
2569 bitflips_threshold -= ecc_bitflips;
2570
2571 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2572 bitflips_threshold);
2573 if (extraoob_bitflips < 0)
2574 return extraoob_bitflips;
2575
2576 if (data_bitflips)
2577 memset(data, 0xff, datalen);
2578
2579 if (ecc_bitflips)
2580 memset(ecc, 0xff, ecclen);
2581
2582 if (extraoob_bitflips)
2583 memset(extraoob, 0xff, extraooblen);
2584
2585 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2586}
2587EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2588
2589/**
2590 * nand_read_page_raw_notsupp - dummy read raw page function
2591 * @chip: nand chip info structure
2592 * @buf: buffer to store read data
2593 * @oob_required: caller requires OOB data read to chip->oob_poi
2594 * @page: page number to read
2595 *
2596 * Returns -ENOTSUPP unconditionally.
2597 */
2598int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf,
2599 int oob_required, int page)
2600{
2601 return -ENOTSUPP;
2602}
2603
2604/**
2605 * nand_read_page_raw - [INTERN] read raw page data without ecc
2606 * @chip: nand chip info structure
2607 * @buf: buffer to store read data
2608 * @oob_required: caller requires OOB data read to chip->oob_poi
2609 * @page: page number to read
2610 *
2611 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2612 */
2613int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required,
2614 int page)
2615{
2616 struct mtd_info *mtd = nand_to_mtd(chip);
2617 int ret;
2618
2619 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2620 if (ret)
2621 return ret;
2622
2623 if (oob_required) {
2624 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2625 false);
2626 if (ret)
2627 return ret;
2628 }
2629
2630 return 0;
2631}
2632EXPORT_SYMBOL(nand_read_page_raw);
2633
2634/**
2635 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
2636 * @chip: nand chip info structure
2637 * @buf: buffer to store read data
2638 * @oob_required: caller requires OOB data read to chip->oob_poi
2639 * @page: page number to read
2640 *
2641 * We need a special oob layout and handling even when OOB isn't used.
2642 */
2643static int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf,
2644 int oob_required, int page)
2645{
2646 struct mtd_info *mtd = nand_to_mtd(chip);
2647 int eccsize = chip->ecc.size;
2648 int eccbytes = chip->ecc.bytes;
2649 uint8_t *oob = chip->oob_poi;
2650 int steps, size, ret;
2651
2652 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2653 if (ret)
2654 return ret;
2655
2656 for (steps = chip->ecc.steps; steps > 0; steps--) {
2657 ret = nand_read_data_op(chip, buf, eccsize, false);
2658 if (ret)
2659 return ret;
2660
2661 buf += eccsize;
2662
2663 if (chip->ecc.prepad) {
2664 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2665 false);
2666 if (ret)
2667 return ret;
2668
2669 oob += chip->ecc.prepad;
2670 }
2671
2672 ret = nand_read_data_op(chip, oob, eccbytes, false);
2673 if (ret)
2674 return ret;
2675
2676 oob += eccbytes;
2677
2678 if (chip->ecc.postpad) {
2679 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2680 false);
2681 if (ret)
2682 return ret;
2683
2684 oob += chip->ecc.postpad;
2685 }
2686 }
2687
2688 size = mtd->oobsize - (oob - chip->oob_poi);
2689 if (size) {
2690 ret = nand_read_data_op(chip, oob, size, false);
2691 if (ret)
2692 return ret;
2693 }
2694
2695 return 0;
2696}
2697
2698/**
2699 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2700 * @chip: nand chip info structure
2701 * @buf: buffer to store read data
2702 * @oob_required: caller requires OOB data read to chip->oob_poi
2703 * @page: page number to read
2704 */
2705static int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf,
2706 int oob_required, int page)
2707{
2708 struct mtd_info *mtd = nand_to_mtd(chip);
2709 int i, eccsize = chip->ecc.size, ret;
2710 int eccbytes = chip->ecc.bytes;
2711 int eccsteps = chip->ecc.steps;
2712 uint8_t *p = buf;
2713 uint8_t *ecc_calc = chip->ecc.calc_buf;
2714 uint8_t *ecc_code = chip->ecc.code_buf;
2715 unsigned int max_bitflips = 0;
2716
2717 chip->ecc.read_page_raw(chip, buf, 1, page);
2718
2719 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2720 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2721
2722 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2723 chip->ecc.total);
2724 if (ret)
2725 return ret;
2726
2727 eccsteps = chip->ecc.steps;
2728 p = buf;
2729
2730 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2731 int stat;
2732
2733 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2734 if (stat < 0) {
2735 mtd->ecc_stats.failed++;
2736 } else {
2737 mtd->ecc_stats.corrected += stat;
2738 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2739 }
2740 }
2741 return max_bitflips;
2742}
2743
2744/**
2745 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2746 * @chip: nand chip info structure
2747 * @data_offs: offset of requested data within the page
2748 * @readlen: data length
2749 * @bufpoi: buffer to store read data
2750 * @page: page number to read
2751 */
2752static int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs,
2753 uint32_t readlen, uint8_t *bufpoi, int page)
2754{
2755 struct mtd_info *mtd = nand_to_mtd(chip);
2756 int start_step, end_step, num_steps, ret;
2757 uint8_t *p;
2758 int data_col_addr, i, gaps = 0;
2759 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2760 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2761 int index, section = 0;
2762 unsigned int max_bitflips = 0;
2763 struct mtd_oob_region oobregion = { };
2764
2765 /* Column address within the page aligned to ECC size (256bytes) */
2766 start_step = data_offs / chip->ecc.size;
2767 end_step = (data_offs + readlen - 1) / chip->ecc.size;
2768 num_steps = end_step - start_step + 1;
2769 index = start_step * chip->ecc.bytes;
2770
2771 /* Data size aligned to ECC ecc.size */
2772 datafrag_len = num_steps * chip->ecc.size;
2773 eccfrag_len = num_steps * chip->ecc.bytes;
2774
2775 data_col_addr = start_step * chip->ecc.size;
2776 /* If we read not a page aligned data */
2777 p = bufpoi + data_col_addr;
2778 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
2779 if (ret)
2780 return ret;
2781
2782 /* Calculate ECC */
2783 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
2784 chip->ecc.calculate(chip, p, &chip->ecc.calc_buf[i]);
2785
2786 /*
2787 * The performance is faster if we position offsets according to
2788 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
2789 */
2790 ret = mtd_ooblayout_find_eccregion(mtd, index, &section, &oobregion);
2791 if (ret)
2792 return ret;
2793
2794 if (oobregion.length < eccfrag_len)
2795 gaps = 1;
2796
2797 if (gaps) {
2798 ret = nand_change_read_column_op(chip, mtd->writesize,
2799 chip->oob_poi, mtd->oobsize,
2800 false);
2801 if (ret)
2802 return ret;
2803 } else {
2804 /*
2805 * Send the command to read the particular ECC bytes take care
2806 * about buswidth alignment in read_buf.
2807 */
2808 aligned_pos = oobregion.offset & ~(busw - 1);
2809 aligned_len = eccfrag_len;
2810 if (oobregion.offset & (busw - 1))
2811 aligned_len++;
2812 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
2813 (busw - 1))
2814 aligned_len++;
2815
2816 ret = nand_change_read_column_op(chip,
2817 mtd->writesize + aligned_pos,
2818 &chip->oob_poi[aligned_pos],
2819 aligned_len, false);
2820 if (ret)
2821 return ret;
2822 }
2823
2824 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
2825 chip->oob_poi, index, eccfrag_len);
2826 if (ret)
2827 return ret;
2828
2829 p = bufpoi + data_col_addr;
2830 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
2831 int stat;
2832
2833 stat = chip->ecc.correct(chip, p, &chip->ecc.code_buf[i],
2834 &chip->ecc.calc_buf[i]);
2835 if (stat == -EBADMSG &&
2836 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2837 /* check for empty pages with bitflips */
2838 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2839 &chip->ecc.code_buf[i],
2840 chip->ecc.bytes,
2841 NULL, 0,
2842 chip->ecc.strength);
2843 }
2844
2845 if (stat < 0) {
2846 mtd->ecc_stats.failed++;
2847 } else {
2848 mtd->ecc_stats.corrected += stat;
2849 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2850 }
2851 }
2852 return max_bitflips;
2853}
2854
2855/**
2856 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2857 * @chip: nand chip info structure
2858 * @buf: buffer to store read data
2859 * @oob_required: caller requires OOB data read to chip->oob_poi
2860 * @page: page number to read
2861 *
2862 * Not for syndrome calculating ECC controllers which need a special oob layout.
2863 */
2864static int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf,
2865 int oob_required, int page)
2866{
2867 struct mtd_info *mtd = nand_to_mtd(chip);
2868 int i, eccsize = chip->ecc.size, ret;
2869 int eccbytes = chip->ecc.bytes;
2870 int eccsteps = chip->ecc.steps;
2871 uint8_t *p = buf;
2872 uint8_t *ecc_calc = chip->ecc.calc_buf;
2873 uint8_t *ecc_code = chip->ecc.code_buf;
2874 unsigned int max_bitflips = 0;
2875
2876 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2877 if (ret)
2878 return ret;
2879
2880 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2881 chip->ecc.hwctl(chip, NAND_ECC_READ);
2882
2883 ret = nand_read_data_op(chip, p, eccsize, false);
2884 if (ret)
2885 return ret;
2886
2887 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2888 }
2889
2890 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2891 if (ret)
2892 return ret;
2893
2894 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2895 chip->ecc.total);
2896 if (ret)
2897 return ret;
2898
2899 eccsteps = chip->ecc.steps;
2900 p = buf;
2901
2902 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2903 int stat;
2904
2905 stat = chip->ecc.correct(chip, p, &ecc_code[i], &ecc_calc[i]);
2906 if (stat == -EBADMSG &&
2907 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2908 /* check for empty pages with bitflips */
2909 stat = nand_check_erased_ecc_chunk(p, eccsize,
2910 &ecc_code[i], eccbytes,
2911 NULL, 0,
2912 chip->ecc.strength);
2913 }
2914
2915 if (stat < 0) {
2916 mtd->ecc_stats.failed++;
2917 } else {
2918 mtd->ecc_stats.corrected += stat;
2919 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2920 }
2921 }
2922 return max_bitflips;
2923}
2924
2925/**
2926 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2927 * @chip: nand chip info structure
2928 * @buf: buffer to store read data
2929 * @oob_required: caller requires OOB data read to chip->oob_poi
2930 * @page: page number to read
2931 *
2932 * Hardware ECC for large page chips, require OOB to be read first. For this
2933 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2934 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2935 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2936 * the data area, by overwriting the NAND manufacturer bad block markings.
2937 */
2938static int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf,
2939 int oob_required, int page)
2940{
2941 struct mtd_info *mtd = nand_to_mtd(chip);
2942 int i, eccsize = chip->ecc.size, ret;
2943 int eccbytes = chip->ecc.bytes;
2944 int eccsteps = chip->ecc.steps;
2945 uint8_t *p = buf;
2946 uint8_t *ecc_code = chip->ecc.code_buf;
2947 uint8_t *ecc_calc = chip->ecc.calc_buf;
2948 unsigned int max_bitflips = 0;
2949
2950 /* Read the OOB area first */
2951 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2952 if (ret)
2953 return ret;
2954
2955 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2956 if (ret)
2957 return ret;
2958
2959 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2960 chip->ecc.total);
2961 if (ret)
2962 return ret;
2963
2964 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2965 int stat;
2966
2967 chip->ecc.hwctl(chip, NAND_ECC_READ);
2968
2969 ret = nand_read_data_op(chip, p, eccsize, false);
2970 if (ret)
2971 return ret;
2972
2973 chip->ecc.calculate(chip, p, &ecc_calc[i]);
2974
2975 stat = chip->ecc.correct(chip, p, &ecc_code[i], NULL);
2976 if (stat == -EBADMSG &&
2977 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2978 /* check for empty pages with bitflips */
2979 stat = nand_check_erased_ecc_chunk(p, eccsize,
2980 &ecc_code[i], eccbytes,
2981 NULL, 0,
2982 chip->ecc.strength);
2983 }
2984
2985 if (stat < 0) {
2986 mtd->ecc_stats.failed++;
2987 } else {
2988 mtd->ecc_stats.corrected += stat;
2989 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2990 }
2991 }
2992 return max_bitflips;
2993}
2994
2995/**
2996 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2997 * @chip: nand chip info structure
2998 * @buf: buffer to store read data
2999 * @oob_required: caller requires OOB data read to chip->oob_poi
3000 * @page: page number to read
3001 *
3002 * The hw generator calculates the error syndrome automatically. Therefore we
3003 * need a special oob layout and handling.
3004 */
3005static int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf,
3006 int oob_required, int page)
3007{
3008 struct mtd_info *mtd = nand_to_mtd(chip);
3009 int ret, i, eccsize = chip->ecc.size;
3010 int eccbytes = chip->ecc.bytes;
3011 int eccsteps = chip->ecc.steps;
3012 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3013 uint8_t *p = buf;
3014 uint8_t *oob = chip->oob_poi;
3015 unsigned int max_bitflips = 0;
3016
3017 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3018 if (ret)
3019 return ret;
3020
3021 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3022 int stat;
3023
3024 chip->ecc.hwctl(chip, NAND_ECC_READ);
3025
3026 ret = nand_read_data_op(chip, p, eccsize, false);
3027 if (ret)
3028 return ret;
3029
3030 if (chip->ecc.prepad) {
3031 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3032 false);
3033 if (ret)
3034 return ret;
3035
3036 oob += chip->ecc.prepad;
3037 }
3038
3039 chip->ecc.hwctl(chip, NAND_ECC_READSYN);
3040
3041 ret = nand_read_data_op(chip, oob, eccbytes, false);
3042 if (ret)
3043 return ret;
3044
3045 stat = chip->ecc.correct(chip, p, oob, NULL);
3046
3047 oob += eccbytes;
3048
3049 if (chip->ecc.postpad) {
3050 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3051 false);
3052 if (ret)
3053 return ret;
3054
3055 oob += chip->ecc.postpad;
3056 }
3057
3058 if (stat == -EBADMSG &&
3059 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3060 /* check for empty pages with bitflips */
3061 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3062 oob - eccpadbytes,
3063 eccpadbytes,
3064 NULL, 0,
3065 chip->ecc.strength);
3066 }
3067
3068 if (stat < 0) {
3069 mtd->ecc_stats.failed++;
3070 } else {
3071 mtd->ecc_stats.corrected += stat;
3072 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3073 }
3074 }
3075
3076 /* Calculate remaining oob bytes */
3077 i = mtd->oobsize - (oob - chip->oob_poi);
3078 if (i) {
3079 ret = nand_read_data_op(chip, oob, i, false);
3080 if (ret)
3081 return ret;
3082 }
3083
3084 return max_bitflips;
3085}
3086
3087/**
3088 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3089 * @chip: NAND chip object
3090 * @oob: oob destination address
3091 * @ops: oob ops structure
3092 * @len: size of oob to transfer
3093 */
3094static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
3095 struct mtd_oob_ops *ops, size_t len)
3096{
3097 struct mtd_info *mtd = nand_to_mtd(chip);
3098 int ret;
3099
3100 switch (ops->mode) {
3101
3102 case MTD_OPS_PLACE_OOB:
3103 case MTD_OPS_RAW:
3104 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3105 return oob + len;
3106
3107 case MTD_OPS_AUTO_OOB:
3108 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3109 ops->ooboffs, len);
3110 BUG_ON(ret);
3111 return oob + len;
3112
3113 default:
3114 BUG();
3115 }
3116 return NULL;
3117}
3118
3119/**
3120 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3121 * @chip: NAND chip object
3122 * @retry_mode: the retry mode to use
3123 *
3124 * Some vendors supply a special command to shift the Vt threshold, to be used
3125 * when there are too many bitflips in a page (i.e., ECC error). After setting
3126 * a new threshold, the host should retry reading the page.
3127 */
3128static int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
3129{
3130 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3131
3132 if (retry_mode >= chip->read_retries)
3133 return -EINVAL;
3134
3135 if (!chip->setup_read_retry)
3136 return -EOPNOTSUPP;
3137
3138 return chip->setup_read_retry(chip, retry_mode);
3139}
3140
3141static void nand_wait_readrdy(struct nand_chip *chip)
3142{
3143 const struct nand_sdr_timings *sdr;
3144
3145 if (!(chip->options & NAND_NEED_READRDY))
3146 return;
3147
3148 sdr = nand_get_sdr_timings(&chip->data_interface);
3149 WARN_ON(nand_wait_rdy_op(chip, PSEC_TO_MSEC(sdr->tR_max), 0));
3150}
3151
3152/**
3153 * nand_do_read_ops - [INTERN] Read data with ECC
3154 * @chip: NAND chip object
3155 * @from: offset to read from
3156 * @ops: oob ops structure
3157 *
3158 * Internal function. Called with chip held.
3159 */
3160static int nand_do_read_ops(struct nand_chip *chip, loff_t from,
3161 struct mtd_oob_ops *ops)
3162{
3163 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3164 struct mtd_info *mtd = nand_to_mtd(chip);
3165 int ret = 0;
3166 uint32_t readlen = ops->len;
3167 uint32_t oobreadlen = ops->ooblen;
3168 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3169
3170 uint8_t *bufpoi, *oob, *buf;
3171 int use_bufpoi;
3172 unsigned int max_bitflips = 0;
3173 int retry_mode = 0;
3174 bool ecc_fail = false;
3175
3176 chipnr = (int)(from >> chip->chip_shift);
3177 nand_select_target(chip, chipnr);
3178
3179 realpage = (int)(from >> chip->page_shift);
3180 page = realpage & chip->pagemask;
3181
3182 col = (int)(from & (mtd->writesize - 1));
3183
3184 buf = ops->datbuf;
3185 oob = ops->oobbuf;
3186 oob_required = oob ? 1 : 0;
3187
3188 while (1) {
3189 unsigned int ecc_failures = mtd->ecc_stats.failed;
3190
3191 bytes = min(mtd->writesize - col, readlen);
3192 aligned = (bytes == mtd->writesize);
3193
3194 if (!aligned)
3195 use_bufpoi = 1;
3196 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3197 use_bufpoi = !virt_addr_valid(buf) ||
3198 !IS_ALIGNED((unsigned long)buf,
3199 chip->buf_align);
3200 else
3201 use_bufpoi = 0;
3202
3203 /* Is the current page in the buffer? */
3204 if (realpage != chip->pagecache.page || oob) {
3205 bufpoi = use_bufpoi ? chip->data_buf : buf;
3206
3207 if (use_bufpoi && aligned)
3208 pr_debug("%s: using read bounce buffer for buf@%p\n",
3209 __func__, buf);
3210
3211read_retry:
3212 /*
3213 * Now read the page into the buffer. Absent an error,
3214 * the read methods return max bitflips per ecc step.
3215 */
3216 if (unlikely(ops->mode == MTD_OPS_RAW))
3217 ret = chip->ecc.read_page_raw(chip, bufpoi,
3218 oob_required,
3219 page);
3220 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3221 !oob)
3222 ret = chip->ecc.read_subpage(chip, col, bytes,
3223 bufpoi, page);
3224 else
3225 ret = chip->ecc.read_page(chip, bufpoi,
3226 oob_required, page);
3227 if (ret < 0) {
3228 if (use_bufpoi)
3229 /* Invalidate page cache */
3230 chip->pagecache.page = -1;
3231 break;
3232 }
3233
3234 /* Transfer not aligned data */
3235 if (use_bufpoi) {
3236 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3237 !(mtd->ecc_stats.failed - ecc_failures) &&
3238 (ops->mode != MTD_OPS_RAW)) {
3239 chip->pagecache.page = realpage;
3240 chip->pagecache.bitflips = ret;
3241 } else {
3242 /* Invalidate page cache */
3243 chip->pagecache.page = -1;
3244 }
3245 memcpy(buf, chip->data_buf + col, bytes);
3246 }
3247
3248 if (unlikely(oob)) {
3249 int toread = min(oobreadlen, max_oobsize);
3250
3251 if (toread) {
3252 oob = nand_transfer_oob(chip, oob, ops,
3253 toread);
3254 oobreadlen -= toread;
3255 }
3256 }
3257
3258 nand_wait_readrdy(chip);
3259
3260 if (mtd->ecc_stats.failed - ecc_failures) {
3261 if (retry_mode + 1 < chip->read_retries) {
3262 retry_mode++;
3263 ret = nand_setup_read_retry(chip,
3264 retry_mode);
3265 if (ret < 0)
3266 break;
3267
3268 /* Reset failures; retry */
3269 mtd->ecc_stats.failed = ecc_failures;
3270 goto read_retry;
3271 } else {
3272 /* No more retry modes; real failure */
3273 ecc_fail = true;
3274 }
3275 }
3276
3277 buf += bytes;
3278 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3279 } else {
3280 memcpy(buf, chip->data_buf + col, bytes);
3281 buf += bytes;
3282 max_bitflips = max_t(unsigned int, max_bitflips,
3283 chip->pagecache.bitflips);
3284 }
3285
3286 readlen -= bytes;
3287
3288 /* Reset to retry mode 0 */
3289 if (retry_mode) {
3290 ret = nand_setup_read_retry(chip, 0);
3291 if (ret < 0)
3292 break;
3293 retry_mode = 0;
3294 }
3295
3296 if (!readlen)
3297 break;
3298
3299 /* For subsequent reads align to page boundary */
3300 col = 0;
3301 /* Increment page address */
3302 realpage++;
3303
3304 page = realpage & chip->pagemask;
3305 /* Check, if we cross a chip boundary */
3306 if (!page) {
3307 chipnr++;
3308 nand_deselect_target(chip);
3309 nand_select_target(chip, chipnr);
3310 }
3311 }
3312 nand_deselect_target(chip);
3313
3314 ops->retlen = ops->len - (size_t) readlen;
3315 if (oob)
3316 ops->oobretlen = ops->ooblen - oobreadlen;
3317
3318 if (ret < 0)
3319 return ret;
3320
3321 if (ecc_fail)
3322 return -EBADMSG;
3323
3324 return max_bitflips;
3325}
3326
3327/**
3328 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3329 * @chip: nand chip info structure
3330 * @page: page number to read
3331 */
3332int nand_read_oob_std(struct nand_chip *chip, int page)
3333{
3334 struct mtd_info *mtd = nand_to_mtd(chip);
3335
3336 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3337}
3338EXPORT_SYMBOL(nand_read_oob_std);
3339
3340/**
3341 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3342 * with syndromes
3343 * @chip: nand chip info structure
3344 * @page: page number to read
3345 */
3346static int nand_read_oob_syndrome(struct nand_chip *chip, int page)
3347{
3348 struct mtd_info *mtd = nand_to_mtd(chip);
3349 int length = mtd->oobsize;
3350 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3351 int eccsize = chip->ecc.size;
3352 uint8_t *bufpoi = chip->oob_poi;
3353 int i, toread, sndrnd = 0, pos, ret;
3354
3355 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3356 if (ret)
3357 return ret;
3358
3359 for (i = 0; i < chip->ecc.steps; i++) {
3360 if (sndrnd) {
3361 int ret;
3362
3363 pos = eccsize + i * (eccsize + chunk);
3364 if (mtd->writesize > 512)
3365 ret = nand_change_read_column_op(chip, pos,
3366 NULL, 0,
3367 false);
3368 else
3369 ret = nand_read_page_op(chip, page, pos, NULL,
3370 0);
3371
3372 if (ret)
3373 return ret;
3374 } else
3375 sndrnd = 1;
3376 toread = min_t(int, length, chunk);
3377
3378 ret = nand_read_data_op(chip, bufpoi, toread, false);
3379 if (ret)
3380 return ret;
3381
3382 bufpoi += toread;
3383 length -= toread;
3384 }
3385 if (length > 0) {
3386 ret = nand_read_data_op(chip, bufpoi, length, false);
3387 if (ret)
3388 return ret;
3389 }
3390
3391 return 0;
3392}
3393
3394/**
3395 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3396 * @chip: nand chip info structure
3397 * @page: page number to write
3398 */
3399int nand_write_oob_std(struct nand_chip *chip, int page)
3400{
3401 struct mtd_info *mtd = nand_to_mtd(chip);
3402
3403 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3404 mtd->oobsize);
3405}
3406EXPORT_SYMBOL(nand_write_oob_std);
3407
3408/**
3409 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3410 * with syndrome - only for large page flash
3411 * @chip: nand chip info structure
3412 * @page: page number to write
3413 */
3414static int nand_write_oob_syndrome(struct nand_chip *chip, int page)
3415{
3416 struct mtd_info *mtd = nand_to_mtd(chip);
3417 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3418 int eccsize = chip->ecc.size, length = mtd->oobsize;
3419 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3420 const uint8_t *bufpoi = chip->oob_poi;
3421
3422 /*
3423 * data-ecc-data-ecc ... ecc-oob
3424 * or
3425 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3426 */
3427 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3428 pos = steps * (eccsize + chunk);
3429 steps = 0;
3430 } else
3431 pos = eccsize;
3432
3433 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3434 if (ret)
3435 return ret;
3436
3437 for (i = 0; i < steps; i++) {
3438 if (sndcmd) {
3439 if (mtd->writesize <= 512) {
3440 uint32_t fill = 0xFFFFFFFF;
3441
3442 len = eccsize;
3443 while (len > 0) {
3444 int num = min_t(int, len, 4);
3445
3446 ret = nand_write_data_op(chip, &fill,
3447 num, false);
3448 if (ret)
3449 return ret;
3450
3451 len -= num;
3452 }
3453 } else {
3454 pos = eccsize + i * (eccsize + chunk);
3455 ret = nand_change_write_column_op(chip, pos,
3456 NULL, 0,
3457 false);
3458 if (ret)
3459 return ret;
3460 }
3461 } else
3462 sndcmd = 1;
3463 len = min_t(int, length, chunk);
3464
3465 ret = nand_write_data_op(chip, bufpoi, len, false);
3466 if (ret)
3467 return ret;
3468
3469 bufpoi += len;
3470 length -= len;
3471 }
3472 if (length > 0) {
3473 ret = nand_write_data_op(chip, bufpoi, length, false);
3474 if (ret)
3475 return ret;
3476 }
3477
3478 return nand_prog_page_end_op(chip);
3479}
3480
3481/**
3482 * nand_do_read_oob - [INTERN] NAND read out-of-band
3483 * @chip: NAND chip object
3484 * @from: offset to read from
3485 * @ops: oob operations description structure
3486 *
3487 * NAND read out-of-band data from the spare area.
3488 */
3489static int nand_do_read_oob(struct nand_chip *chip, loff_t from,
3490 struct mtd_oob_ops *ops)
3491{
3492 struct mtd_info *mtd = nand_to_mtd(chip);
3493 unsigned int max_bitflips = 0;
3494 int page, realpage, chipnr;
3495 struct mtd_ecc_stats stats;
3496 int readlen = ops->ooblen;
3497 int len;
3498 uint8_t *buf = ops->oobbuf;
3499 int ret = 0;
3500
3501 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3502 __func__, (unsigned long long)from, readlen);
3503
3504 stats = mtd->ecc_stats;
3505
3506 len = mtd_oobavail(mtd, ops);
3507
3508 chipnr = (int)(from >> chip->chip_shift);
3509 nand_select_target(chip, chipnr);
3510
3511 /* Shift to get page */
3512 realpage = (int)(from >> chip->page_shift);
3513 page = realpage & chip->pagemask;
3514
3515 while (1) {
3516 if (ops->mode == MTD_OPS_RAW)
3517 ret = chip->ecc.read_oob_raw(chip, page);
3518 else
3519 ret = chip->ecc.read_oob(chip, page);
3520
3521 if (ret < 0)
3522 break;
3523
3524 len = min(len, readlen);
3525 buf = nand_transfer_oob(chip, buf, ops, len);
3526
3527 nand_wait_readrdy(chip);
3528
3529 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3530
3531 readlen -= len;
3532 if (!readlen)
3533 break;
3534
3535 /* Increment page address */
3536 realpage++;
3537
3538 page = realpage & chip->pagemask;
3539 /* Check, if we cross a chip boundary */
3540 if (!page) {
3541 chipnr++;
3542 nand_deselect_target(chip);
3543 nand_select_target(chip, chipnr);
3544 }
3545 }
3546 nand_deselect_target(chip);
3547
3548 ops->oobretlen = ops->ooblen - readlen;
3549
3550 if (ret < 0)
3551 return ret;
3552
3553 if (mtd->ecc_stats.failed - stats.failed)
3554 return -EBADMSG;
3555
3556 return max_bitflips;
3557}
3558
3559/**
3560 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3561 * @mtd: MTD device structure
3562 * @from: offset to read from
3563 * @ops: oob operation description structure
3564 *
3565 * NAND read data and/or out-of-band data.
3566 */
3567static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3568 struct mtd_oob_ops *ops)
3569{
3570 struct nand_chip *chip = mtd_to_nand(mtd);
3571 int ret;
3572
3573 ops->retlen = 0;
3574
3575 if (ops->mode != MTD_OPS_PLACE_OOB &&
3576 ops->mode != MTD_OPS_AUTO_OOB &&
3577 ops->mode != MTD_OPS_RAW)
3578 return -ENOTSUPP;
3579
3580 nand_get_device(chip);
3581
3582 if (!ops->datbuf)
3583 ret = nand_do_read_oob(chip, from, ops);
3584 else
3585 ret = nand_do_read_ops(chip, from, ops);
3586
3587 nand_release_device(chip);
3588 return ret;
3589}
3590
3591/**
3592 * nand_write_page_raw_notsupp - dummy raw page write function
3593 * @chip: nand chip info structure
3594 * @buf: data buffer
3595 * @oob_required: must write chip->oob_poi to OOB
3596 * @page: page number to write
3597 *
3598 * Returns -ENOTSUPP unconditionally.
3599 */
3600int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf,
3601 int oob_required, int page)
3602{
3603 return -ENOTSUPP;
3604}
3605
3606/**
3607 * nand_write_page_raw - [INTERN] raw page write function
3608 * @chip: nand chip info structure
3609 * @buf: data buffer
3610 * @oob_required: must write chip->oob_poi to OOB
3611 * @page: page number to write
3612 *
3613 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3614 */
3615int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf,
3616 int oob_required, int page)
3617{
3618 struct mtd_info *mtd = nand_to_mtd(chip);
3619 int ret;
3620
3621 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3622 if (ret)
3623 return ret;
3624
3625 if (oob_required) {
3626 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3627 false);
3628 if (ret)
3629 return ret;
3630 }
3631
3632 return nand_prog_page_end_op(chip);
3633}
3634EXPORT_SYMBOL(nand_write_page_raw);
3635
3636/**
3637 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3638 * @chip: nand chip info structure
3639 * @buf: data buffer
3640 * @oob_required: must write chip->oob_poi to OOB
3641 * @page: page number to write
3642 *
3643 * We need a special oob layout and handling even when ECC isn't checked.
3644 */
3645static int nand_write_page_raw_syndrome(struct nand_chip *chip,
3646 const uint8_t *buf, int oob_required,
3647 int page)
3648{
3649 struct mtd_info *mtd = nand_to_mtd(chip);
3650 int eccsize = chip->ecc.size;
3651 int eccbytes = chip->ecc.bytes;
3652 uint8_t *oob = chip->oob_poi;
3653 int steps, size, ret;
3654
3655 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3656 if (ret)
3657 return ret;
3658
3659 for (steps = chip->ecc.steps; steps > 0; steps--) {
3660 ret = nand_write_data_op(chip, buf, eccsize, false);
3661 if (ret)
3662 return ret;
3663
3664 buf += eccsize;
3665
3666 if (chip->ecc.prepad) {
3667 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3668 false);
3669 if (ret)
3670 return ret;
3671
3672 oob += chip->ecc.prepad;
3673 }
3674
3675 ret = nand_write_data_op(chip, oob, eccbytes, false);
3676 if (ret)
3677 return ret;
3678
3679 oob += eccbytes;
3680
3681 if (chip->ecc.postpad) {
3682 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3683 false);
3684 if (ret)
3685 return ret;
3686
3687 oob += chip->ecc.postpad;
3688 }
3689 }
3690
3691 size = mtd->oobsize - (oob - chip->oob_poi);
3692 if (size) {
3693 ret = nand_write_data_op(chip, oob, size, false);
3694 if (ret)
3695 return ret;
3696 }
3697
3698 return nand_prog_page_end_op(chip);
3699}
3700/**
3701 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3702 * @chip: nand chip info structure
3703 * @buf: data buffer
3704 * @oob_required: must write chip->oob_poi to OOB
3705 * @page: page number to write
3706 */
3707static int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf,
3708 int oob_required, int page)
3709{
3710 struct mtd_info *mtd = nand_to_mtd(chip);
3711 int i, eccsize = chip->ecc.size, ret;
3712 int eccbytes = chip->ecc.bytes;
3713 int eccsteps = chip->ecc.steps;
3714 uint8_t *ecc_calc = chip->ecc.calc_buf;
3715 const uint8_t *p = buf;
3716
3717 /* Software ECC calculation */
3718 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3719 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3720
3721 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3722 chip->ecc.total);
3723 if (ret)
3724 return ret;
3725
3726 return chip->ecc.write_page_raw(chip, buf, 1, page);
3727}
3728
3729/**
3730 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3731 * @chip: nand chip info structure
3732 * @buf: data buffer
3733 * @oob_required: must write chip->oob_poi to OOB
3734 * @page: page number to write
3735 */
3736static int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf,
3737 int oob_required, int page)
3738{
3739 struct mtd_info *mtd = nand_to_mtd(chip);
3740 int i, eccsize = chip->ecc.size, ret;
3741 int eccbytes = chip->ecc.bytes;
3742 int eccsteps = chip->ecc.steps;
3743 uint8_t *ecc_calc = chip->ecc.calc_buf;
3744 const uint8_t *p = buf;
3745
3746 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3747 if (ret)
3748 return ret;
3749
3750 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3751 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3752
3753 ret = nand_write_data_op(chip, p, eccsize, false);
3754 if (ret)
3755 return ret;
3756
3757 chip->ecc.calculate(chip, p, &ecc_calc[i]);
3758 }
3759
3760 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3761 chip->ecc.total);
3762 if (ret)
3763 return ret;
3764
3765 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3766 if (ret)
3767 return ret;
3768
3769 return nand_prog_page_end_op(chip);
3770}
3771
3772
3773/**
3774 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3775 * @chip: nand chip info structure
3776 * @offset: column address of subpage within the page
3777 * @data_len: data length
3778 * @buf: data buffer
3779 * @oob_required: must write chip->oob_poi to OOB
3780 * @page: page number to write
3781 */
3782static int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset,
3783 uint32_t data_len, const uint8_t *buf,
3784 int oob_required, int page)
3785{
3786 struct mtd_info *mtd = nand_to_mtd(chip);
3787 uint8_t *oob_buf = chip->oob_poi;
3788 uint8_t *ecc_calc = chip->ecc.calc_buf;
3789 int ecc_size = chip->ecc.size;
3790 int ecc_bytes = chip->ecc.bytes;
3791 int ecc_steps = chip->ecc.steps;
3792 uint32_t start_step = offset / ecc_size;
3793 uint32_t end_step = (offset + data_len - 1) / ecc_size;
3794 int oob_bytes = mtd->oobsize / ecc_steps;
3795 int step, ret;
3796
3797 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3798 if (ret)
3799 return ret;
3800
3801 for (step = 0; step < ecc_steps; step++) {
3802 /* configure controller for WRITE access */
3803 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3804
3805 /* write data (untouched subpages already masked by 0xFF) */
3806 ret = nand_write_data_op(chip, buf, ecc_size, false);
3807 if (ret)
3808 return ret;
3809
3810 /* mask ECC of un-touched subpages by padding 0xFF */
3811 if ((step < start_step) || (step > end_step))
3812 memset(ecc_calc, 0xff, ecc_bytes);
3813 else
3814 chip->ecc.calculate(chip, buf, ecc_calc);
3815
3816 /* mask OOB of un-touched subpages by padding 0xFF */
3817 /* if oob_required, preserve OOB metadata of written subpage */
3818 if (!oob_required || (step < start_step) || (step > end_step))
3819 memset(oob_buf, 0xff, oob_bytes);
3820
3821 buf += ecc_size;
3822 ecc_calc += ecc_bytes;
3823 oob_buf += oob_bytes;
3824 }
3825
3826 /* copy calculated ECC for whole page to chip->buffer->oob */
3827 /* this include masked-value(0xFF) for unwritten subpages */
3828 ecc_calc = chip->ecc.calc_buf;
3829 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3830 chip->ecc.total);
3831 if (ret)
3832 return ret;
3833
3834 /* write OOB buffer to NAND device */
3835 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3836 if (ret)
3837 return ret;
3838
3839 return nand_prog_page_end_op(chip);
3840}
3841
3842
3843/**
3844 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3845 * @chip: nand chip info structure
3846 * @buf: data buffer
3847 * @oob_required: must write chip->oob_poi to OOB
3848 * @page: page number to write
3849 *
3850 * The hw generator calculates the error syndrome automatically. Therefore we
3851 * need a special oob layout and handling.
3852 */
3853static int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf,
3854 int oob_required, int page)
3855{
3856 struct mtd_info *mtd = nand_to_mtd(chip);
3857 int i, eccsize = chip->ecc.size;
3858 int eccbytes = chip->ecc.bytes;
3859 int eccsteps = chip->ecc.steps;
3860 const uint8_t *p = buf;
3861 uint8_t *oob = chip->oob_poi;
3862 int ret;
3863
3864 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3865 if (ret)
3866 return ret;
3867
3868 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3869 chip->ecc.hwctl(chip, NAND_ECC_WRITE);
3870
3871 ret = nand_write_data_op(chip, p, eccsize, false);
3872 if (ret)
3873 return ret;
3874
3875 if (chip->ecc.prepad) {
3876 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3877 false);
3878 if (ret)
3879 return ret;
3880
3881 oob += chip->ecc.prepad;
3882 }
3883
3884 chip->ecc.calculate(chip, p, oob);
3885
3886 ret = nand_write_data_op(chip, oob, eccbytes, false);
3887 if (ret)
3888 return ret;
3889
3890 oob += eccbytes;
3891
3892 if (chip->ecc.postpad) {
3893 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3894 false);
3895 if (ret)
3896 return ret;
3897
3898 oob += chip->ecc.postpad;
3899 }
3900 }
3901
3902 /* Calculate remaining oob bytes */
3903 i = mtd->oobsize - (oob - chip->oob_poi);
3904 if (i) {
3905 ret = nand_write_data_op(chip, oob, i, false);
3906 if (ret)
3907 return ret;
3908 }
3909
3910 return nand_prog_page_end_op(chip);
3911}
3912
3913/**
3914 * nand_write_page - write one page
3915 * @chip: NAND chip descriptor
3916 * @offset: address offset within the page
3917 * @data_len: length of actual data to be written
3918 * @buf: the data to write
3919 * @oob_required: must write chip->oob_poi to OOB
3920 * @page: page number to write
3921 * @raw: use _raw version of write_page
3922 */
3923static int nand_write_page(struct nand_chip *chip, uint32_t offset,
3924 int data_len, const uint8_t *buf, int oob_required,
3925 int page, int raw)
3926{
3927 struct mtd_info *mtd = nand_to_mtd(chip);
3928 int status, subpage;
3929
3930 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3931 chip->ecc.write_subpage)
3932 subpage = offset || (data_len < mtd->writesize);
3933 else
3934 subpage = 0;
3935
3936 if (unlikely(raw))
3937 status = chip->ecc.write_page_raw(chip, buf, oob_required,
3938 page);
3939 else if (subpage)
3940 status = chip->ecc.write_subpage(chip, offset, data_len, buf,
3941 oob_required, page);
3942 else
3943 status = chip->ecc.write_page(chip, buf, oob_required, page);
3944
3945 if (status < 0)
3946 return status;
3947
3948 return 0;
3949}
3950
3951#define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3952
3953/**
3954 * nand_do_write_ops - [INTERN] NAND write with ECC
3955 * @chip: NAND chip object
3956 * @to: offset to write to
3957 * @ops: oob operations description structure
3958 *
3959 * NAND write with ECC.
3960 */
3961static int nand_do_write_ops(struct nand_chip *chip, loff_t to,
3962 struct mtd_oob_ops *ops)
3963{
3964 struct mtd_info *mtd = nand_to_mtd(chip);
3965 int chipnr, realpage, page, column;
3966 uint32_t writelen = ops->len;
3967
3968 uint32_t oobwritelen = ops->ooblen;
3969 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3970
3971 uint8_t *oob = ops->oobbuf;
3972 uint8_t *buf = ops->datbuf;
3973 int ret;
3974 int oob_required = oob ? 1 : 0;
3975
3976 ops->retlen = 0;
3977 if (!writelen)
3978 return 0;
3979
3980 /* Reject writes, which are not page aligned */
3981 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
3982 pr_notice("%s: attempt to write non page aligned data\n",
3983 __func__);
3984 return -EINVAL;
3985 }
3986
3987 column = to & (mtd->writesize - 1);
3988
3989 chipnr = (int)(to >> chip->chip_shift);
3990 nand_select_target(chip, chipnr);
3991
3992 /* Check, if it is write protected */
3993 if (nand_check_wp(chip)) {
3994 ret = -EIO;
3995 goto err_out;
3996 }
3997
3998 realpage = (int)(to >> chip->page_shift);
3999 page = realpage & chip->pagemask;
4000
4001 /* Invalidate the page cache, when we write to the cached page */
4002 if (to <= ((loff_t)chip->pagecache.page << chip->page_shift) &&
4003 ((loff_t)chip->pagecache.page << chip->page_shift) < (to + ops->len))
4004 chip->pagecache.page = -1;
4005
4006 /* Don't allow multipage oob writes with offset */
4007 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4008 ret = -EINVAL;
4009 goto err_out;
4010 }
4011
4012 while (1) {
4013 int bytes = mtd->writesize;
4014 uint8_t *wbuf = buf;
4015 int use_bufpoi;
4016 int part_pagewr = (column || writelen < mtd->writesize);
4017
4018 if (part_pagewr)
4019 use_bufpoi = 1;
4020 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
4021 use_bufpoi = !virt_addr_valid(buf) ||
4022 !IS_ALIGNED((unsigned long)buf,
4023 chip->buf_align);
4024 else
4025 use_bufpoi = 0;
4026
4027 /* Partial page write?, or need to use bounce buffer */
4028 if (use_bufpoi) {
4029 pr_debug("%s: using write bounce buffer for buf@%p\n",
4030 __func__, buf);
4031 if (part_pagewr)
4032 bytes = min_t(int, bytes - column, writelen);
4033 wbuf = nand_get_data_buf(chip);
4034 memset(wbuf, 0xff, mtd->writesize);
4035 memcpy(&wbuf[column], buf, bytes);
4036 }
4037
4038 if (unlikely(oob)) {
4039 size_t len = min(oobwritelen, oobmaxlen);
4040 oob = nand_fill_oob(chip, oob, len, ops);
4041 oobwritelen -= len;
4042 } else {
4043 /* We still need to erase leftover OOB data */
4044 memset(chip->oob_poi, 0xff, mtd->oobsize);
4045 }
4046
4047 ret = nand_write_page(chip, column, bytes, wbuf,
4048 oob_required, page,
4049 (ops->mode == MTD_OPS_RAW));
4050 if (ret)
4051 break;
4052
4053 writelen -= bytes;
4054 if (!writelen)
4055 break;
4056
4057 column = 0;
4058 buf += bytes;
4059 realpage++;
4060
4061 page = realpage & chip->pagemask;
4062 /* Check, if we cross a chip boundary */
4063 if (!page) {
4064 chipnr++;
4065 nand_deselect_target(chip);
4066 nand_select_target(chip, chipnr);
4067 }
4068 }
4069
4070 ops->retlen = ops->len - writelen;
4071 if (unlikely(oob))
4072 ops->oobretlen = ops->ooblen;
4073
4074err_out:
4075 nand_deselect_target(chip);
4076 return ret;
4077}
4078
4079/**
4080 * panic_nand_write - [MTD Interface] NAND write with ECC
4081 * @mtd: MTD device structure
4082 * @to: offset to write to
4083 * @len: number of bytes to write
4084 * @retlen: pointer to variable to store the number of written bytes
4085 * @buf: the data to write
4086 *
4087 * NAND write with ECC. Used when performing writes in interrupt context, this
4088 * may for example be called by mtdoops when writing an oops while in panic.
4089 */
4090static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4091 size_t *retlen, const uint8_t *buf)
4092{
4093 struct nand_chip *chip = mtd_to_nand(mtd);
4094 int chipnr = (int)(to >> chip->chip_shift);
4095 struct mtd_oob_ops ops;
4096 int ret;
4097
4098 nand_select_target(chip, chipnr);
4099
4100 /* Wait for the device to get ready */
4101 panic_nand_wait(chip, 400);
4102
4103 memset(&ops, 0, sizeof(ops));
4104 ops.len = len;
4105 ops.datbuf = (uint8_t *)buf;
4106 ops.mode = MTD_OPS_PLACE_OOB;
4107
4108 ret = nand_do_write_ops(chip, to, &ops);
4109
4110 *retlen = ops.retlen;
4111 return ret;
4112}
4113
4114/**
4115 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4116 * @mtd: MTD device structure
4117 * @to: offset to write to
4118 * @ops: oob operation description structure
4119 */
4120static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4121 struct mtd_oob_ops *ops)
4122{
4123 struct nand_chip *chip = mtd_to_nand(mtd);
4124 int ret = 0;
4125
4126 ops->retlen = 0;
4127
4128 nand_get_device(chip);
4129
4130 switch (ops->mode) {
4131 case MTD_OPS_PLACE_OOB:
4132 case MTD_OPS_AUTO_OOB:
4133 case MTD_OPS_RAW:
4134 break;
4135
4136 default:
4137 goto out;
4138 }
4139
4140 if (!ops->datbuf)
4141 ret = nand_do_write_oob(chip, to, ops);
4142 else
4143 ret = nand_do_write_ops(chip, to, ops);
4144
4145out:
4146 nand_release_device(chip);
4147 return ret;
4148}
4149
4150/**
4151 * nand_erase - [MTD Interface] erase block(s)
4152 * @mtd: MTD device structure
4153 * @instr: erase instruction
4154 *
4155 * Erase one ore more blocks.
4156 */
4157static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4158{
4159 return nand_erase_nand(mtd_to_nand(mtd), instr, 0);
4160}
4161
4162/**
4163 * nand_erase_nand - [INTERN] erase block(s)
4164 * @chip: NAND chip object
4165 * @instr: erase instruction
4166 * @allowbbt: allow erasing the bbt area
4167 *
4168 * Erase one ore more blocks.
4169 */
4170int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr,
4171 int allowbbt)
4172{
4173 int page, pages_per_block, ret, chipnr;
4174 loff_t len;
4175
4176 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4177 __func__, (unsigned long long)instr->addr,
4178 (unsigned long long)instr->len);
4179
4180 if (check_offs_len(chip, instr->addr, instr->len))
4181 return -EINVAL;
4182
4183 /* Grab the lock and see if the device is available */
4184 nand_get_device(chip);
4185
4186 /* Shift to get first page */
4187 page = (int)(instr->addr >> chip->page_shift);
4188 chipnr = (int)(instr->addr >> chip->chip_shift);
4189
4190 /* Calculate pages in each block */
4191 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4192
4193 /* Select the NAND device */
4194 nand_select_target(chip, chipnr);
4195
4196 /* Check, if it is write protected */
4197 if (nand_check_wp(chip)) {
4198 pr_debug("%s: device is write protected!\n",
4199 __func__);
4200 ret = -EIO;
4201 goto erase_exit;
4202 }
4203
4204 /* Loop through the pages */
4205 len = instr->len;
4206
4207 while (len) {
4208 /* Check if we have a bad block, we do not erase bad blocks! */
4209 if (nand_block_checkbad(chip, ((loff_t) page) <<
4210 chip->page_shift, allowbbt)) {
4211 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4212 __func__, page);
4213 ret = -EIO;
4214 goto erase_exit;
4215 }
4216
4217 /*
4218 * Invalidate the page cache, if we erase the block which
4219 * contains the current cached page.
4220 */
4221 if (page <= chip->pagecache.page && chip->pagecache.page <
4222 (page + pages_per_block))
4223 chip->pagecache.page = -1;
4224
4225 ret = nand_erase_op(chip, (page & chip->pagemask) >>
4226 (chip->phys_erase_shift - chip->page_shift));
4227 if (ret) {
4228 pr_debug("%s: failed erase, page 0x%08x\n",
4229 __func__, page);
4230 instr->fail_addr =
4231 ((loff_t)page << chip->page_shift);
4232 goto erase_exit;
4233 }
4234
4235 /* Increment page address and decrement length */
4236 len -= (1ULL << chip->phys_erase_shift);
4237 page += pages_per_block;
4238
4239 /* Check, if we cross a chip boundary */
4240 if (len && !(page & chip->pagemask)) {
4241 chipnr++;
4242 nand_deselect_target(chip);
4243 nand_select_target(chip, chipnr);
4244 }
4245 }
4246
4247 ret = 0;
4248erase_exit:
4249
4250 /* Deselect and wake up anyone waiting on the device */
4251 nand_deselect_target(chip);
4252 nand_release_device(chip);
4253
4254 /* Return more or less happy */
4255 return ret;
4256}
4257
4258/**
4259 * nand_sync - [MTD Interface] sync
4260 * @mtd: MTD device structure
4261 *
4262 * Sync is actually a wait for chip ready function.
4263 */
4264static void nand_sync(struct mtd_info *mtd)
4265{
4266 struct nand_chip *chip = mtd_to_nand(mtd);
4267
4268 pr_debug("%s: called\n", __func__);
4269
4270 /* Grab the lock and see if the device is available */
4271 nand_get_device(chip);
4272 /* Release it and go back */
4273 nand_release_device(chip);
4274}
4275
4276/**
4277 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4278 * @mtd: MTD device structure
4279 * @offs: offset relative to mtd start
4280 */
4281static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4282{
4283 struct nand_chip *chip = mtd_to_nand(mtd);
4284 int chipnr = (int)(offs >> chip->chip_shift);
4285 int ret;
4286
4287 /* Select the NAND device */
4288 nand_get_device(chip);
4289
4290 nand_select_target(chip, chipnr);
4291
4292 ret = nand_block_checkbad(chip, offs, 0);
4293
4294 nand_deselect_target(chip);
4295 nand_release_device(chip);
4296
4297 return ret;
4298}
4299
4300/**
4301 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4302 * @mtd: MTD device structure
4303 * @ofs: offset relative to mtd start
4304 */
4305static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4306{
4307 int ret;
4308
4309 ret = nand_block_isbad(mtd, ofs);
4310 if (ret) {
4311 /* If it was bad already, return success and do nothing */
4312 if (ret > 0)
4313 return 0;
4314 return ret;
4315 }
4316
4317 return nand_block_markbad_lowlevel(mtd_to_nand(mtd), ofs);
4318}
4319
4320/**
4321 * nand_suspend - [MTD Interface] Suspend the NAND flash
4322 * @mtd: MTD device structure
4323 */
4324static int nand_suspend(struct mtd_info *mtd)
4325{
4326 struct nand_chip *chip = mtd_to_nand(mtd);
4327
4328 mutex_lock(&chip->lock);
4329 chip->suspended = 1;
4330 mutex_unlock(&chip->lock);
4331
4332 return 0;
4333}
4334
4335/**
4336 * nand_resume - [MTD Interface] Resume the NAND flash
4337 * @mtd: MTD device structure
4338 */
4339static void nand_resume(struct mtd_info *mtd)
4340{
4341 struct nand_chip *chip = mtd_to_nand(mtd);
4342
4343 mutex_lock(&chip->lock);
4344 if (chip->suspended)
4345 chip->suspended = 0;
4346 else
4347 pr_err("%s called for a chip which is not in suspended state\n",
4348 __func__);
4349 mutex_unlock(&chip->lock);
4350
4351 wake_up_all(&chip->resume_wq);
4352}
4353
4354/**
4355 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4356 * prevent further operations
4357 * @mtd: MTD device structure
4358 */
4359static void nand_shutdown(struct mtd_info *mtd)
4360{
4361 nand_suspend(mtd);
4362}
4363
4364/* Set default functions */
4365static void nand_set_defaults(struct nand_chip *chip)
4366{
4367 /* If no controller is provided, use the dummy, legacy one. */
4368 if (!chip->controller) {
4369 chip->controller = &chip->legacy.dummy_controller;
4370 nand_controller_init(chip->controller);
4371 }
4372
4373 nand_legacy_set_defaults(chip);
4374
4375 if (!chip->buf_align)
4376 chip->buf_align = 1;
4377}
4378
4379/* Sanitize ONFI strings so we can safely print them */
4380void sanitize_string(uint8_t *s, size_t len)
4381{
4382 ssize_t i;
4383
4384 /* Null terminate */
4385 s[len - 1] = 0;
4386
4387 /* Remove non printable chars */
4388 for (i = 0; i < len - 1; i++) {
4389 if (s[i] < ' ' || s[i] > 127)
4390 s[i] = '?';
4391 }
4392
4393 /* Remove trailing spaces */
4394 strim(s);
4395}
4396
4397/*
4398 * nand_id_has_period - Check if an ID string has a given wraparound period
4399 * @id_data: the ID string
4400 * @arrlen: the length of the @id_data array
4401 * @period: the period of repitition
4402 *
4403 * Check if an ID string is repeated within a given sequence of bytes at
4404 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4405 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4406 * if the repetition has a period of @period; otherwise, returns zero.
4407 */
4408static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4409{
4410 int i, j;
4411 for (i = 0; i < period; i++)
4412 for (j = i + period; j < arrlen; j += period)
4413 if (id_data[i] != id_data[j])
4414 return 0;
4415 return 1;
4416}
4417
4418/*
4419 * nand_id_len - Get the length of an ID string returned by CMD_READID
4420 * @id_data: the ID string
4421 * @arrlen: the length of the @id_data array
4422
4423 * Returns the length of the ID string, according to known wraparound/trailing
4424 * zero patterns. If no pattern exists, returns the length of the array.
4425 */
4426static int nand_id_len(u8 *id_data, int arrlen)
4427{
4428 int last_nonzero, period;
4429
4430 /* Find last non-zero byte */
4431 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4432 if (id_data[last_nonzero])
4433 break;
4434
4435 /* All zeros */
4436 if (last_nonzero < 0)
4437 return 0;
4438
4439 /* Calculate wraparound period */
4440 for (period = 1; period < arrlen; period++)
4441 if (nand_id_has_period(id_data, arrlen, period))
4442 break;
4443
4444 /* There's a repeated pattern */
4445 if (period < arrlen)
4446 return period;
4447
4448 /* There are trailing zeros */
4449 if (last_nonzero < arrlen - 1)
4450 return last_nonzero + 1;
4451
4452 /* No pattern detected */
4453 return arrlen;
4454}
4455
4456/* Extract the bits of per cell from the 3rd byte of the extended ID */
4457static int nand_get_bits_per_cell(u8 cellinfo)
4458{
4459 int bits;
4460
4461 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4462 bits >>= NAND_CI_CELLTYPE_SHIFT;
4463 return bits + 1;
4464}
4465
4466/*
4467 * Many new NAND share similar device ID codes, which represent the size of the
4468 * chip. The rest of the parameters must be decoded according to generic or
4469 * manufacturer-specific "extended ID" decoding patterns.
4470 */
4471void nand_decode_ext_id(struct nand_chip *chip)
4472{
4473 struct nand_memory_organization *memorg;
4474 struct mtd_info *mtd = nand_to_mtd(chip);
4475 int extid;
4476 u8 *id_data = chip->id.data;
4477
4478 memorg = nanddev_get_memorg(&chip->base);
4479
4480 /* The 3rd id byte holds MLC / multichip data */
4481 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4482 /* The 4th id byte is the important one */
4483 extid = id_data[3];
4484
4485 /* Calc pagesize */
4486 memorg->pagesize = 1024 << (extid & 0x03);
4487 mtd->writesize = memorg->pagesize;
4488 extid >>= 2;
4489 /* Calc oobsize */
4490 memorg->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4491 mtd->oobsize = memorg->oobsize;
4492 extid >>= 2;
4493 /* Calc blocksize. Blocksize is multiples of 64KiB */
4494 memorg->pages_per_eraseblock = ((64 * 1024) << (extid & 0x03)) /
4495 memorg->pagesize;
4496 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4497 extid >>= 2;
4498 /* Get buswidth information */
4499 if (extid & 0x1)
4500 chip->options |= NAND_BUSWIDTH_16;
4501}
4502EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4503
4504/*
4505 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4506 * decodes a matching ID table entry and assigns the MTD size parameters for
4507 * the chip.
4508 */
4509static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4510{
4511 struct mtd_info *mtd = nand_to_mtd(chip);
4512 struct nand_memory_organization *memorg;
4513
4514 memorg = nanddev_get_memorg(&chip->base);
4515
4516 memorg->pages_per_eraseblock = type->erasesize / type->pagesize;
4517 mtd->erasesize = type->erasesize;
4518 memorg->pagesize = type->pagesize;
4519 mtd->writesize = memorg->pagesize;
4520 memorg->oobsize = memorg->pagesize / 32;
4521 mtd->oobsize = memorg->oobsize;
4522
4523 /* All legacy ID NAND are small-page, SLC */
4524 memorg->bits_per_cell = 1;
4525}
4526
4527/*
4528 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4529 * heuristic patterns using various detected parameters (e.g., manufacturer,
4530 * page size, cell-type information).
4531 */
4532static void nand_decode_bbm_options(struct nand_chip *chip)
4533{
4534 struct mtd_info *mtd = nand_to_mtd(chip);
4535
4536 /* Set the bad block position */
4537 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4538 chip->badblockpos = NAND_BBM_POS_LARGE;
4539 else
4540 chip->badblockpos = NAND_BBM_POS_SMALL;
4541}
4542
4543static inline bool is_full_id_nand(struct nand_flash_dev *type)
4544{
4545 return type->id_len;
4546}
4547
4548static bool find_full_id_nand(struct nand_chip *chip,
4549 struct nand_flash_dev *type)
4550{
4551 struct mtd_info *mtd = nand_to_mtd(chip);
4552 struct nand_memory_organization *memorg;
4553 u8 *id_data = chip->id.data;
4554
4555 memorg = nanddev_get_memorg(&chip->base);
4556
4557 if (!strncmp(type->id, id_data, type->id_len)) {
4558 memorg->pagesize = type->pagesize;
4559 mtd->writesize = memorg->pagesize;
4560 memorg->pages_per_eraseblock = type->erasesize /
4561 type->pagesize;
4562 mtd->erasesize = type->erasesize;
4563 memorg->oobsize = type->oobsize;
4564 mtd->oobsize = memorg->oobsize;
4565
4566 memorg->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4567 memorg->eraseblocks_per_lun =
4568 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4569 memorg->pagesize *
4570 memorg->pages_per_eraseblock);
4571 chip->options |= type->options;
4572 chip->base.eccreq.strength = NAND_ECC_STRENGTH(type);
4573 chip->base.eccreq.step_size = NAND_ECC_STEP(type);
4574 chip->onfi_timing_mode_default =
4575 type->onfi_timing_mode_default;
4576
4577 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4578 if (!chip->parameters.model)
4579 return false;
4580
4581 return true;
4582 }
4583 return false;
4584}
4585
4586/*
4587 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4588 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4589 * table.
4590 */
4591static void nand_manufacturer_detect(struct nand_chip *chip)
4592{
4593 /*
4594 * Try manufacturer detection if available and use
4595 * nand_decode_ext_id() otherwise.
4596 */
4597 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4598 chip->manufacturer.desc->ops->detect) {
4599 struct nand_memory_organization *memorg;
4600
4601 memorg = nanddev_get_memorg(&chip->base);
4602
4603 /* The 3rd id byte holds MLC / multichip data */
4604 memorg->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4605 chip->manufacturer.desc->ops->detect(chip);
4606 } else {
4607 nand_decode_ext_id(chip);
4608 }
4609}
4610
4611/*
4612 * Manufacturer initialization. This function is called for all NANDs including
4613 * ONFI and JEDEC compliant ones.
4614 * Manufacturer drivers should put all their specific initialization code in
4615 * their ->init() hook.
4616 */
4617static int nand_manufacturer_init(struct nand_chip *chip)
4618{
4619 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4620 !chip->manufacturer.desc->ops->init)
4621 return 0;
4622
4623 return chip->manufacturer.desc->ops->init(chip);
4624}
4625
4626/*
4627 * Manufacturer cleanup. This function is called for all NANDs including
4628 * ONFI and JEDEC compliant ones.
4629 * Manufacturer drivers should put all their specific cleanup code in their
4630 * ->cleanup() hook.
4631 */
4632static void nand_manufacturer_cleanup(struct nand_chip *chip)
4633{
4634 /* Release manufacturer private data */
4635 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4636 chip->manufacturer.desc->ops->cleanup)
4637 chip->manufacturer.desc->ops->cleanup(chip);
4638}
4639
4640static const char *
4641nand_manufacturer_name(const struct nand_manufacturer *manufacturer)
4642{
4643 return manufacturer ? manufacturer->name : "Unknown";
4644}
4645
4646/*
4647 * Get the flash and manufacturer id and lookup if the type is supported.
4648 */
4649static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4650{
4651 const struct nand_manufacturer *manufacturer;
4652 struct mtd_info *mtd = nand_to_mtd(chip);
4653 struct nand_memory_organization *memorg;
4654 int busw, ret;
4655 u8 *id_data = chip->id.data;
4656 u8 maf_id, dev_id;
4657 u64 targetsize;
4658
4659 /*
4660 * Let's start by initializing memorg fields that might be left
4661 * unassigned by the ID-based detection logic.
4662 */
4663 memorg = nanddev_get_memorg(&chip->base);
4664 memorg->planes_per_lun = 1;
4665 memorg->luns_per_target = 1;
4666
4667 /*
4668 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4669 * after power-up.
4670 */
4671 ret = nand_reset(chip, 0);
4672 if (ret)
4673 return ret;
4674
4675 /* Select the device */
4676 nand_select_target(chip, 0);
4677
4678 /* Send the command for reading device ID */
4679 ret = nand_readid_op(chip, 0, id_data, 2);
4680 if (ret)
4681 return ret;
4682
4683 /* Read manufacturer and device IDs */
4684 maf_id = id_data[0];
4685 dev_id = id_data[1];
4686
4687 /*
4688 * Try again to make sure, as some systems the bus-hold or other
4689 * interface concerns can cause random data which looks like a
4690 * possibly credible NAND flash to appear. If the two results do
4691 * not match, ignore the device completely.
4692 */
4693
4694 /* Read entire ID string */
4695 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4696 if (ret)
4697 return ret;
4698
4699 if (id_data[0] != maf_id || id_data[1] != dev_id) {
4700 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4701 maf_id, dev_id, id_data[0], id_data[1]);
4702 return -ENODEV;
4703 }
4704
4705 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4706
4707 /* Try to identify manufacturer */
4708 manufacturer = nand_get_manufacturer(maf_id);
4709 chip->manufacturer.desc = manufacturer;
4710
4711 if (!type)
4712 type = nand_flash_ids;
4713
4714 /*
4715 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4716 * override it.
4717 * This is required to make sure initial NAND bus width set by the
4718 * NAND controller driver is coherent with the real NAND bus width
4719 * (extracted by auto-detection code).
4720 */
4721 busw = chip->options & NAND_BUSWIDTH_16;
4722
4723 /*
4724 * The flag is only set (never cleared), reset it to its default value
4725 * before starting auto-detection.
4726 */
4727 chip->options &= ~NAND_BUSWIDTH_16;
4728
4729 for (; type->name != NULL; type++) {
4730 if (is_full_id_nand(type)) {
4731 if (find_full_id_nand(chip, type))
4732 goto ident_done;
4733 } else if (dev_id == type->dev_id) {
4734 break;
4735 }
4736 }
4737
4738 if (!type->name || !type->pagesize) {
4739 /* Check if the chip is ONFI compliant */
4740 ret = nand_onfi_detect(chip);
4741 if (ret < 0)
4742 return ret;
4743 else if (ret)
4744 goto ident_done;
4745
4746 /* Check if the chip is JEDEC compliant */
4747 ret = nand_jedec_detect(chip);
4748 if (ret < 0)
4749 return ret;
4750 else if (ret)
4751 goto ident_done;
4752 }
4753
4754 if (!type->name)
4755 return -ENODEV;
4756
4757 chip->parameters.model = kstrdup(type->name, GFP_KERNEL);
4758 if (!chip->parameters.model)
4759 return -ENOMEM;
4760
4761 if (!type->pagesize)
4762 nand_manufacturer_detect(chip);
4763 else
4764 nand_decode_id(chip, type);
4765
4766 /* Get chip options */
4767 chip->options |= type->options;
4768
4769 memorg->eraseblocks_per_lun =
4770 DIV_ROUND_DOWN_ULL((u64)type->chipsize << 20,
4771 memorg->pagesize *
4772 memorg->pages_per_eraseblock);
4773
4774ident_done:
4775 if (!mtd->name)
4776 mtd->name = chip->parameters.model;
4777
4778 if (chip->options & NAND_BUSWIDTH_AUTO) {
4779 WARN_ON(busw & NAND_BUSWIDTH_16);
4780 nand_set_defaults(chip);
4781 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4782 /*
4783 * Check, if buswidth is correct. Hardware drivers should set
4784 * chip correct!
4785 */
4786 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4787 maf_id, dev_id);
4788 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4789 mtd->name);
4790 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4791 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4792 ret = -EINVAL;
4793
4794 goto free_detect_allocation;
4795 }
4796
4797 nand_decode_bbm_options(chip);
4798
4799 /* Calculate the address shift from the page size */
4800 chip->page_shift = ffs(mtd->writesize) - 1;
4801 /* Convert chipsize to number of pages per chip -1 */
4802 targetsize = nanddev_target_size(&chip->base);
4803 chip->pagemask = (targetsize >> chip->page_shift) - 1;
4804
4805 chip->bbt_erase_shift = chip->phys_erase_shift =
4806 ffs(mtd->erasesize) - 1;
4807 if (targetsize & 0xffffffff)
4808 chip->chip_shift = ffs((unsigned)targetsize) - 1;
4809 else {
4810 chip->chip_shift = ffs((unsigned)(targetsize >> 32));
4811 chip->chip_shift += 32 - 1;
4812 }
4813
4814 if (chip->chip_shift - chip->page_shift > 16)
4815 chip->options |= NAND_ROW_ADDR_3;
4816
4817 chip->badblockbits = 8;
4818
4819 nand_legacy_adjust_cmdfunc(chip);
4820
4821 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4822 maf_id, dev_id);
4823 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4824 chip->parameters.model);
4825 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4826 (int)(targetsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4827 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4828 return 0;
4829
4830free_detect_allocation:
4831 kfree(chip->parameters.model);
4832
4833 return ret;
4834}
4835
4836static const char * const nand_ecc_modes[] = {
4837 [NAND_ECC_NONE] = "none",
4838 [NAND_ECC_SOFT] = "soft",
4839 [NAND_ECC_HW] = "hw",
4840 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4841 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4842 [NAND_ECC_ON_DIE] = "on-die",
4843};
4844
4845static int of_get_nand_ecc_mode(struct device_node *np)
4846{
4847 const char *pm;
4848 int err, i;
4849
4850 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4851 if (err < 0)
4852 return err;
4853
4854 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4855 if (!strcasecmp(pm, nand_ecc_modes[i]))
4856 return i;
4857
4858 /*
4859 * For backward compatibility we support few obsoleted values that don't
4860 * have their mappings into nand_ecc_modes_t anymore (they were merged
4861 * with other enums).
4862 */
4863 if (!strcasecmp(pm, "soft_bch"))
4864 return NAND_ECC_SOFT;
4865
4866 return -ENODEV;
4867}
4868
4869static const char * const nand_ecc_algos[] = {
4870 [NAND_ECC_HAMMING] = "hamming",
4871 [NAND_ECC_BCH] = "bch",
4872 [NAND_ECC_RS] = "rs",
4873};
4874
4875static int of_get_nand_ecc_algo(struct device_node *np)
4876{
4877 const char *pm;
4878 int err, i;
4879
4880 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4881 if (!err) {
4882 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4883 if (!strcasecmp(pm, nand_ecc_algos[i]))
4884 return i;
4885 return -ENODEV;
4886 }
4887
4888 /*
4889 * For backward compatibility we also read "nand-ecc-mode" checking
4890 * for some obsoleted values that were specifying ECC algorithm.
4891 */
4892 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4893 if (err < 0)
4894 return err;
4895
4896 if (!strcasecmp(pm, "soft"))
4897 return NAND_ECC_HAMMING;
4898 else if (!strcasecmp(pm, "soft_bch"))
4899 return NAND_ECC_BCH;
4900
4901 return -ENODEV;
4902}
4903
4904static int of_get_nand_ecc_step_size(struct device_node *np)
4905{
4906 int ret;
4907 u32 val;
4908
4909 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4910 return ret ? ret : val;
4911}
4912
4913static int of_get_nand_ecc_strength(struct device_node *np)
4914{
4915 int ret;
4916 u32 val;
4917
4918 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4919 return ret ? ret : val;
4920}
4921
4922static int of_get_nand_bus_width(struct device_node *np)
4923{
4924 u32 val;
4925
4926 if (of_property_read_u32(np, "nand-bus-width", &val))
4927 return 8;
4928
4929 switch (val) {
4930 case 8:
4931 case 16:
4932 return val;
4933 default:
4934 return -EIO;
4935 }
4936}
4937
4938static bool of_get_nand_on_flash_bbt(struct device_node *np)
4939{
4940 return of_property_read_bool(np, "nand-on-flash-bbt");
4941}
4942
4943static int nand_dt_init(struct nand_chip *chip)
4944{
4945 struct device_node *dn = nand_get_flash_node(chip);
4946 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4947
4948 if (!dn)
4949 return 0;
4950
4951 if (of_get_nand_bus_width(dn) == 16)
4952 chip->options |= NAND_BUSWIDTH_16;
4953
4954 if (of_property_read_bool(dn, "nand-is-boot-medium"))
4955 chip->options |= NAND_IS_BOOT_MEDIUM;
4956
4957 if (of_get_nand_on_flash_bbt(dn))
4958 chip->bbt_options |= NAND_BBT_USE_FLASH;
4959
4960 ecc_mode = of_get_nand_ecc_mode(dn);
4961 ecc_algo = of_get_nand_ecc_algo(dn);
4962 ecc_strength = of_get_nand_ecc_strength(dn);
4963 ecc_step = of_get_nand_ecc_step_size(dn);
4964
4965 if (ecc_mode >= 0)
4966 chip->ecc.mode = ecc_mode;
4967
4968 if (ecc_algo >= 0)
4969 chip->ecc.algo = ecc_algo;
4970
4971 if (ecc_strength >= 0)
4972 chip->ecc.strength = ecc_strength;
4973
4974 if (ecc_step > 0)
4975 chip->ecc.size = ecc_step;
4976
4977 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4978 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4979
4980 return 0;
4981}
4982
4983/**
4984 * nand_scan_ident - Scan for the NAND device
4985 * @chip: NAND chip object
4986 * @maxchips: number of chips to scan for
4987 * @table: alternative NAND ID table
4988 *
4989 * This is the first phase of the normal nand_scan() function. It reads the
4990 * flash ID and sets up MTD fields accordingly.
4991 *
4992 * This helper used to be called directly from controller drivers that needed
4993 * to tweak some ECC-related parameters before nand_scan_tail(). This separation
4994 * prevented dynamic allocations during this phase which was unconvenient and
4995 * as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
4996 */
4997static int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips,
4998 struct nand_flash_dev *table)
4999{
5000 struct mtd_info *mtd = nand_to_mtd(chip);
5001 struct nand_memory_organization *memorg;
5002 int nand_maf_id, nand_dev_id;
5003 unsigned int i;
5004 int ret;
5005
5006 memorg = nanddev_get_memorg(&chip->base);
5007
5008 /* Assume all dies are deselected when we enter nand_scan_ident(). */
5009 chip->cur_cs = -1;
5010
5011 mutex_init(&chip->lock);
5012 init_waitqueue_head(&chip->resume_wq);
5013
5014 /* Enforce the right timings for reset/detection */
5015 onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
5016
5017 ret = nand_dt_init(chip);
5018 if (ret)
5019 return ret;
5020
5021 if (!mtd->name && mtd->dev.parent)
5022 mtd->name = dev_name(mtd->dev.parent);
5023
5024 /* Set the default functions */
5025 nand_set_defaults(chip);
5026
5027 ret = nand_legacy_check_hooks(chip);
5028 if (ret)
5029 return ret;
5030
5031 memorg->ntargets = maxchips;
5032
5033 /* Read the flash type */
5034 ret = nand_detect(chip, table);
5035 if (ret) {
5036 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5037 pr_warn("No NAND device found\n");
5038 nand_deselect_target(chip);
5039 return ret;
5040 }
5041
5042 nand_maf_id = chip->id.data[0];
5043 nand_dev_id = chip->id.data[1];
5044
5045 nand_deselect_target(chip);
5046
5047 /* Check for a chip array */
5048 for (i = 1; i < maxchips; i++) {
5049 u8 id[2];
5050
5051 /* See comment in nand_get_flash_type for reset */
5052 ret = nand_reset(chip, i);
5053 if (ret)
5054 break;
5055
5056 nand_select_target(chip, i);
5057 /* Send the command for reading device ID */
5058 ret = nand_readid_op(chip, 0, id, sizeof(id));
5059 if (ret)
5060 break;
5061 /* Read manufacturer and device IDs */
5062 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5063 nand_deselect_target(chip);
5064 break;
5065 }
5066 nand_deselect_target(chip);
5067 }
5068 if (i > 1)
5069 pr_info("%d chips detected\n", i);
5070
5071 /* Store the number of chips and calc total size for mtd */
5072 memorg->ntargets = i;
5073 mtd->size = i * nanddev_target_size(&chip->base);
5074
5075 return 0;
5076}
5077
5078static void nand_scan_ident_cleanup(struct nand_chip *chip)
5079{
5080 kfree(chip->parameters.model);
5081 kfree(chip->parameters.onfi);
5082}
5083
5084static int nand_set_ecc_soft_ops(struct nand_chip *chip)
5085{
5086 struct mtd_info *mtd = nand_to_mtd(chip);
5087 struct nand_ecc_ctrl *ecc = &chip->ecc;
5088
5089 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
5090 return -EINVAL;
5091
5092 switch (ecc->algo) {
5093 case NAND_ECC_HAMMING:
5094 ecc->calculate = nand_calculate_ecc;
5095 ecc->correct = nand_correct_data;
5096 ecc->read_page = nand_read_page_swecc;
5097 ecc->read_subpage = nand_read_subpage;
5098 ecc->write_page = nand_write_page_swecc;
5099 ecc->read_page_raw = nand_read_page_raw;
5100 ecc->write_page_raw = nand_write_page_raw;
5101 ecc->read_oob = nand_read_oob_std;
5102 ecc->write_oob = nand_write_oob_std;
5103 if (!ecc->size)
5104 ecc->size = 256;
5105 ecc->bytes = 3;
5106 ecc->strength = 1;
5107
5108 if (IS_ENABLED(CONFIG_MTD_NAND_ECC_SW_HAMMING_SMC))
5109 ecc->options |= NAND_ECC_SOFT_HAMMING_SM_ORDER;
5110
5111 return 0;
5112 case NAND_ECC_BCH:
5113 if (!mtd_nand_has_bch()) {
5114 WARN(1, "CONFIG_MTD_NAND_ECC_SW_BCH not enabled\n");
5115 return -EINVAL;
5116 }
5117 ecc->calculate = nand_bch_calculate_ecc;
5118 ecc->correct = nand_bch_correct_data;
5119 ecc->read_page = nand_read_page_swecc;
5120 ecc->read_subpage = nand_read_subpage;
5121 ecc->write_page = nand_write_page_swecc;
5122 ecc->read_page_raw = nand_read_page_raw;
5123 ecc->write_page_raw = nand_write_page_raw;
5124 ecc->read_oob = nand_read_oob_std;
5125 ecc->write_oob = nand_write_oob_std;
5126
5127 /*
5128 * Board driver should supply ecc.size and ecc.strength
5129 * values to select how many bits are correctable.
5130 * Otherwise, default to 4 bits for large page devices.
5131 */
5132 if (!ecc->size && (mtd->oobsize >= 64)) {
5133 ecc->size = 512;
5134 ecc->strength = 4;
5135 }
5136
5137 /*
5138 * if no ecc placement scheme was provided pickup the default
5139 * large page one.
5140 */
5141 if (!mtd->ooblayout) {
5142 /* handle large page devices only */
5143 if (mtd->oobsize < 64) {
5144 WARN(1, "OOB layout is required when using software BCH on small pages\n");
5145 return -EINVAL;
5146 }
5147
5148 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
5149
5150 }
5151
5152 /*
5153 * We can only maximize ECC config when the default layout is
5154 * used, otherwise we don't know how many bytes can really be
5155 * used.
5156 */
5157 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
5158 ecc->options & NAND_ECC_MAXIMIZE) {
5159 int steps, bytes;
5160
5161 /* Always prefer 1k blocks over 512bytes ones */
5162 ecc->size = 1024;
5163 steps = mtd->writesize / ecc->size;
5164
5165 /* Reserve 2 bytes for the BBM */
5166 bytes = (mtd->oobsize - 2) / steps;
5167 ecc->strength = bytes * 8 / fls(8 * ecc->size);
5168 }
5169
5170 /* See nand_bch_init() for details. */
5171 ecc->bytes = 0;
5172 ecc->priv = nand_bch_init(mtd);
5173 if (!ecc->priv) {
5174 WARN(1, "BCH ECC initialization failed!\n");
5175 return -EINVAL;
5176 }
5177 return 0;
5178 default:
5179 WARN(1, "Unsupported ECC algorithm!\n");
5180 return -EINVAL;
5181 }
5182}
5183
5184/**
5185 * nand_check_ecc_caps - check the sanity of preset ECC settings
5186 * @chip: nand chip info structure
5187 * @caps: ECC caps info structure
5188 * @oobavail: OOB size that the ECC engine can use
5189 *
5190 * When ECC step size and strength are already set, check if they are supported
5191 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5192 * On success, the calculated ECC bytes is set.
5193 */
5194static int
5195nand_check_ecc_caps(struct nand_chip *chip,
5196 const struct nand_ecc_caps *caps, int oobavail)
5197{
5198 struct mtd_info *mtd = nand_to_mtd(chip);
5199 const struct nand_ecc_step_info *stepinfo;
5200 int preset_step = chip->ecc.size;
5201 int preset_strength = chip->ecc.strength;
5202 int ecc_bytes, nsteps = mtd->writesize / preset_step;
5203 int i, j;
5204
5205 for (i = 0; i < caps->nstepinfos; i++) {
5206 stepinfo = &caps->stepinfos[i];
5207
5208 if (stepinfo->stepsize != preset_step)
5209 continue;
5210
5211 for (j = 0; j < stepinfo->nstrengths; j++) {
5212 if (stepinfo->strengths[j] != preset_strength)
5213 continue;
5214
5215 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5216 preset_strength);
5217 if (WARN_ON_ONCE(ecc_bytes < 0))
5218 return ecc_bytes;
5219
5220 if (ecc_bytes * nsteps > oobavail) {
5221 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5222 preset_step, preset_strength);
5223 return -ENOSPC;
5224 }
5225
5226 chip->ecc.bytes = ecc_bytes;
5227
5228 return 0;
5229 }
5230 }
5231
5232 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5233 preset_step, preset_strength);
5234
5235 return -ENOTSUPP;
5236}
5237
5238/**
5239 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5240 * @chip: nand chip info structure
5241 * @caps: ECC engine caps info structure
5242 * @oobavail: OOB size that the ECC engine can use
5243 *
5244 * If a chip's ECC requirement is provided, try to meet it with the least
5245 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5246 * On success, the chosen ECC settings are set.
5247 */
5248static int
5249nand_match_ecc_req(struct nand_chip *chip,
5250 const struct nand_ecc_caps *caps, int oobavail)
5251{
5252 struct mtd_info *mtd = nand_to_mtd(chip);
5253 const struct nand_ecc_step_info *stepinfo;
5254 int req_step = chip->base.eccreq.step_size;
5255 int req_strength = chip->base.eccreq.strength;
5256 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5257 int best_step, best_strength, best_ecc_bytes;
5258 int best_ecc_bytes_total = INT_MAX;
5259 int i, j;
5260
5261 /* No information provided by the NAND chip */
5262 if (!req_step || !req_strength)
5263 return -ENOTSUPP;
5264
5265 /* number of correctable bits the chip requires in a page */
5266 req_corr = mtd->writesize / req_step * req_strength;
5267
5268 for (i = 0; i < caps->nstepinfos; i++) {
5269 stepinfo = &caps->stepinfos[i];
5270 step_size = stepinfo->stepsize;
5271
5272 for (j = 0; j < stepinfo->nstrengths; j++) {
5273 strength = stepinfo->strengths[j];
5274
5275 /*
5276 * If both step size and strength are smaller than the
5277 * chip's requirement, it is not easy to compare the
5278 * resulted reliability.
5279 */
5280 if (step_size < req_step && strength < req_strength)
5281 continue;
5282
5283 if (mtd->writesize % step_size)
5284 continue;
5285
5286 nsteps = mtd->writesize / step_size;
5287
5288 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5289 if (WARN_ON_ONCE(ecc_bytes < 0))
5290 continue;
5291 ecc_bytes_total = ecc_bytes * nsteps;
5292
5293 if (ecc_bytes_total > oobavail ||
5294 strength * nsteps < req_corr)
5295 continue;
5296
5297 /*
5298 * We assume the best is to meet the chip's requrement
5299 * with the least number of ECC bytes.
5300 */
5301 if (ecc_bytes_total < best_ecc_bytes_total) {
5302 best_ecc_bytes_total = ecc_bytes_total;
5303 best_step = step_size;
5304 best_strength = strength;
5305 best_ecc_bytes = ecc_bytes;
5306 }
5307 }
5308 }
5309
5310 if (best_ecc_bytes_total == INT_MAX)
5311 return -ENOTSUPP;
5312
5313 chip->ecc.size = best_step;
5314 chip->ecc.strength = best_strength;
5315 chip->ecc.bytes = best_ecc_bytes;
5316
5317 return 0;
5318}
5319
5320/**
5321 * nand_maximize_ecc - choose the max ECC strength available
5322 * @chip: nand chip info structure
5323 * @caps: ECC engine caps info structure
5324 * @oobavail: OOB size that the ECC engine can use
5325 *
5326 * Choose the max ECC strength that is supported on the controller, and can fit
5327 * within the chip's OOB. On success, the chosen ECC settings are set.
5328 */
5329static int
5330nand_maximize_ecc(struct nand_chip *chip,
5331 const struct nand_ecc_caps *caps, int oobavail)
5332{
5333 struct mtd_info *mtd = nand_to_mtd(chip);
5334 const struct nand_ecc_step_info *stepinfo;
5335 int step_size, strength, nsteps, ecc_bytes, corr;
5336 int best_corr = 0;
5337 int best_step = 0;
5338 int best_strength, best_ecc_bytes;
5339 int i, j;
5340
5341 for (i = 0; i < caps->nstepinfos; i++) {
5342 stepinfo = &caps->stepinfos[i];
5343 step_size = stepinfo->stepsize;
5344
5345 /* If chip->ecc.size is already set, respect it */
5346 if (chip->ecc.size && step_size != chip->ecc.size)
5347 continue;
5348
5349 for (j = 0; j < stepinfo->nstrengths; j++) {
5350 strength = stepinfo->strengths[j];
5351
5352 if (mtd->writesize % step_size)
5353 continue;
5354
5355 nsteps = mtd->writesize / step_size;
5356
5357 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5358 if (WARN_ON_ONCE(ecc_bytes < 0))
5359 continue;
5360
5361 if (ecc_bytes * nsteps > oobavail)
5362 continue;
5363
5364 corr = strength * nsteps;
5365
5366 /*
5367 * If the number of correctable bits is the same,
5368 * bigger step_size has more reliability.
5369 */
5370 if (corr > best_corr ||
5371 (corr == best_corr && step_size > best_step)) {
5372 best_corr = corr;
5373 best_step = step_size;
5374 best_strength = strength;
5375 best_ecc_bytes = ecc_bytes;
5376 }
5377 }
5378 }
5379
5380 if (!best_corr)
5381 return -ENOTSUPP;
5382
5383 chip->ecc.size = best_step;
5384 chip->ecc.strength = best_strength;
5385 chip->ecc.bytes = best_ecc_bytes;
5386
5387 return 0;
5388}
5389
5390/**
5391 * nand_ecc_choose_conf - Set the ECC strength and ECC step size
5392 * @chip: nand chip info structure
5393 * @caps: ECC engine caps info structure
5394 * @oobavail: OOB size that the ECC engine can use
5395 *
5396 * Choose the ECC configuration according to following logic
5397 *
5398 * 1. If both ECC step size and ECC strength are already set (usually by DT)
5399 * then check if it is supported by this controller.
5400 * 2. If NAND_ECC_MAXIMIZE is set, then select maximum ECC strength.
5401 * 3. Otherwise, try to match the ECC step size and ECC strength closest
5402 * to the chip's requirement. If available OOB size can't fit the chip
5403 * requirement then fallback to the maximum ECC step size and ECC strength.
5404 *
5405 * On success, the chosen ECC settings are set.
5406 */
5407int nand_ecc_choose_conf(struct nand_chip *chip,
5408 const struct nand_ecc_caps *caps, int oobavail)
5409{
5410 struct mtd_info *mtd = nand_to_mtd(chip);
5411
5412 if (WARN_ON(oobavail < 0 || oobavail > mtd->oobsize))
5413 return -EINVAL;
5414
5415 if (chip->ecc.size && chip->ecc.strength)
5416 return nand_check_ecc_caps(chip, caps, oobavail);
5417
5418 if (chip->ecc.options & NAND_ECC_MAXIMIZE)
5419 return nand_maximize_ecc(chip, caps, oobavail);
5420
5421 if (!nand_match_ecc_req(chip, caps, oobavail))
5422 return 0;
5423
5424 return nand_maximize_ecc(chip, caps, oobavail);
5425}
5426EXPORT_SYMBOL_GPL(nand_ecc_choose_conf);
5427
5428/*
5429 * Check if the chip configuration meet the datasheet requirements.
5430
5431 * If our configuration corrects A bits per B bytes and the minimum
5432 * required correction level is X bits per Y bytes, then we must ensure
5433 * both of the following are true:
5434 *
5435 * (1) A / B >= X / Y
5436 * (2) A >= X
5437 *
5438 * Requirement (1) ensures we can correct for the required bitflip density.
5439 * Requirement (2) ensures we can correct even when all bitflips are clumped
5440 * in the same sector.
5441 */
5442static bool nand_ecc_strength_good(struct nand_chip *chip)
5443{
5444 struct mtd_info *mtd = nand_to_mtd(chip);
5445 struct nand_ecc_ctrl *ecc = &chip->ecc;
5446 int corr, ds_corr;
5447
5448 if (ecc->size == 0 || chip->base.eccreq.step_size == 0)
5449 /* Not enough information */
5450 return true;
5451
5452 /*
5453 * We get the number of corrected bits per page to compare
5454 * the correction density.
5455 */
5456 corr = (mtd->writesize * ecc->strength) / ecc->size;
5457 ds_corr = (mtd->writesize * chip->base.eccreq.strength) /
5458 chip->base.eccreq.step_size;
5459
5460 return corr >= ds_corr && ecc->strength >= chip->base.eccreq.strength;
5461}
5462
5463static int rawnand_erase(struct nand_device *nand, const struct nand_pos *pos)
5464{
5465 struct nand_chip *chip = container_of(nand, struct nand_chip,
5466 base);
5467 unsigned int eb = nanddev_pos_to_row(nand, pos);
5468 int ret;
5469
5470 eb >>= nand->rowconv.eraseblock_addr_shift;
5471
5472 nand_select_target(chip, pos->target);
5473 ret = nand_erase_op(chip, eb);
5474 nand_deselect_target(chip);
5475
5476 return ret;
5477}
5478
5479static int rawnand_markbad(struct nand_device *nand,
5480 const struct nand_pos *pos)
5481{
5482 struct nand_chip *chip = container_of(nand, struct nand_chip,
5483 base);
5484
5485 return nand_markbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5486}
5487
5488static bool rawnand_isbad(struct nand_device *nand, const struct nand_pos *pos)
5489{
5490 struct nand_chip *chip = container_of(nand, struct nand_chip,
5491 base);
5492 int ret;
5493
5494 nand_select_target(chip, pos->target);
5495 ret = nand_isbad_bbm(chip, nanddev_pos_to_offs(nand, pos));
5496 nand_deselect_target(chip);
5497
5498 return ret;
5499}
5500
5501static const struct nand_ops rawnand_ops = {
5502 .erase = rawnand_erase,
5503 .markbad = rawnand_markbad,
5504 .isbad = rawnand_isbad,
5505};
5506
5507/**
5508 * nand_scan_tail - Scan for the NAND device
5509 * @chip: NAND chip object
5510 *
5511 * This is the second phase of the normal nand_scan() function. It fills out
5512 * all the uninitialized function pointers with the defaults and scans for a
5513 * bad block table if appropriate.
5514 */
5515static int nand_scan_tail(struct nand_chip *chip)
5516{
5517 struct mtd_info *mtd = nand_to_mtd(chip);
5518 struct nand_ecc_ctrl *ecc = &chip->ecc;
5519 int ret, i;
5520
5521 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5522 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5523 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5524 return -EINVAL;
5525 }
5526
5527 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
5528 if (!chip->data_buf)
5529 return -ENOMEM;
5530
5531 /*
5532 * FIXME: some NAND manufacturer drivers expect the first die to be
5533 * selected when manufacturer->init() is called. They should be fixed
5534 * to explictly select the relevant die when interacting with the NAND
5535 * chip.
5536 */
5537 nand_select_target(chip, 0);
5538 ret = nand_manufacturer_init(chip);
5539 nand_deselect_target(chip);
5540 if (ret)
5541 goto err_free_buf;
5542
5543 /* Set the internal oob buffer location, just after the page data */
5544 chip->oob_poi = chip->data_buf + mtd->writesize;
5545
5546 /*
5547 * If no default placement scheme is given, select an appropriate one.
5548 */
5549 if (!mtd->ooblayout &&
5550 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
5551 switch (mtd->oobsize) {
5552 case 8:
5553 case 16:
5554 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
5555 break;
5556 case 64:
5557 case 128:
5558 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
5559 break;
5560 default:
5561 /*
5562 * Expose the whole OOB area to users if ECC_NONE
5563 * is passed. We could do that for all kind of
5564 * ->oobsize, but we must keep the old large/small
5565 * page with ECC layout when ->oobsize <= 128 for
5566 * compatibility reasons.
5567 */
5568 if (ecc->mode == NAND_ECC_NONE) {
5569 mtd_set_ooblayout(mtd,
5570 &nand_ooblayout_lp_ops);
5571 break;
5572 }
5573
5574 WARN(1, "No oob scheme defined for oobsize %d\n",
5575 mtd->oobsize);
5576 ret = -EINVAL;
5577 goto err_nand_manuf_cleanup;
5578 }
5579 }
5580
5581 /*
5582 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5583 * selected and we have 256 byte pagesize fallback to software ECC
5584 */
5585
5586 switch (ecc->mode) {
5587 case NAND_ECC_HW_OOB_FIRST:
5588 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5589 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5590 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5591 ret = -EINVAL;
5592 goto err_nand_manuf_cleanup;
5593 }
5594 if (!ecc->read_page)
5595 ecc->read_page = nand_read_page_hwecc_oob_first;
5596 /* fall through */
5597
5598 case NAND_ECC_HW:
5599 /* Use standard hwecc read page function? */
5600 if (!ecc->read_page)
5601 ecc->read_page = nand_read_page_hwecc;
5602 if (!ecc->write_page)
5603 ecc->write_page = nand_write_page_hwecc;
5604 if (!ecc->read_page_raw)
5605 ecc->read_page_raw = nand_read_page_raw;
5606 if (!ecc->write_page_raw)
5607 ecc->write_page_raw = nand_write_page_raw;
5608 if (!ecc->read_oob)
5609 ecc->read_oob = nand_read_oob_std;
5610 if (!ecc->write_oob)
5611 ecc->write_oob = nand_write_oob_std;
5612 if (!ecc->read_subpage)
5613 ecc->read_subpage = nand_read_subpage;
5614 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5615 ecc->write_subpage = nand_write_subpage_hwecc;
5616 /* fall through */
5617
5618 case NAND_ECC_HW_SYNDROME:
5619 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5620 (!ecc->read_page ||
5621 ecc->read_page == nand_read_page_hwecc ||
5622 !ecc->write_page ||
5623 ecc->write_page == nand_write_page_hwecc)) {
5624 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5625 ret = -EINVAL;
5626 goto err_nand_manuf_cleanup;
5627 }
5628 /* Use standard syndrome read/write page function? */
5629 if (!ecc->read_page)
5630 ecc->read_page = nand_read_page_syndrome;
5631 if (!ecc->write_page)
5632 ecc->write_page = nand_write_page_syndrome;
5633 if (!ecc->read_page_raw)
5634 ecc->read_page_raw = nand_read_page_raw_syndrome;
5635 if (!ecc->write_page_raw)
5636 ecc->write_page_raw = nand_write_page_raw_syndrome;
5637 if (!ecc->read_oob)
5638 ecc->read_oob = nand_read_oob_syndrome;
5639 if (!ecc->write_oob)
5640 ecc->write_oob = nand_write_oob_syndrome;
5641
5642 if (mtd->writesize >= ecc->size) {
5643 if (!ecc->strength) {
5644 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
5645 ret = -EINVAL;
5646 goto err_nand_manuf_cleanup;
5647 }
5648 break;
5649 }
5650 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5651 ecc->size, mtd->writesize);
5652 ecc->mode = NAND_ECC_SOFT;
5653 ecc->algo = NAND_ECC_HAMMING;
5654 /* fall through */
5655
5656 case NAND_ECC_SOFT:
5657 ret = nand_set_ecc_soft_ops(chip);
5658 if (ret) {
5659 ret = -EINVAL;
5660 goto err_nand_manuf_cleanup;
5661 }
5662 break;
5663
5664 case NAND_ECC_ON_DIE:
5665 if (!ecc->read_page || !ecc->write_page) {
5666 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
5667 ret = -EINVAL;
5668 goto err_nand_manuf_cleanup;
5669 }
5670 if (!ecc->read_oob)
5671 ecc->read_oob = nand_read_oob_std;
5672 if (!ecc->write_oob)
5673 ecc->write_oob = nand_write_oob_std;
5674 break;
5675
5676 case NAND_ECC_NONE:
5677 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5678 ecc->read_page = nand_read_page_raw;
5679 ecc->write_page = nand_write_page_raw;
5680 ecc->read_oob = nand_read_oob_std;
5681 ecc->read_page_raw = nand_read_page_raw;
5682 ecc->write_page_raw = nand_write_page_raw;
5683 ecc->write_oob = nand_write_oob_std;
5684 ecc->size = mtd->writesize;
5685 ecc->bytes = 0;
5686 ecc->strength = 0;
5687 break;
5688
5689 default:
5690 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
5691 ret = -EINVAL;
5692 goto err_nand_manuf_cleanup;
5693 }
5694
5695 if (ecc->correct || ecc->calculate) {
5696 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5697 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
5698 if (!ecc->calc_buf || !ecc->code_buf) {
5699 ret = -ENOMEM;
5700 goto err_nand_manuf_cleanup;
5701 }
5702 }
5703
5704 /* For many systems, the standard OOB write also works for raw */
5705 if (!ecc->read_oob_raw)
5706 ecc->read_oob_raw = ecc->read_oob;
5707 if (!ecc->write_oob_raw)
5708 ecc->write_oob_raw = ecc->write_oob;
5709
5710 /* propagate ecc info to mtd_info */
5711 mtd->ecc_strength = ecc->strength;
5712 mtd->ecc_step_size = ecc->size;
5713
5714 /*
5715 * Set the number of read / write steps for one page depending on ECC
5716 * mode.
5717 */
5718 ecc->steps = mtd->writesize / ecc->size;
5719 if (ecc->steps * ecc->size != mtd->writesize) {
5720 WARN(1, "Invalid ECC parameters\n");
5721 ret = -EINVAL;
5722 goto err_nand_manuf_cleanup;
5723 }
5724 ecc->total = ecc->steps * ecc->bytes;
5725 if (ecc->total > mtd->oobsize) {
5726 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
5727 ret = -EINVAL;
5728 goto err_nand_manuf_cleanup;
5729 }
5730
5731 /*
5732 * The number of bytes available for a client to place data into
5733 * the out of band area.
5734 */
5735 ret = mtd_ooblayout_count_freebytes(mtd);
5736 if (ret < 0)
5737 ret = 0;
5738
5739 mtd->oobavail = ret;
5740
5741 /* ECC sanity check: warn if it's too weak */
5742 if (!nand_ecc_strength_good(chip))
5743 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5744 mtd->name);
5745
5746 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5747 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5748 switch (ecc->steps) {
5749 case 2:
5750 mtd->subpage_sft = 1;
5751 break;
5752 case 4:
5753 case 8:
5754 case 16:
5755 mtd->subpage_sft = 2;
5756 break;
5757 }
5758 }
5759 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5760
5761 /* Invalidate the pagebuffer reference */
5762 chip->pagecache.page = -1;
5763
5764 /* Large page NAND with SOFT_ECC should support subpage reads */
5765 switch (ecc->mode) {
5766 case NAND_ECC_SOFT:
5767 if (chip->page_shift > 9)
5768 chip->options |= NAND_SUBPAGE_READ;
5769 break;
5770
5771 default:
5772 break;
5773 }
5774
5775 ret = nanddev_init(&chip->base, &rawnand_ops, mtd->owner);
5776 if (ret)
5777 goto err_nand_manuf_cleanup;
5778
5779 /* Adjust the MTD_CAP_ flags when NAND_ROM is set. */
5780 if (chip->options & NAND_ROM)
5781 mtd->flags = MTD_CAP_ROM;
5782
5783 /* Fill in remaining MTD driver data */
5784 mtd->_erase = nand_erase;
5785 mtd->_point = NULL;
5786 mtd->_unpoint = NULL;
5787 mtd->_panic_write = panic_nand_write;
5788 mtd->_read_oob = nand_read_oob;
5789 mtd->_write_oob = nand_write_oob;
5790 mtd->_sync = nand_sync;
5791 mtd->_lock = NULL;
5792 mtd->_unlock = NULL;
5793 mtd->_suspend = nand_suspend;
5794 mtd->_resume = nand_resume;
5795 mtd->_reboot = nand_shutdown;
5796 mtd->_block_isreserved = nand_block_isreserved;
5797 mtd->_block_isbad = nand_block_isbad;
5798 mtd->_block_markbad = nand_block_markbad;
5799 mtd->_max_bad_blocks = nanddev_mtd_max_bad_blocks;
5800
5801 /*
5802 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5803 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5804 * properly set.
5805 */
5806 if (!mtd->bitflip_threshold)
5807 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5808
5809 /* Initialize the ->data_interface field. */
5810 ret = nand_init_data_interface(chip);
5811 if (ret)
5812 goto err_nanddev_cleanup;
5813
5814 /* Enter fastest possible mode on all dies. */
5815 for (i = 0; i < nanddev_ntargets(&chip->base); i++) {
5816 ret = nand_setup_data_interface(chip, i);
5817 if (ret)
5818 goto err_nanddev_cleanup;
5819 }
5820
5821 /* Check, if we should skip the bad block table scan */
5822 if (chip->options & NAND_SKIP_BBTSCAN)
5823 return 0;
5824
5825 /* Build bad block table */
5826 ret = nand_create_bbt(chip);
5827 if (ret)
5828 goto err_nanddev_cleanup;
5829
5830 return 0;
5831
5832
5833err_nanddev_cleanup:
5834 nanddev_cleanup(&chip->base);
5835
5836err_nand_manuf_cleanup:
5837 nand_manufacturer_cleanup(chip);
5838
5839err_free_buf:
5840 kfree(chip->data_buf);
5841 kfree(ecc->code_buf);
5842 kfree(ecc->calc_buf);
5843
5844 return ret;
5845}
5846
5847static int nand_attach(struct nand_chip *chip)
5848{
5849 if (chip->controller->ops && chip->controller->ops->attach_chip)
5850 return chip->controller->ops->attach_chip(chip);
5851
5852 return 0;
5853}
5854
5855static void nand_detach(struct nand_chip *chip)
5856{
5857 if (chip->controller->ops && chip->controller->ops->detach_chip)
5858 chip->controller->ops->detach_chip(chip);
5859}
5860
5861/**
5862 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
5863 * @chip: NAND chip object
5864 * @maxchips: number of chips to scan for.
5865 * @ids: optional flash IDs table
5866 *
5867 * This fills out all the uninitialized function pointers with the defaults.
5868 * The flash ID is read and the mtd/chip structures are filled with the
5869 * appropriate values.
5870 */
5871int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips,
5872 struct nand_flash_dev *ids)
5873{
5874 int ret;
5875
5876 if (!maxchips)
5877 return -EINVAL;
5878
5879 ret = nand_scan_ident(chip, maxchips, ids);
5880 if (ret)
5881 return ret;
5882
5883 ret = nand_attach(chip);
5884 if (ret)
5885 goto cleanup_ident;
5886
5887 ret = nand_scan_tail(chip);
5888 if (ret)
5889 goto detach_chip;
5890
5891 return 0;
5892
5893detach_chip:
5894 nand_detach(chip);
5895cleanup_ident:
5896 nand_scan_ident_cleanup(chip);
5897
5898 return ret;
5899}
5900EXPORT_SYMBOL(nand_scan_with_ids);
5901
5902/**
5903 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
5904 * @chip: NAND chip object
5905 */
5906void nand_cleanup(struct nand_chip *chip)
5907{
5908 if (chip->ecc.mode == NAND_ECC_SOFT &&
5909 chip->ecc.algo == NAND_ECC_BCH)
5910 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
5911
5912 nanddev_cleanup(&chip->base);
5913
5914 /* Free bad block table memory */
5915 kfree(chip->bbt);
5916 kfree(chip->data_buf);
5917 kfree(chip->ecc.code_buf);
5918 kfree(chip->ecc.calc_buf);
5919
5920 /* Free bad block descriptor memory */
5921 if (chip->badblock_pattern && chip->badblock_pattern->options
5922 & NAND_BBT_DYNAMICSTRUCT)
5923 kfree(chip->badblock_pattern);
5924
5925 /* Free manufacturer priv data. */
5926 nand_manufacturer_cleanup(chip);
5927
5928 /* Free controller specific allocations after chip identification */
5929 nand_detach(chip);
5930
5931 /* Free identification phase allocations */
5932 nand_scan_ident_cleanup(chip);
5933}
5934
5935EXPORT_SYMBOL_GPL(nand_cleanup);
5936
5937/**
5938 * nand_release - [NAND Interface] Unregister the MTD device and free resources
5939 * held by the NAND device
5940 * @chip: NAND chip object
5941 */
5942void nand_release(struct nand_chip *chip)
5943{
5944 mtd_device_unregister(nand_to_mtd(chip));
5945 nand_cleanup(chip);
5946}
5947EXPORT_SYMBOL_GPL(nand_release);
5948
5949MODULE_LICENSE("GPL");
5950MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5951MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5952MODULE_DESCRIPTION("Generic NAND flash driver code");