Root/drivers/mtd/nand/nand_base.c

Source at commit b05a5adf03613de371c77c3235f7d970d7cd0c71 created 9 years 5 months ago.
By Lars-Peter Clausen, NAND: Optimize reading the eec data for the JZ4740 (evil hack)
1/*
2 * drivers/mtd/nand.c
3 *
4 * Overview:
5 * This is the generic MTD driver for NAND flash devices. It should be
6 * capable of working with almost all NAND chips currently available.
7 * Basic support for AG-AND chips is provided.
8 *
9 * Additional technical information is available on
10 * http://www.linux-mtd.infradead.org/doc/nand.html
11 *
12 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
13 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
14 *
15 * Credits:
16 * David Woodhouse for adding multichip support
17 *
18 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
19 * rework for 2K page size chips
20 *
21 * TODO:
22 * Enable cached programming for 2k page size chips
23 * Check, if mtd->ecctype should be set to MTD_ECC_HW
24 * if we have HW ecc support.
25 * The AG-AND chips have nice features for speed improvement,
26 * which are not supported yet. Read / program 4 pages in one go.
27 * BBT table is not serialized, has to be fixed
28 *
29 * This program is free software; you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License version 2 as
31 * published by the Free Software Foundation.
32 *
33 */
34
35#include <linux/module.h>
36#include <linux/delay.h>
37#include <linux/errno.h>
38#include <linux/err.h>
39#include <linux/sched.h>
40#include <linux/slab.h>
41#include <linux/types.h>
42#include <linux/mtd/mtd.h>
43#include <linux/mtd/nand.h>
44#include <linux/mtd/nand_ecc.h>
45#include <linux/mtd/nand_bch.h>
46#include <linux/interrupt.h>
47#include <linux/bitops.h>
48#include <linux/leds.h>
49#include <linux/io.h>
50
51#ifdef CONFIG_MTD_PARTITIONS
52#include <linux/mtd/partitions.h>
53#endif
54
55/* Define default oob placement schemes for large and small page devices */
56static struct nand_ecclayout nand_oob_8 = {
57    .eccbytes = 3,
58    .eccpos = {0, 1, 2},
59    .oobfree = {
60        {.offset = 3,
61         .length = 2},
62        {.offset = 6,
63         .length = 2} }
64};
65
66static struct nand_ecclayout nand_oob_16 = {
67    .eccbytes = 6,
68    .eccpos = {0, 1, 2, 3, 6, 7},
69    .oobfree = {
70        {.offset = 8,
71         . length = 8} }
72};
73
74static struct nand_ecclayout nand_oob_64 = {
75    .eccbytes = 24,
76    .eccpos = {
77           40, 41, 42, 43, 44, 45, 46, 47,
78           48, 49, 50, 51, 52, 53, 54, 55,
79           56, 57, 58, 59, 60, 61, 62, 63},
80    .oobfree = {
81        {.offset = 2,
82         .length = 38} }
83};
84
85static struct nand_ecclayout nand_oob_128 = {
86    .eccbytes = 48,
87    .eccpos = {
88           80, 81, 82, 83, 84, 85, 86, 87,
89           88, 89, 90, 91, 92, 93, 94, 95,
90           96, 97, 98, 99, 100, 101, 102, 103,
91           104, 105, 106, 107, 108, 109, 110, 111,
92           112, 113, 114, 115, 116, 117, 118, 119,
93           120, 121, 122, 123, 124, 125, 126, 127},
94    .oobfree = {
95        {.offset = 2,
96         .length = 78} }
97};
98
99static int nand_get_device(struct nand_chip *chip, struct mtd_info *mtd,
100               int new_state);
101
102static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
103                 struct mtd_oob_ops *ops);
104
105/*
106 * For devices which display every fart in the system on a separate LED. Is
107 * compiled away when LED support is disabled.
108 */
109DEFINE_LED_TRIGGER(nand_led_trigger);
110
111static int check_offs_len(struct mtd_info *mtd,
112                    loff_t ofs, uint64_t len)
113{
114    struct nand_chip *chip = mtd->priv;
115    int ret = 0;
116
117    /* Start address must align on block boundary */
118    if (ofs & ((1 << chip->phys_erase_shift) - 1)) {
119        DEBUG(MTD_DEBUG_LEVEL0, "%s: Unaligned address\n", __func__);
120        ret = -EINVAL;
121    }
122
123    /* Length must align on block boundary */
124    if (len & ((1 << chip->phys_erase_shift) - 1)) {
125        DEBUG(MTD_DEBUG_LEVEL0, "%s: Length not block aligned\n",
126                    __func__);
127        ret = -EINVAL;
128    }
129
130    /* Do not allow past end of device */
131    if (ofs + len > mtd->size) {
132        DEBUG(MTD_DEBUG_LEVEL0, "%s: Past end of device\n",
133                    __func__);
134        ret = -EINVAL;
135    }
136
137    return ret;
138}
139
140/**
141 * nand_release_device - [GENERIC] release chip
142 * @mtd: MTD device structure
143 *
144 * Deselect, release chip lock and wake up anyone waiting on the device
145 */
146static void nand_release_device(struct mtd_info *mtd)
147{
148    struct nand_chip *chip = mtd->priv;
149
150    /* De-select the NAND device */
151    chip->select_chip(mtd, -1);
152
153    /* Release the controller and the chip */
154    spin_lock(&chip->controller->lock);
155    chip->controller->active = NULL;
156    chip->state = FL_READY;
157    wake_up(&chip->controller->wq);
158    spin_unlock(&chip->controller->lock);
159}
160
161/**
162 * nand_read_byte - [DEFAULT] read one byte from the chip
163 * @mtd: MTD device structure
164 *
165 * Default read function for 8bit buswith
166 */
167static uint8_t nand_read_byte(struct mtd_info *mtd)
168{
169    struct nand_chip *chip = mtd->priv;
170    return readb(chip->IO_ADDR_R);
171}
172
173/**
174 * nand_read_byte16 - [DEFAULT] read one byte endianess aware from the chip
175 * @mtd: MTD device structure
176 *
177 * Default read function for 16bit buswith with
178 * endianess conversion
179 */
180static uint8_t nand_read_byte16(struct mtd_info *mtd)
181{
182    struct nand_chip *chip = mtd->priv;
183    return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
184}
185
186/**
187 * nand_read_word - [DEFAULT] read one word from the chip
188 * @mtd: MTD device structure
189 *
190 * Default read function for 16bit buswith without
191 * endianess conversion
192 */
193static u16 nand_read_word(struct mtd_info *mtd)
194{
195    struct nand_chip *chip = mtd->priv;
196    return readw(chip->IO_ADDR_R);
197}
198
199/**
200 * nand_select_chip - [DEFAULT] control CE line
201 * @mtd: MTD device structure
202 * @chipnr: chipnumber to select, -1 for deselect
203 *
204 * Default select function for 1 chip devices.
205 */
206static void nand_select_chip(struct mtd_info *mtd, int chipnr)
207{
208    struct nand_chip *chip = mtd->priv;
209
210    switch (chipnr) {
211    case -1:
212        chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
213        break;
214    case 0:
215        break;
216
217    default:
218        BUG();
219    }
220}
221
222/**
223 * nand_write_buf - [DEFAULT] write buffer to chip
224 * @mtd: MTD device structure
225 * @buf: data buffer
226 * @len: number of bytes to write
227 *
228 * Default write function for 8bit buswith
229 */
230static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
231{
232    int i;
233    struct nand_chip *chip = mtd->priv;
234
235    for (i = 0; i < len; i++)
236        writeb(buf[i], chip->IO_ADDR_W);
237}
238
239/**
240 * nand_read_buf - [DEFAULT] read chip data into buffer
241 * @mtd: MTD device structure
242 * @buf: buffer to store date
243 * @len: number of bytes to read
244 *
245 * Default read function for 8bit buswith
246 */
247static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
248{
249    int i;
250    struct nand_chip *chip = mtd->priv;
251
252    for (i = 0; i < len; i++)
253        buf[i] = readb(chip->IO_ADDR_R);
254}
255
256/**
257 * nand_verify_buf - [DEFAULT] Verify chip data against buffer
258 * @mtd: MTD device structure
259 * @buf: buffer containing the data to compare
260 * @len: number of bytes to compare
261 *
262 * Default verify function for 8bit buswith
263 */
264static int nand_verify_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
265{
266    int i;
267    struct nand_chip *chip = mtd->priv;
268
269    for (i = 0; i < len; i++)
270        if (buf[i] != readb(chip->IO_ADDR_R))
271            return -EFAULT;
272    return 0;
273}
274
275/**
276 * nand_write_buf16 - [DEFAULT] write buffer to chip
277 * @mtd: MTD device structure
278 * @buf: data buffer
279 * @len: number of bytes to write
280 *
281 * Default write function for 16bit buswith
282 */
283static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
284{
285    int i;
286    struct nand_chip *chip = mtd->priv;
287    u16 *p = (u16 *) buf;
288    len >>= 1;
289
290    for (i = 0; i < len; i++)
291        writew(p[i], chip->IO_ADDR_W);
292
293}
294
295/**
296 * nand_read_buf16 - [DEFAULT] read chip data into buffer
297 * @mtd: MTD device structure
298 * @buf: buffer to store date
299 * @len: number of bytes to read
300 *
301 * Default read function for 16bit buswith
302 */
303static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
304{
305    int i;
306    struct nand_chip *chip = mtd->priv;
307    u16 *p = (u16 *) buf;
308    len >>= 1;
309
310    for (i = 0; i < len; i++)
311        p[i] = readw(chip->IO_ADDR_R);
312}
313
314/**
315 * nand_verify_buf16 - [DEFAULT] Verify chip data against buffer
316 * @mtd: MTD device structure
317 * @buf: buffer containing the data to compare
318 * @len: number of bytes to compare
319 *
320 * Default verify function for 16bit buswith
321 */
322static int nand_verify_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
323{
324    int i;
325    struct nand_chip *chip = mtd->priv;
326    u16 *p = (u16 *) buf;
327    len >>= 1;
328
329    for (i = 0; i < len; i++)
330        if (p[i] != readw(chip->IO_ADDR_R))
331            return -EFAULT;
332
333    return 0;
334}
335
336/**
337 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
338 * @mtd: MTD device structure
339 * @ofs: offset from device start
340 * @getchip: 0, if the chip is already selected
341 *
342 * Check, if the block is bad.
343 */
344static int nand_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip)
345{
346    int page, chipnr, res = 0;
347    struct nand_chip *chip = mtd->priv;
348    u16 bad;
349
350    if (chip->options & NAND_BBT_SCANLASTPAGE)
351        ofs += mtd->erasesize - mtd->writesize;
352
353    page = (int)(ofs >> chip->page_shift) & chip->pagemask;
354
355    if (getchip) {
356        chipnr = (int)(ofs >> chip->chip_shift);
357
358        nand_get_device(chip, mtd, FL_READING);
359
360        /* Select the NAND device */
361        chip->select_chip(mtd, chipnr);
362    }
363
364    if (chip->options & NAND_BUSWIDTH_16) {
365        chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos & 0xFE,
366                  page);
367        bad = cpu_to_le16(chip->read_word(mtd));
368        if (chip->badblockpos & 0x1)
369            bad >>= 8;
370        else
371            bad &= 0xFF;
372    } else {
373        chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos, page);
374        bad = chip->read_byte(mtd);
375    }
376
377    if (likely(chip->badblockbits == 8))
378        res = bad != 0xFF;
379    else
380        res = hweight8(bad) < chip->badblockbits;
381
382    if (getchip)
383        nand_release_device(mtd);
384
385    return res;
386}
387
388/**
389 * nand_default_block_markbad - [DEFAULT] mark a block bad
390 * @mtd: MTD device structure
391 * @ofs: offset from device start
392 *
393 * This is the default implementation, which can be overridden by
394 * a hardware specific driver.
395*/
396static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
397{
398    struct nand_chip *chip = mtd->priv;
399    uint8_t buf[2] = { 0, 0 };
400    int block, ret, i = 0;
401
402    if (chip->options & NAND_BBT_SCANLASTPAGE)
403        ofs += mtd->erasesize - mtd->writesize;
404
405    /* Get block number */
406    block = (int)(ofs >> chip->bbt_erase_shift);
407    if (chip->bbt)
408        chip->bbt[block >> 2] |= 0x01 << ((block & 0x03) << 1);
409
410    /* Do we have a flash based bad block table ? */
411    if (chip->options & NAND_USE_FLASH_BBT)
412        ret = nand_update_bbt(mtd, ofs);
413    else {
414        nand_get_device(chip, mtd, FL_WRITING);
415
416        /* Write to first two pages and to byte 1 and 6 if necessary.
417         * If we write to more than one location, the first error
418         * encountered quits the procedure. We write two bytes per
419         * location, so we dont have to mess with 16 bit access.
420         */
421        do {
422            chip->ops.len = chip->ops.ooblen = 2;
423            chip->ops.datbuf = NULL;
424            chip->ops.oobbuf = buf;
425            chip->ops.ooboffs = chip->badblockpos & ~0x01;
426
427            ret = nand_do_write_oob(mtd, ofs, &chip->ops);
428
429            if (!ret && (chip->options & NAND_BBT_SCANBYTE1AND6)) {
430                chip->ops.ooboffs = NAND_SMALL_BADBLOCK_POS
431                    & ~0x01;
432                ret = nand_do_write_oob(mtd, ofs, &chip->ops);
433            }
434            i++;
435            ofs += mtd->writesize;
436        } while (!ret && (chip->options & NAND_BBT_SCAN2NDPAGE) &&
437                i < 2);
438
439        nand_release_device(mtd);
440    }
441    if (!ret)
442        mtd->ecc_stats.badblocks++;
443
444    return ret;
445}
446
447/**
448 * nand_check_wp - [GENERIC] check if the chip is write protected
449 * @mtd: MTD device structure
450 * Check, if the device is write protected
451 *
452 * The function expects, that the device is already selected
453 */
454static int nand_check_wp(struct mtd_info *mtd)
455{
456    struct nand_chip *chip = mtd->priv;
457
458    /* broken xD cards report WP despite being writable */
459    if (chip->options & NAND_BROKEN_XD)
460        return 0;
461
462    /* Check the WP bit */
463    chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
464    return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
465}
466
467/**
468 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
469 * @mtd: MTD device structure
470 * @ofs: offset from device start
471 * @getchip: 0, if the chip is already selected
472 * @allowbbt: 1, if its allowed to access the bbt area
473 *
474 * Check, if the block is bad. Either by reading the bad block table or
475 * calling of the scan function.
476 */
477static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int getchip,
478                   int allowbbt)
479{
480    struct nand_chip *chip = mtd->priv;
481
482    if (!chip->bbt)
483        return chip->block_bad(mtd, ofs, getchip);
484
485    /* Return info from the table */
486    return nand_isbad_bbt(mtd, ofs, allowbbt);
487}
488
489/**
490 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
491 * @mtd: MTD device structure
492 * @timeo: Timeout
493 *
494 * Helper function for nand_wait_ready used when needing to wait in interrupt
495 * context.
496 */
497static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
498{
499    struct nand_chip *chip = mtd->priv;
500    int i;
501
502    /* Wait for the device to get ready */
503    for (i = 0; i < timeo; i++) {
504        if (chip->dev_ready(mtd))
505            break;
506        touch_softlockup_watchdog();
507        mdelay(1);
508    }
509}
510
511/*
512 * Wait for the ready pin, after a command
513 * The timeout is catched later.
514 */
515void nand_wait_ready(struct mtd_info *mtd)
516{
517    struct nand_chip *chip = mtd->priv;
518    unsigned long timeo = jiffies + 2;
519
520    /* 400ms timeout */
521    if (in_interrupt() || oops_in_progress)
522        return panic_nand_wait_ready(mtd, 400);
523
524    led_trigger_event(nand_led_trigger, LED_FULL);
525    /* wait until command is processed or timeout occures */
526    do {
527        if (chip->dev_ready(mtd))
528            break;
529        touch_softlockup_watchdog();
530    } while (time_before(jiffies, timeo));
531    led_trigger_event(nand_led_trigger, LED_OFF);
532}
533EXPORT_SYMBOL_GPL(nand_wait_ready);
534
535/**
536 * nand_command - [DEFAULT] Send command to NAND device
537 * @mtd: MTD device structure
538 * @command: the command to be sent
539 * @column: the column address for this command, -1 if none
540 * @page_addr: the page address for this command, -1 if none
541 *
542 * Send command to NAND device. This function is used for small page
543 * devices (256/512 Bytes per page)
544 */
545static void nand_command(struct mtd_info *mtd, unsigned int command,
546             int column, int page_addr)
547{
548    register struct nand_chip *chip = mtd->priv;
549    int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
550
551    /*
552     * Write out the command to the device.
553     */
554    if (command == NAND_CMD_SEQIN) {
555        int readcmd;
556
557        if (column >= mtd->writesize) {
558            /* OOB area */
559            column -= mtd->writesize;
560            readcmd = NAND_CMD_READOOB;
561        } else if (column < 256) {
562            /* First 256 bytes --> READ0 */
563            readcmd = NAND_CMD_READ0;
564        } else {
565            column -= 256;
566            readcmd = NAND_CMD_READ1;
567        }
568        chip->cmd_ctrl(mtd, readcmd, ctrl);
569        ctrl &= ~NAND_CTRL_CHANGE;
570    }
571    chip->cmd_ctrl(mtd, command, ctrl);
572
573    /*
574     * Address cycle, when necessary
575     */
576    ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
577    /* Serially input address */
578    if (column != -1) {
579        /* Adjust columns for 16 bit buswidth */
580        if (chip->options & NAND_BUSWIDTH_16)
581            column >>= 1;
582        chip->cmd_ctrl(mtd, column, ctrl);
583        ctrl &= ~NAND_CTRL_CHANGE;
584    }
585    if (page_addr != -1) {
586        chip->cmd_ctrl(mtd, page_addr, ctrl);
587        ctrl &= ~NAND_CTRL_CHANGE;
588        chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
589        /* One more address cycle for devices > 32MiB */
590        if (chip->chipsize > (32 << 20))
591            chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
592    }
593    chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
594
595    /*
596     * program and erase have their own busy handlers
597     * status and sequential in needs no delay
598     */
599    switch (command) {
600
601    case NAND_CMD_PAGEPROG:
602    case NAND_CMD_ERASE1:
603    case NAND_CMD_ERASE2:
604    case NAND_CMD_SEQIN:
605    case NAND_CMD_STATUS:
606        return;
607
608    case NAND_CMD_RESET:
609        if (chip->dev_ready)
610            break;
611        udelay(chip->chip_delay);
612        chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
613                   NAND_CTRL_CLE | NAND_CTRL_CHANGE);
614        chip->cmd_ctrl(mtd,
615                   NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
616        while (!(chip->read_byte(mtd) & NAND_STATUS_READY))
617                ;
618        return;
619
620        /* This applies to read commands */
621    default:
622        /*
623         * If we don't have access to the busy pin, we apply the given
624         * command delay
625         */
626        if (!chip->dev_ready) {
627            udelay(chip->chip_delay);
628            return;
629        }
630    }
631    /* Apply this short delay always to ensure that we do wait tWB in
632     * any case on any machine. */
633    ndelay(100);
634
635    nand_wait_ready(mtd);
636}
637
638/**
639 * nand_command_lp - [DEFAULT] Send command to NAND large page device
640 * @mtd: MTD device structure
641 * @command: the command to be sent
642 * @column: the column address for this command, -1 if none
643 * @page_addr: the page address for this command, -1 if none
644 *
645 * Send command to NAND device. This is the version for the new large page
646 * devices We dont have the separate regions as we have in the small page
647 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
648 */
649static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
650                int column, int page_addr)
651{
652    register struct nand_chip *chip = mtd->priv;
653
654    /* Emulate NAND_CMD_READOOB */
655    if (command == NAND_CMD_READOOB) {
656        column += mtd->writesize;
657        command = NAND_CMD_READ0;
658    }
659
660    /* Command latch cycle */
661    chip->cmd_ctrl(mtd, command & 0xff,
662               NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
663
664    if (column != -1 || page_addr != -1) {
665        int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
666
667        /* Serially input address */
668        if (column != -1) {
669            /* Adjust columns for 16 bit buswidth */
670            if (chip->options & NAND_BUSWIDTH_16)
671                column >>= 1;
672            chip->cmd_ctrl(mtd, column, ctrl);
673            ctrl &= ~NAND_CTRL_CHANGE;
674            chip->cmd_ctrl(mtd, column >> 8, ctrl);
675        }
676        if (page_addr != -1) {
677            chip->cmd_ctrl(mtd, page_addr, ctrl);
678            chip->cmd_ctrl(mtd, page_addr >> 8,
679                       NAND_NCE | NAND_ALE);
680            /* One more address cycle for devices > 128MiB */
681            if (chip->chipsize > (128 << 20))
682                chip->cmd_ctrl(mtd, page_addr >> 16,
683                           NAND_NCE | NAND_ALE);
684        }
685    }
686    chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
687
688    /*
689     * program and erase have their own busy handlers
690     * status, sequential in, and deplete1 need no delay
691     */
692    switch (command) {
693
694    case NAND_CMD_CACHEDPROG:
695    case NAND_CMD_PAGEPROG:
696    case NAND_CMD_ERASE1:
697    case NAND_CMD_ERASE2:
698    case NAND_CMD_SEQIN:
699    case NAND_CMD_RNDIN:
700    case NAND_CMD_STATUS:
701    case NAND_CMD_DEPLETE1:
702        return;
703
704        /*
705         * read error status commands require only a short delay
706         */
707    case NAND_CMD_STATUS_ERROR:
708    case NAND_CMD_STATUS_ERROR0:
709    case NAND_CMD_STATUS_ERROR1:
710    case NAND_CMD_STATUS_ERROR2:
711    case NAND_CMD_STATUS_ERROR3:
712        udelay(chip->chip_delay);
713        return;
714
715    case NAND_CMD_RESET:
716        if (chip->dev_ready)
717            break;
718        udelay(chip->chip_delay);
719        chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
720                   NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
721        chip->cmd_ctrl(mtd, NAND_CMD_NONE,
722                   NAND_NCE | NAND_CTRL_CHANGE);
723        while (!(chip->read_byte(mtd) & NAND_STATUS_READY))
724                ;
725        return;
726
727    case NAND_CMD_RNDOUT:
728        /* No ready / busy check necessary */
729        chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
730                   NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
731        chip->cmd_ctrl(mtd, NAND_CMD_NONE,
732                   NAND_NCE | NAND_CTRL_CHANGE);
733        return;
734
735    case NAND_CMD_READ0:
736        chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
737                   NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
738        chip->cmd_ctrl(mtd, NAND_CMD_NONE,
739                   NAND_NCE | NAND_CTRL_CHANGE);
740
741        /* This applies to read commands */
742    default:
743        /*
744         * If we don't have access to the busy pin, we apply the given
745         * command delay
746         */
747        if (!chip->dev_ready) {
748            udelay(chip->chip_delay);
749            return;
750        }
751    }
752
753    /* Apply this short delay always to ensure that we do wait tWB in
754     * any case on any machine. */
755    ndelay(100);
756
757    nand_wait_ready(mtd);
758}
759
760/**
761 * panic_nand_get_device - [GENERIC] Get chip for selected access
762 * @chip: the nand chip descriptor
763 * @mtd: MTD device structure
764 * @new_state: the state which is requested
765 *
766 * Used when in panic, no locks are taken.
767 */
768static void panic_nand_get_device(struct nand_chip *chip,
769              struct mtd_info *mtd, int new_state)
770{
771    /* Hardware controller shared among independend devices */
772    chip->controller->active = chip;
773    chip->state = new_state;
774}
775
776/**
777 * nand_get_device - [GENERIC] Get chip for selected access
778 * @chip: the nand chip descriptor
779 * @mtd: MTD device structure
780 * @new_state: the state which is requested
781 *
782 * Get the device and lock it for exclusive access
783 */
784static int
785nand_get_device(struct nand_chip *chip, struct mtd_info *mtd, int new_state)
786{
787    spinlock_t *lock = &chip->controller->lock;
788    wait_queue_head_t *wq = &chip->controller->wq;
789    DECLARE_WAITQUEUE(wait, current);
790retry:
791    spin_lock(lock);
792
793    /* Hardware controller shared among independent devices */
794    if (!chip->controller->active)
795        chip->controller->active = chip;
796
797    if (chip->controller->active == chip && chip->state == FL_READY) {
798        chip->state = new_state;
799        spin_unlock(lock);
800        return 0;
801    }
802    if (new_state == FL_PM_SUSPENDED) {
803        if (chip->controller->active->state == FL_PM_SUSPENDED) {
804            chip->state = FL_PM_SUSPENDED;
805            spin_unlock(lock);
806            return 0;
807        }
808    }
809    set_current_state(TASK_UNINTERRUPTIBLE);
810    add_wait_queue(wq, &wait);
811    spin_unlock(lock);
812    schedule();
813    remove_wait_queue(wq, &wait);
814    goto retry;
815}
816
817/**
818 * panic_nand_wait - [GENERIC] wait until the command is done
819 * @mtd: MTD device structure
820 * @chip: NAND chip structure
821 * @timeo: Timeout
822 *
823 * Wait for command done. This is a helper function for nand_wait used when
824 * we are in interrupt context. May happen when in panic and trying to write
825 * an oops through mtdoops.
826 */
827static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
828                unsigned long timeo)
829{
830    int i;
831    for (i = 0; i < timeo; i++) {
832        if (chip->dev_ready) {
833            if (chip->dev_ready(mtd))
834                break;
835        } else {
836            if (chip->read_byte(mtd) & NAND_STATUS_READY)
837                break;
838        }
839        mdelay(1);
840    }
841}
842
843/**
844 * nand_wait - [DEFAULT] wait until the command is done
845 * @mtd: MTD device structure
846 * @chip: NAND chip structure
847 *
848 * Wait for command done. This applies to erase and program only
849 * Erase can take up to 400ms and program up to 20ms according to
850 * general NAND and SmartMedia specs
851 */
852static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
853{
854
855    unsigned long timeo = jiffies;
856    int status, state = chip->state;
857
858    if (state == FL_ERASING)
859        timeo += (HZ * 400) / 1000;
860    else
861        timeo += (HZ * 20) / 1000;
862
863    led_trigger_event(nand_led_trigger, LED_FULL);
864
865    /* Apply this short delay always to ensure that we do wait tWB in
866     * any case on any machine. */
867    ndelay(100);
868
869    if ((state == FL_ERASING) && (chip->options & NAND_IS_AND))
870        chip->cmdfunc(mtd, NAND_CMD_STATUS_MULTI, -1, -1);
871    else
872        chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
873
874    if (in_interrupt() || oops_in_progress)
875        panic_nand_wait(mtd, chip, timeo);
876    else {
877        while (time_before(jiffies, timeo)) {
878            if (chip->dev_ready) {
879                if (chip->dev_ready(mtd))
880                    break;
881            } else {
882                if (chip->read_byte(mtd) & NAND_STATUS_READY)
883                    break;
884            }
885            cond_resched();
886        }
887    }
888    led_trigger_event(nand_led_trigger, LED_OFF);
889
890    status = (int)chip->read_byte(mtd);
891    return status;
892}
893
894/**
895 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
896 *
897 * @mtd: mtd info
898 * @ofs: offset to start unlock from
899 * @len: length to unlock
900 * @invert: when = 0, unlock the range of blocks within the lower and
901 * upper boundary address
902 * when = 1, unlock the range of blocks outside the boundaries
903 * of the lower and upper boundary address
904 *
905 * return - unlock status
906 */
907static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
908                    uint64_t len, int invert)
909{
910    int ret = 0;
911    int status, page;
912    struct nand_chip *chip = mtd->priv;
913
914    /* Submit address of first page to unlock */
915    page = ofs >> chip->page_shift;
916    chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
917
918    /* Submit address of last page to unlock */
919    page = (ofs + len) >> chip->page_shift;
920    chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
921                (page | invert) & chip->pagemask);
922
923    /* Call wait ready function */
924    status = chip->waitfunc(mtd, chip);
925    udelay(1000);
926    /* See if device thinks it succeeded */
927    if (status & 0x01) {
928        DEBUG(MTD_DEBUG_LEVEL0, "%s: Error status = 0x%08x\n",
929                    __func__, status);
930        ret = -EIO;
931    }
932
933    return ret;
934}
935
936/**
937 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
938 *
939 * @mtd: mtd info
940 * @ofs: offset to start unlock from
941 * @len: length to unlock
942 *
943 * return - unlock status
944 */
945int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
946{
947    int ret = 0;
948    int chipnr;
949    struct nand_chip *chip = mtd->priv;
950
951    DEBUG(MTD_DEBUG_LEVEL3, "%s: start = 0x%012llx, len = %llu\n",
952            __func__, (unsigned long long)ofs, len);
953
954    if (check_offs_len(mtd, ofs, len))
955        ret = -EINVAL;
956
957    /* Align to last block address if size addresses end of the device */
958    if (ofs + len == mtd->size)
959        len -= mtd->erasesize;
960
961    nand_get_device(chip, mtd, FL_UNLOCKING);
962
963    /* Shift to get chip number */
964    chipnr = ofs >> chip->chip_shift;
965
966    chip->select_chip(mtd, chipnr);
967
968    /* Check, if it is write protected */
969    if (nand_check_wp(mtd)) {
970        DEBUG(MTD_DEBUG_LEVEL0, "%s: Device is write protected!!!\n",
971                    __func__);
972        ret = -EIO;
973        goto out;
974    }
975
976    ret = __nand_unlock(mtd, ofs, len, 0);
977
978out:
979    /* de-select the NAND device */
980    chip->select_chip(mtd, -1);
981
982    nand_release_device(mtd);
983
984    return ret;
985}
986EXPORT_SYMBOL(nand_unlock);
987
988/**
989 * nand_lock - [REPLACEABLE] locks all blocks present in the device
990 *
991 * @mtd: mtd info
992 * @ofs: offset to start unlock from
993 * @len: length to unlock
994 *
995 * return - lock status
996 *
997 * This feature is not supported in many NAND parts. 'Micron' NAND parts
998 * do have this feature, but it allows only to lock all blocks, not for
999 * specified range for block.
1000 *
1001 * Implementing 'lock' feature by making use of 'unlock', for now.
1002 */
1003int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1004{
1005    int ret = 0;
1006    int chipnr, status, page;
1007    struct nand_chip *chip = mtd->priv;
1008
1009    DEBUG(MTD_DEBUG_LEVEL3, "%s: start = 0x%012llx, len = %llu\n",
1010            __func__, (unsigned long long)ofs, len);
1011
1012    if (check_offs_len(mtd, ofs, len))
1013        ret = -EINVAL;
1014
1015    nand_get_device(chip, mtd, FL_LOCKING);
1016
1017    /* Shift to get chip number */
1018    chipnr = ofs >> chip->chip_shift;
1019
1020    chip->select_chip(mtd, chipnr);
1021
1022    /* Check, if it is write protected */
1023    if (nand_check_wp(mtd)) {
1024        DEBUG(MTD_DEBUG_LEVEL0, "%s: Device is write protected!!!\n",
1025                    __func__);
1026        status = MTD_ERASE_FAILED;
1027        ret = -EIO;
1028        goto out;
1029    }
1030
1031    /* Submit address of first page to lock */
1032    page = ofs >> chip->page_shift;
1033    chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1034
1035    /* Call wait ready function */
1036    status = chip->waitfunc(mtd, chip);
1037    udelay(1000);
1038    /* See if device thinks it succeeded */
1039    if (status & 0x01) {
1040        DEBUG(MTD_DEBUG_LEVEL0, "%s: Error status = 0x%08x\n",
1041                    __func__, status);
1042        ret = -EIO;
1043        goto out;
1044    }
1045
1046    ret = __nand_unlock(mtd, ofs, len, 0x1);
1047
1048out:
1049    /* de-select the NAND device */
1050    chip->select_chip(mtd, -1);
1051
1052    nand_release_device(mtd);
1053
1054    return ret;
1055}
1056EXPORT_SYMBOL(nand_lock);
1057
1058/**
1059 * nand_read_page_raw - [Intern] read raw page data without ecc
1060 * @mtd: mtd info structure
1061 * @chip: nand chip info structure
1062 * @buf: buffer to store read data
1063 * @page: page number to read
1064 *
1065 * Not for syndrome calculating ecc controllers, which use a special oob layout
1066 */
1067static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1068                  uint8_t *buf, int page)
1069{
1070    chip->read_buf(mtd, buf, mtd->writesize);
1071    chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1072    return 0;
1073}
1074
1075/**
1076 * nand_read_page_raw_syndrome - [Intern] read raw page data without ecc
1077 * @mtd: mtd info structure
1078 * @chip: nand chip info structure
1079 * @buf: buffer to store read data
1080 * @page: page number to read
1081 *
1082 * We need a special oob layout and handling even when OOB isn't used.
1083 */
1084static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1085                    struct nand_chip *chip,
1086                    uint8_t *buf, int page)
1087{
1088    int eccsize = chip->ecc.size;
1089    int eccbytes = chip->ecc.bytes;
1090    uint8_t *oob = chip->oob_poi;
1091    int steps, size;
1092
1093    for (steps = chip->ecc.steps; steps > 0; steps--) {
1094        chip->read_buf(mtd, buf, eccsize);
1095        buf += eccsize;
1096
1097        if (chip->ecc.prepad) {
1098            chip->read_buf(mtd, oob, chip->ecc.prepad);
1099            oob += chip->ecc.prepad;
1100        }
1101
1102        chip->read_buf(mtd, oob, eccbytes);
1103        oob += eccbytes;
1104
1105        if (chip->ecc.postpad) {
1106            chip->read_buf(mtd, oob, chip->ecc.postpad);
1107            oob += chip->ecc.postpad;
1108        }
1109    }
1110
1111    size = mtd->oobsize - (oob - chip->oob_poi);
1112    if (size)
1113        chip->read_buf(mtd, oob, size);
1114
1115    return 0;
1116}
1117
1118/**
1119 * nand_read_page_swecc - [REPLACABLE] software ecc based page read function
1120 * @mtd: mtd info structure
1121 * @chip: nand chip info structure
1122 * @buf: buffer to store read data
1123 * @page: page number to read
1124 */
1125static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1126                uint8_t *buf, int page)
1127{
1128    int i, eccsize = chip->ecc.size;
1129    int eccbytes = chip->ecc.bytes;
1130    int eccsteps = chip->ecc.steps;
1131    uint8_t *p = buf;
1132    uint8_t *ecc_calc = chip->buffers->ecccalc;
1133    uint8_t *ecc_code = chip->buffers->ecccode;
1134    uint32_t *eccpos = chip->ecc.layout->eccpos;
1135
1136    chip->ecc.read_page_raw(mtd, chip, buf, page);
1137
1138    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1139        chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1140
1141    for (i = 0; i < chip->ecc.total; i++)
1142        ecc_code[i] = chip->oob_poi[eccpos[i]];
1143
1144    eccsteps = chip->ecc.steps;
1145    p = buf;
1146
1147    for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1148        int stat;
1149
1150        stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1151        if (stat < 0)
1152            mtd->ecc_stats.failed++;
1153        else
1154            mtd->ecc_stats.corrected += stat;
1155    }
1156    return 0;
1157}
1158
1159/**
1160 * nand_read_subpage - [REPLACABLE] software ecc based sub-page read function
1161 * @mtd: mtd info structure
1162 * @chip: nand chip info structure
1163 * @data_offs: offset of requested data within the page
1164 * @readlen: data length
1165 * @bufpoi: buffer to store read data
1166 */
1167static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1168            uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi, int page)
1169{
1170    int start_step, end_step, num_steps;
1171    uint32_t *eccpos = chip->ecc.layout->eccpos;
1172    uint8_t *p;
1173    int data_col_addr, i, gaps = 0;
1174    int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1175    int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1176    int index = 0;
1177
1178    /* Column address wihin the page aligned to ECC size (256bytes). */
1179    start_step = data_offs / chip->ecc.size;
1180    end_step = (data_offs + readlen - 1) / chip->ecc.size;
1181    num_steps = end_step - start_step + 1;
1182
1183    /* Data size aligned to ECC ecc.size*/
1184    datafrag_len = num_steps * chip->ecc.size;
1185    eccfrag_len = num_steps * chip->ecc.bytes;
1186
1187    data_col_addr = start_step * chip->ecc.size;
1188    /* If we read not a page aligned data */
1189    if (data_col_addr != 0)
1190        chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1191
1192    p = bufpoi + data_col_addr;
1193    chip->read_buf(mtd, p, datafrag_len);
1194
1195    /* Calculate ECC */
1196    for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1197        chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1198
1199    /* The performance is faster if to position offsets
1200       according to ecc.pos. Let make sure here that
1201       there are no gaps in ecc positions */
1202    for (i = 0; i < eccfrag_len - 1; i++) {
1203        if (eccpos[i + start_step * chip->ecc.bytes] + 1 !=
1204            eccpos[i + start_step * chip->ecc.bytes + 1]) {
1205            gaps = 1;
1206            break;
1207        }
1208    }
1209    if (gaps) {
1210        chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1211        chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1212    } else {
1213        /* send the command to read the particular ecc bytes */
1214        /* take care about buswidth alignment in read_buf */
1215        index = start_step * chip->ecc.bytes;
1216
1217        aligned_pos = eccpos[index] & ~(busw - 1);
1218        aligned_len = eccfrag_len;
1219        if (eccpos[index] & (busw - 1))
1220            aligned_len++;
1221        if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1222            aligned_len++;
1223
1224        chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1225                    mtd->writesize + aligned_pos, -1);
1226        chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1227    }
1228
1229    for (i = 0; i < eccfrag_len; i++)
1230        chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1231
1232    p = bufpoi + data_col_addr;
1233    for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1234        int stat;
1235
1236        stat = chip->ecc.correct(mtd, p,
1237            &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1238        if (stat < 0)
1239            mtd->ecc_stats.failed++;
1240        else
1241            mtd->ecc_stats.corrected += stat;
1242    }
1243    return 0;
1244}
1245
1246/**
1247 * nand_read_page_hwecc - [REPLACABLE] hardware ecc based page read function
1248 * @mtd: mtd info structure
1249 * @chip: nand chip info structure
1250 * @buf: buffer to store read data
1251 * @page: page number to read
1252 *
1253 * Not for syndrome calculating ecc controllers which need a special oob layout
1254 */
1255static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1256                uint8_t *buf, int page)
1257{
1258    int i, eccsize = chip->ecc.size;
1259    int eccbytes = chip->ecc.bytes;
1260    int eccsteps = chip->ecc.steps;
1261    uint8_t *p = buf;
1262    uint8_t *ecc_calc = chip->buffers->ecccalc;
1263    uint8_t *ecc_code = chip->buffers->ecccode;
1264    uint32_t *eccpos = chip->ecc.layout->eccpos;
1265
1266    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1267        chip->ecc.hwctl(mtd, NAND_ECC_READ);
1268        chip->read_buf(mtd, p, eccsize);
1269        chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1270    }
1271    chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1272
1273    for (i = 0; i < chip->ecc.total; i++)
1274        ecc_code[i] = chip->oob_poi[eccpos[i]];
1275
1276    eccsteps = chip->ecc.steps;
1277    p = buf;
1278
1279    for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1280        int stat;
1281
1282        stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1283        if (stat < 0)
1284            mtd->ecc_stats.failed++;
1285        else
1286            mtd->ecc_stats.corrected += stat;
1287    }
1288    return 0;
1289}
1290
1291/**
1292 * nand_read_page_hwecc_oob_first - [REPLACABLE] hw ecc, read oob first
1293 * @mtd: mtd info structure
1294 * @chip: nand chip info structure
1295 * @buf: buffer to store read data
1296 * @page: page number to read
1297 *
1298 * Hardware ECC for large page chips, require OOB to be read first.
1299 * For this ECC mode, the write_page method is re-used from ECC_HW.
1300 * These methods read/write ECC from the OOB area, unlike the
1301 * ECC_HW_SYNDROME support with multiple ECC steps, follows the
1302 * "infix ECC" scheme and reads/writes ECC from the data area, by
1303 * overwriting the NAND manufacturer bad block markings.
1304 */
1305static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1306    struct nand_chip *chip, uint8_t *buf, int page)
1307{
1308    int i, eccsize = chip->ecc.size;
1309    int eccbytes = chip->ecc.bytes;
1310    int eccsteps = chip->ecc.steps;
1311    uint8_t *p = buf;
1312    uint8_t *ecc_code = chip->buffers->ecccode;
1313    uint32_t *eccpos = chip->ecc.layout->eccpos;
1314    uint8_t *ecc_calc = chip->buffers->ecccalc;
1315
1316    /* Read the OOB area first */
1317    /* Read the OOB area first */
1318    if (mtd->writesize > 512) {
1319        chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize + eccpos[0], page);
1320        chip->read_buf(mtd, ecc_code, chip->ecc.total);
1321        chip->cmdfunc(mtd, NAND_CMD_RNDOUT, 0, -1);
1322    } else {
1323        chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1324        chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1325        chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1326    }
1327
1328    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1329        int stat;
1330
1331        chip->ecc.hwctl(mtd, NAND_ECC_READ);
1332        chip->read_buf(mtd, p, eccsize);
1333        chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1334
1335        stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1336        if (stat < 0)
1337            mtd->ecc_stats.failed++;
1338        else
1339            mtd->ecc_stats.corrected += stat;
1340    }
1341    return 0;
1342}
1343
1344/**
1345 * nand_read_subpage_hwecc_oob_first - [REPLACABLE] hw ecc based sub-page read function
1346 * @mtd: mtd info structure
1347 * @chip: nand chip info structure
1348 * @data_offs: offset of requested data within the page
1349 * @readlen: data length
1350 * @bufpoi: buffer to store read data
1351 * @page: page number to read
1352 *
1353 * Hardware ECC for large page chips, require OOB to be read first.
1354 * For this ECC mode, the write_page method is re-used from ECC_HW.
1355 * These methods read/write ECC from the OOB area, unlike the
1356 * ECC_HW_SYNDROME support with multiple ECC steps, follows the
1357 * "infix ECC" scheme and reads/writes ECC from the data area, by
1358 * overwriting the NAND manufacturer bad block markings.
1359 */
1360static int nand_read_subpage_hwecc_oob_first(struct mtd_info *mtd, struct nand_chip *chip,
1361            uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi, int page)
1362{
1363    int start_step, end_step, num_steps;
1364    uint32_t *eccpos = chip->ecc.layout->eccpos;
1365    uint8_t *p;
1366    int data_col_addr;
1367    int eccsize = chip->ecc.size;
1368    int eccbytes = chip->ecc.bytes;
1369    uint8_t *ecc_code = chip->buffers->ecccode;
1370    uint8_t *ecc_calc = chip->buffers->ecccalc;
1371    int i;
1372
1373    /* Column address wihin the page aligned to ECC size */
1374    start_step = data_offs / chip->ecc.size;
1375    end_step = (data_offs + readlen - 1) / chip->ecc.size;
1376    num_steps = end_step - start_step + 1;
1377
1378    data_col_addr = start_step * chip->ecc.size;
1379
1380    /* Read the OOB area first */
1381    if (mtd->writesize > 512) {
1382        chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize + eccpos[0], page);
1383        chip->read_buf(mtd, ecc_code, chip->ecc.total);
1384        chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1385    } else {
1386        chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1387        chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1388        chip->cmdfunc(mtd, NAND_CMD_READ0, data_col_addr, page);
1389    }
1390
1391    p = bufpoi + data_col_addr;
1392
1393    for (i = eccbytes * start_step; num_steps; num_steps--, i += eccbytes, p += eccsize) {
1394        int stat;
1395
1396        chip->ecc.hwctl(mtd, NAND_ECC_READ);
1397        chip->read_buf(mtd, p, eccsize);
1398        chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1399
1400        stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1401        if (stat < 0)
1402            mtd->ecc_stats.failed++;
1403        else
1404            mtd->ecc_stats.corrected += stat;
1405    }
1406
1407    return 0;
1408}
1409
1410
1411/**
1412 * nand_read_page_syndrome - [REPLACABLE] hardware ecc syndrom based page read
1413 * @mtd: mtd info structure
1414 * @chip: nand chip info structure
1415 * @buf: buffer to store read data
1416 * @page: page number to read
1417 *
1418 * The hw generator calculates the error syndrome automatically. Therefor
1419 * we need a special oob layout and handling.
1420 */
1421static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1422                   uint8_t *buf, int page)
1423{
1424    int i, eccsize = chip->ecc.size;
1425    int eccbytes = chip->ecc.bytes;
1426    int eccsteps = chip->ecc.steps;
1427    uint8_t *p = buf;
1428    uint8_t *oob = chip->oob_poi;
1429
1430    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1431        int stat;
1432
1433        chip->ecc.hwctl(mtd, NAND_ECC_READ);
1434        chip->read_buf(mtd, p, eccsize);
1435
1436        if (chip->ecc.prepad) {
1437            chip->read_buf(mtd, oob, chip->ecc.prepad);
1438            oob += chip->ecc.prepad;
1439        }
1440
1441        chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1442        chip->read_buf(mtd, oob, eccbytes);
1443        stat = chip->ecc.correct(mtd, p, oob, NULL);
1444
1445        if (stat < 0)
1446            mtd->ecc_stats.failed++;
1447        else
1448            mtd->ecc_stats.corrected += stat;
1449
1450        oob += eccbytes;
1451
1452        if (chip->ecc.postpad) {
1453            chip->read_buf(mtd, oob, chip->ecc.postpad);
1454            oob += chip->ecc.postpad;
1455        }
1456    }
1457
1458    /* Calculate remaining oob bytes */
1459    i = mtd->oobsize - (oob - chip->oob_poi);
1460    if (i)
1461        chip->read_buf(mtd, oob, i);
1462
1463    return 0;
1464}
1465
1466/**
1467 * nand_transfer_oob - [Internal] Transfer oob to client buffer
1468 * @chip: nand chip structure
1469 * @oob: oob destination address
1470 * @ops: oob ops structure
1471 * @len: size of oob to transfer
1472 */
1473static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1474                  struct mtd_oob_ops *ops, size_t len)
1475{
1476    switch (ops->mode) {
1477
1478    case MTD_OOB_PLACE:
1479    case MTD_OOB_RAW:
1480        memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1481        return oob + len;
1482
1483    case MTD_OOB_AUTO: {
1484        struct nand_oobfree *free = chip->ecc.layout->oobfree;
1485        uint32_t boffs = 0, roffs = ops->ooboffs;
1486        size_t bytes = 0;
1487
1488        for (; free->length && len; free++, len -= bytes) {
1489            /* Read request not from offset 0 ? */
1490            if (unlikely(roffs)) {
1491                if (roffs >= free->length) {
1492                    roffs -= free->length;
1493                    continue;
1494                }
1495                boffs = free->offset + roffs;
1496                bytes = min_t(size_t, len,
1497                          (free->length - roffs));
1498                roffs = 0;
1499            } else {
1500                bytes = min_t(size_t, len, free->length);
1501                boffs = free->offset;
1502            }
1503            memcpy(oob, chip->oob_poi + boffs, bytes);
1504            oob += bytes;
1505        }
1506        return oob;
1507    }
1508    default:
1509        BUG();
1510    }
1511    return NULL;
1512}
1513
1514/**
1515 * nand_do_read_ops - [Internal] Read data with ECC
1516 *
1517 * @mtd: MTD device structure
1518 * @from: offset to read from
1519 * @ops: oob ops structure
1520 *
1521 * Internal function. Called with chip held.
1522 */
1523static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1524                struct mtd_oob_ops *ops)
1525{
1526    int chipnr, page, realpage, col, bytes, aligned;
1527    struct nand_chip *chip = mtd->priv;
1528    struct mtd_ecc_stats stats;
1529    int blkcheck = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
1530    int sndcmd = 1;
1531    int ret = 0;
1532    uint32_t readlen = ops->len;
1533    uint32_t oobreadlen = ops->ooblen;
1534    uint32_t max_oobsize = ops->mode == MTD_OOB_AUTO ?
1535        mtd->oobavail : mtd->oobsize;
1536
1537    uint8_t *bufpoi, *oob, *buf;
1538
1539    stats = mtd->ecc_stats;
1540
1541    chipnr = (int)(from >> chip->chip_shift);
1542    chip->select_chip(mtd, chipnr);
1543
1544    realpage = (int)(from >> chip->page_shift);
1545    page = realpage & chip->pagemask;
1546
1547    col = (int)(from & (mtd->writesize - 1));
1548
1549    buf = ops->datbuf;
1550    oob = ops->oobbuf;
1551
1552    while (1) {
1553        bytes = min(mtd->writesize - col, readlen);
1554        aligned = (bytes == mtd->writesize);
1555
1556        /* Is the current page in the buffer ? */
1557        if (realpage != chip->pagebuf || oob) {
1558            bufpoi = aligned ? buf : chip->buffers->databuf;
1559
1560            if (likely(sndcmd) && chip->ecc.mode != NAND_ECC_HW_OOB_FIRST) {
1561                chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1562                sndcmd = 0;
1563            }
1564
1565            /* Now read the page into the buffer */
1566            if (unlikely(ops->mode == MTD_OOB_RAW))
1567                ret = chip->ecc.read_page_raw(mtd, chip,
1568                                  bufpoi, page);
1569            else if (!aligned && NAND_SUBPAGE_READ(chip) && !oob)
1570                ret = chip->ecc.read_subpage(mtd, chip,
1571                            col, bytes, bufpoi, page);
1572            else
1573                ret = chip->ecc.read_page(mtd, chip, bufpoi,
1574                              page);
1575            if (ret < 0)
1576                break;
1577
1578            /* Transfer not aligned data */
1579            if (!aligned) {
1580                if (!NAND_SUBPAGE_READ(chip) && !oob &&
1581                    !(mtd->ecc_stats.failed - stats.failed))
1582                    chip->pagebuf = realpage;
1583                memcpy(buf, chip->buffers->databuf + col, bytes);
1584            }
1585
1586            buf += bytes;
1587
1588            if (unlikely(oob)) {
1589
1590                int toread = min(oobreadlen, max_oobsize);
1591
1592                if (toread) {
1593                    oob = nand_transfer_oob(chip,
1594                        oob, ops, toread);
1595                    oobreadlen -= toread;
1596                }
1597            }
1598
1599            if (!(chip->options & NAND_NO_READRDY)) {
1600                /*
1601                 * Apply delay or wait for ready/busy pin. Do
1602                 * this before the AUTOINCR check, so no
1603                 * problems arise if a chip which does auto
1604                 * increment is marked as NOAUTOINCR by the
1605                 * board driver.
1606                 */
1607                if (!chip->dev_ready)
1608                    udelay(chip->chip_delay);
1609                else
1610                    nand_wait_ready(mtd);
1611            }
1612        } else {
1613            memcpy(buf, chip->buffers->databuf + col, bytes);
1614            buf += bytes;
1615        }
1616
1617        readlen -= bytes;
1618
1619        if (!readlen)
1620            break;
1621
1622        /* For subsequent reads align to page boundary. */
1623        col = 0;
1624        /* Increment page address */
1625        realpage++;
1626
1627        page = realpage & chip->pagemask;
1628        /* Check, if we cross a chip boundary */
1629        if (!page) {
1630            chipnr++;
1631            chip->select_chip(mtd, -1);
1632            chip->select_chip(mtd, chipnr);
1633        }
1634
1635        /* Check, if the chip supports auto page increment
1636         * or if we have hit a block boundary.
1637         */
1638        if (!NAND_CANAUTOINCR(chip) || !(page & blkcheck))
1639            sndcmd = 1;
1640    }
1641
1642    ops->retlen = ops->len - (size_t) readlen;
1643    if (oob)
1644        ops->oobretlen = ops->ooblen - oobreadlen;
1645
1646    if (ret)
1647        return ret;
1648
1649    if (mtd->ecc_stats.failed - stats.failed)
1650        return -EBADMSG;
1651
1652    return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
1653}
1654
1655/**
1656 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1657 * @mtd: MTD device structure
1658 * @from: offset to read from
1659 * @len: number of bytes to read
1660 * @retlen: pointer to variable to store the number of read bytes
1661 * @buf: the databuffer to put data
1662 *
1663 * Get hold of the chip and call nand_do_read
1664 */
1665static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1666             size_t *retlen, uint8_t *buf)
1667{
1668    struct nand_chip *chip = mtd->priv;
1669    int ret;
1670
1671    /* Do not allow reads past end of device */
1672    if ((from + len) > mtd->size)
1673        return -EINVAL;
1674    if (!len)
1675        return 0;
1676
1677    nand_get_device(chip, mtd, FL_READING);
1678
1679    chip->ops.len = len;
1680    chip->ops.datbuf = buf;
1681    chip->ops.oobbuf = NULL;
1682
1683    ret = nand_do_read_ops(mtd, from, &chip->ops);
1684
1685    *retlen = chip->ops.retlen;
1686
1687    nand_release_device(mtd);
1688
1689    return ret;
1690}
1691
1692/**
1693 * nand_read_oob_std - [REPLACABLE] the most common OOB data read function
1694 * @mtd: mtd info structure
1695 * @chip: nand chip info structure
1696 * @page: page number to read
1697 * @sndcmd: flag whether to issue read command or not
1698 */
1699static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1700                 int page, int sndcmd)
1701{
1702    if (sndcmd) {
1703        chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1704        sndcmd = 0;
1705    }
1706    chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1707    return sndcmd;
1708}
1709
1710/**
1711 * nand_read_oob_syndrome - [REPLACABLE] OOB data read function for HW ECC
1712 * with syndromes
1713 * @mtd: mtd info structure
1714 * @chip: nand chip info structure
1715 * @page: page number to read
1716 * @sndcmd: flag whether to issue read command or not
1717 */
1718static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1719                  int page, int sndcmd)
1720{
1721    uint8_t *buf = chip->oob_poi;
1722    int length = mtd->oobsize;
1723    int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1724    int eccsize = chip->ecc.size;
1725    uint8_t *bufpoi = buf;
1726    int i, toread, sndrnd = 0, pos;
1727
1728    chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1729    for (i = 0; i < chip->ecc.steps; i++) {
1730        if (sndrnd) {
1731            pos = eccsize + i * (eccsize + chunk);
1732            if (mtd->writesize > 512)
1733                chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1734            else
1735                chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1736        } else
1737            sndrnd = 1;
1738        toread = min_t(int, length, chunk);
1739        chip->read_buf(mtd, bufpoi, toread);
1740        bufpoi += toread;
1741        length -= toread;
1742    }
1743    if (length > 0)
1744        chip->read_buf(mtd, bufpoi, length);
1745
1746    return 1;
1747}
1748
1749/**
1750 * nand_write_oob_std - [REPLACABLE] the most common OOB data write function
1751 * @mtd: mtd info structure
1752 * @chip: nand chip info structure
1753 * @page: page number to write
1754 */
1755static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1756                  int page)
1757{
1758    int status = 0;
1759    const uint8_t *buf = chip->oob_poi;
1760    int length = mtd->oobsize;
1761
1762    chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1763    chip->write_buf(mtd, buf, length);
1764    /* Send command to program the OOB data */
1765    chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1766
1767    status = chip->waitfunc(mtd, chip);
1768
1769    return status & NAND_STATUS_FAIL ? -EIO : 0;
1770}
1771
1772/**
1773 * nand_write_oob_syndrome - [REPLACABLE] OOB data write function for HW ECC
1774 * with syndrome - only for large page flash !
1775 * @mtd: mtd info structure
1776 * @chip: nand chip info structure
1777 * @page: page number to write
1778 */
1779static int nand_write_oob_syndrome(struct mtd_info *mtd,
1780                   struct nand_chip *chip, int page)
1781{
1782    int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1783    int eccsize = chip->ecc.size, length = mtd->oobsize;
1784    int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1785    const uint8_t *bufpoi = chip->oob_poi;
1786
1787    /*
1788     * data-ecc-data-ecc ... ecc-oob
1789     * or
1790     * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1791     */
1792    if (!chip->ecc.prepad && !chip->ecc.postpad) {
1793        pos = steps * (eccsize + chunk);
1794        steps = 0;
1795    } else
1796        pos = eccsize;
1797
1798    chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1799    for (i = 0; i < steps; i++) {
1800        if (sndcmd) {
1801            if (mtd->writesize <= 512) {
1802                uint32_t fill = 0xFFFFFFFF;
1803
1804                len = eccsize;
1805                while (len > 0) {
1806                    int num = min_t(int, len, 4);
1807                    chip->write_buf(mtd, (uint8_t *)&fill,
1808                            num);
1809                    len -= num;
1810                }
1811            } else {
1812                pos = eccsize + i * (eccsize + chunk);
1813                chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
1814            }
1815        } else
1816            sndcmd = 1;
1817        len = min_t(int, length, chunk);
1818        chip->write_buf(mtd, bufpoi, len);
1819        bufpoi += len;
1820        length -= len;
1821    }
1822    if (length > 0)
1823        chip->write_buf(mtd, bufpoi, length);
1824
1825    chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1826    status = chip->waitfunc(mtd, chip);
1827
1828    return status & NAND_STATUS_FAIL ? -EIO : 0;
1829}
1830
1831/**
1832 * nand_do_read_oob - [Intern] NAND read out-of-band
1833 * @mtd: MTD device structure
1834 * @from: offset to read from
1835 * @ops: oob operations description structure
1836 *
1837 * NAND read out-of-band data from the spare area
1838 */
1839static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
1840                struct mtd_oob_ops *ops)
1841{
1842    int page, realpage, chipnr, sndcmd = 1;
1843    struct nand_chip *chip = mtd->priv;
1844    int blkcheck = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
1845    int readlen = ops->ooblen;
1846    int len;
1847    uint8_t *buf = ops->oobbuf;
1848
1849    DEBUG(MTD_DEBUG_LEVEL3, "%s: from = 0x%08Lx, len = %i\n",
1850            __func__, (unsigned long long)from, readlen);
1851
1852    if (ops->mode == MTD_OOB_AUTO)
1853        len = chip->ecc.layout->oobavail;
1854    else
1855        len = mtd->oobsize;
1856
1857    if (unlikely(ops->ooboffs >= len)) {
1858        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt to start read "
1859                    "outside oob\n", __func__);
1860        return -EINVAL;
1861    }
1862
1863    /* Do not allow reads past end of device */
1864    if (unlikely(from >= mtd->size ||
1865             ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
1866                    (from >> chip->page_shift)) * len)) {
1867        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt read beyond end "
1868                    "of device\n", __func__);
1869        return -EINVAL;
1870    }
1871
1872    chipnr = (int)(from >> chip->chip_shift);
1873    chip->select_chip(mtd, chipnr);
1874
1875    /* Shift to get page */
1876    realpage = (int)(from >> chip->page_shift);
1877    page = realpage & chip->pagemask;
1878
1879    while (1) {
1880        sndcmd = chip->ecc.read_oob(mtd, chip, page, sndcmd);
1881
1882        len = min(len, readlen);
1883        buf = nand_transfer_oob(chip, buf, ops, len);
1884
1885        if (!(chip->options & NAND_NO_READRDY)) {
1886            /*
1887             * Apply delay or wait for ready/busy pin. Do this
1888             * before the AUTOINCR check, so no problems arise if a
1889             * chip which does auto increment is marked as
1890             * NOAUTOINCR by the board driver.
1891             */
1892            if (!chip->dev_ready)
1893                udelay(chip->chip_delay);
1894            else
1895                nand_wait_ready(mtd);
1896        }
1897
1898        readlen -= len;
1899        if (!readlen)
1900            break;
1901
1902        /* Increment page address */
1903        realpage++;
1904
1905        page = realpage & chip->pagemask;
1906        /* Check, if we cross a chip boundary */
1907        if (!page) {
1908            chipnr++;
1909            chip->select_chip(mtd, -1);
1910            chip->select_chip(mtd, chipnr);
1911        }
1912
1913        /* Check, if the chip supports auto page increment
1914         * or if we have hit a block boundary.
1915         */
1916        if (!NAND_CANAUTOINCR(chip) || !(page & blkcheck))
1917            sndcmd = 1;
1918    }
1919
1920    ops->oobretlen = ops->ooblen;
1921    return 0;
1922}
1923
1924/**
1925 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
1926 * @mtd: MTD device structure
1927 * @from: offset to read from
1928 * @ops: oob operation description structure
1929 *
1930 * NAND read data and/or out-of-band data
1931 */
1932static int nand_read_oob(struct mtd_info *mtd, loff_t from,
1933             struct mtd_oob_ops *ops)
1934{
1935    struct nand_chip *chip = mtd->priv;
1936    int ret = -ENOTSUPP;
1937
1938    ops->retlen = 0;
1939
1940    /* Do not allow reads past end of device */
1941    if (ops->datbuf && (from + ops->len) > mtd->size) {
1942        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt read "
1943                "beyond end of device\n", __func__);
1944        return -EINVAL;
1945    }
1946
1947    nand_get_device(chip, mtd, FL_READING);
1948
1949    switch (ops->mode) {
1950    case MTD_OOB_PLACE:
1951    case MTD_OOB_AUTO:
1952    case MTD_OOB_RAW:
1953        break;
1954
1955    default:
1956        goto out;
1957    }
1958
1959    if (!ops->datbuf)
1960        ret = nand_do_read_oob(mtd, from, ops);
1961    else
1962        ret = nand_do_read_ops(mtd, from, ops);
1963
1964out:
1965    nand_release_device(mtd);
1966    return ret;
1967}
1968
1969
1970/**
1971 * nand_write_page_raw - [Intern] raw page write function
1972 * @mtd: mtd info structure
1973 * @chip: nand chip info structure
1974 * @buf: data buffer
1975 *
1976 * Not for syndrome calculating ecc controllers, which use a special oob layout
1977 */
1978static void nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1979                const uint8_t *buf)
1980{
1981    chip->write_buf(mtd, buf, mtd->writesize);
1982    chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
1983}
1984
1985/**
1986 * nand_write_page_raw_syndrome - [Intern] raw page write function
1987 * @mtd: mtd info structure
1988 * @chip: nand chip info structure
1989 * @buf: data buffer
1990 *
1991 * We need a special oob layout and handling even when ECC isn't checked.
1992 */
1993static void nand_write_page_raw_syndrome(struct mtd_info *mtd,
1994                    struct nand_chip *chip,
1995                    const uint8_t *buf)
1996{
1997    int eccsize = chip->ecc.size;
1998    int eccbytes = chip->ecc.bytes;
1999    uint8_t *oob = chip->oob_poi;
2000    int steps, size;
2001
2002    for (steps = chip->ecc.steps; steps > 0; steps--) {
2003        chip->write_buf(mtd, buf, eccsize);
2004        buf += eccsize;
2005
2006        if (chip->ecc.prepad) {
2007            chip->write_buf(mtd, oob, chip->ecc.prepad);
2008            oob += chip->ecc.prepad;
2009        }
2010
2011        chip->read_buf(mtd, oob, eccbytes);
2012        oob += eccbytes;
2013
2014        if (chip->ecc.postpad) {
2015            chip->write_buf(mtd, oob, chip->ecc.postpad);
2016            oob += chip->ecc.postpad;
2017        }
2018    }
2019
2020    size = mtd->oobsize - (oob - chip->oob_poi);
2021    if (size)
2022        chip->write_buf(mtd, oob, size);
2023}
2024/**
2025 * nand_write_page_swecc - [REPLACABLE] software ecc based page write function
2026 * @mtd: mtd info structure
2027 * @chip: nand chip info structure
2028 * @buf: data buffer
2029 */
2030static void nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2031                  const uint8_t *buf)
2032{
2033    int i, eccsize = chip->ecc.size;
2034    int eccbytes = chip->ecc.bytes;
2035    int eccsteps = chip->ecc.steps;
2036    uint8_t *ecc_calc = chip->buffers->ecccalc;
2037    const uint8_t *p = buf;
2038    uint32_t *eccpos = chip->ecc.layout->eccpos;
2039
2040    /* Software ecc calculation */
2041    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2042        chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2043
2044    for (i = 0; i < chip->ecc.total; i++)
2045        chip->oob_poi[eccpos[i]] = ecc_calc[i];
2046
2047    chip->ecc.write_page_raw(mtd, chip, buf);
2048}
2049
2050/**
2051 * nand_write_page_hwecc - [REPLACABLE] hardware ecc based page write function
2052 * @mtd: mtd info structure
2053 * @chip: nand chip info structure
2054 * @buf: data buffer
2055 */
2056static void nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2057                  const uint8_t *buf)
2058{
2059    int i, eccsize = chip->ecc.size;
2060    int eccbytes = chip->ecc.bytes;
2061    int eccsteps = chip->ecc.steps;
2062    uint8_t *ecc_calc = chip->buffers->ecccalc;
2063    const uint8_t *p = buf;
2064    uint32_t *eccpos = chip->ecc.layout->eccpos;
2065
2066    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2067        chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2068        chip->write_buf(mtd, p, eccsize);
2069        chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2070    }
2071
2072    for (i = 0; i < chip->ecc.total; i++)
2073        chip->oob_poi[eccpos[i]] = ecc_calc[i];
2074
2075    chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2076}
2077
2078/**
2079 * nand_write_page_syndrome - [REPLACABLE] hardware ecc syndrom based page write
2080 * @mtd: mtd info structure
2081 * @chip: nand chip info structure
2082 * @buf: data buffer
2083 *
2084 * The hw generator calculates the error syndrome automatically. Therefor
2085 * we need a special oob layout and handling.
2086 */
2087static void nand_write_page_syndrome(struct mtd_info *mtd,
2088                    struct nand_chip *chip, const uint8_t *buf)
2089{
2090    int i, eccsize = chip->ecc.size;
2091    int eccbytes = chip->ecc.bytes;
2092    int eccsteps = chip->ecc.steps;
2093    const uint8_t *p = buf;
2094    uint8_t *oob = chip->oob_poi;
2095
2096    for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2097
2098        chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2099        chip->write_buf(mtd, p, eccsize);
2100
2101        if (chip->ecc.prepad) {
2102            chip->write_buf(mtd, oob, chip->ecc.prepad);
2103            oob += chip->ecc.prepad;
2104        }
2105
2106        chip->ecc.calculate(mtd, p, oob);
2107        chip->write_buf(mtd, oob, eccbytes);
2108        oob += eccbytes;
2109
2110        if (chip->ecc.postpad) {
2111            chip->write_buf(mtd, oob, chip->ecc.postpad);
2112            oob += chip->ecc.postpad;
2113        }
2114    }
2115
2116    /* Calculate remaining oob bytes */
2117    i = mtd->oobsize - (oob - chip->oob_poi);
2118    if (i)
2119        chip->write_buf(mtd, oob, i);
2120}
2121
2122/**
2123 * nand_write_page - [REPLACEABLE] write one page
2124 * @mtd: MTD device structure
2125 * @chip: NAND chip descriptor
2126 * @buf: the data to write
2127 * @page: page number to write
2128 * @cached: cached programming
2129 * @raw: use _raw version of write_page
2130 */
2131static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2132               const uint8_t *buf, int page, int cached, int raw)
2133{
2134    int status;
2135
2136    chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2137
2138    if (unlikely(raw))
2139        chip->ecc.write_page_raw(mtd, chip, buf);
2140    else
2141        chip->ecc.write_page(mtd, chip, buf);
2142
2143    /*
2144     * Cached progamming disabled for now, Not sure if its worth the
2145     * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s)
2146     */
2147    cached = 0;
2148
2149    if (!cached || !(chip->options & NAND_CACHEPRG)) {
2150
2151        chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2152        status = chip->waitfunc(mtd, chip);
2153        /*
2154         * See if operation failed and additional status checks are
2155         * available
2156         */
2157        if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2158            status = chip->errstat(mtd, chip, FL_WRITING, status,
2159                           page);
2160
2161        if (status & NAND_STATUS_FAIL)
2162            return -EIO;
2163    } else {
2164        chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2165        status = chip->waitfunc(mtd, chip);
2166    }
2167
2168#ifdef CONFIG_MTD_NAND_VERIFY_WRITE
2169    /* Send command to read back the data */
2170    chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
2171
2172    if (chip->verify_buf(mtd, buf, mtd->writesize))
2173        return -EIO;
2174#endif
2175    return 0;
2176}
2177
2178/**
2179 * nand_fill_oob - [Internal] Transfer client buffer to oob
2180 * @chip: nand chip structure
2181 * @oob: oob data buffer
2182 * @len: oob data write length
2183 * @ops: oob ops structure
2184 */
2185static uint8_t *nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len,
2186                        struct mtd_oob_ops *ops)
2187{
2188    switch (ops->mode) {
2189
2190    case MTD_OOB_PLACE:
2191    case MTD_OOB_RAW:
2192        memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2193        return oob + len;
2194
2195    case MTD_OOB_AUTO: {
2196        struct nand_oobfree *free = chip->ecc.layout->oobfree;
2197        uint32_t boffs = 0, woffs = ops->ooboffs;
2198        size_t bytes = 0;
2199
2200        for (; free->length && len; free++, len -= bytes) {
2201            /* Write request not from offset 0 ? */
2202            if (unlikely(woffs)) {
2203                if (woffs >= free->length) {
2204                    woffs -= free->length;
2205                    continue;
2206                }
2207                boffs = free->offset + woffs;
2208                bytes = min_t(size_t, len,
2209                          (free->length - woffs));
2210                woffs = 0;
2211            } else {
2212                bytes = min_t(size_t, len, free->length);
2213                boffs = free->offset;
2214            }
2215            memcpy(chip->oob_poi + boffs, oob, bytes);
2216            oob += bytes;
2217        }
2218        return oob;
2219    }
2220    default:
2221        BUG();
2222    }
2223    return NULL;
2224}
2225
2226#define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2227
2228/**
2229 * nand_do_write_ops - [Internal] NAND write with ECC
2230 * @mtd: MTD device structure
2231 * @to: offset to write to
2232 * @ops: oob operations description structure
2233 *
2234 * NAND write with ECC
2235 */
2236static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2237                 struct mtd_oob_ops *ops)
2238{
2239    int chipnr, realpage, page, blockmask, column;
2240    struct nand_chip *chip = mtd->priv;
2241    uint32_t writelen = ops->len;
2242
2243    uint32_t oobwritelen = ops->ooblen;
2244    uint32_t oobmaxlen = ops->mode == MTD_OOB_AUTO ?
2245                mtd->oobavail : mtd->oobsize;
2246
2247    uint8_t *oob = ops->oobbuf;
2248    uint8_t *buf = ops->datbuf;
2249    int ret, subpage;
2250
2251    ops->retlen = 0;
2252    if (!writelen)
2253        return 0;
2254
2255    /* reject writes, which are not page aligned */
2256    if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2257        printk(KERN_NOTICE "%s: Attempt to write not "
2258                "page aligned data\n", __func__);
2259        return -EINVAL;
2260    }
2261
2262    column = to & (mtd->writesize - 1);
2263    subpage = column || (writelen & (mtd->writesize - 1));
2264
2265    if (subpage && oob)
2266        return -EINVAL;
2267
2268    chipnr = (int)(to >> chip->chip_shift);
2269    chip->select_chip(mtd, chipnr);
2270
2271    /* Check, if it is write protected */
2272    if (nand_check_wp(mtd))
2273        return -EIO;
2274
2275    realpage = (int)(to >> chip->page_shift);
2276    page = realpage & chip->pagemask;
2277    blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2278
2279    /* Invalidate the page cache, when we write to the cached page */
2280    if (to <= (chip->pagebuf << chip->page_shift) &&
2281        (chip->pagebuf << chip->page_shift) < (to + ops->len))
2282        chip->pagebuf = -1;
2283
2284    /* If we're not given explicit OOB data, let it be 0xFF */
2285    if (likely(!oob))
2286        memset(chip->oob_poi, 0xff, mtd->oobsize);
2287
2288    /* Don't allow multipage oob writes with offset */
2289    if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen))
2290        return -EINVAL;
2291
2292    while (1) {
2293        int bytes = mtd->writesize;
2294        int cached = writelen > bytes && page != blockmask;
2295        uint8_t *wbuf = buf;
2296
2297        /* Partial page write ? */
2298        if (unlikely(column || writelen < (mtd->writesize - 1))) {
2299            cached = 0;
2300            bytes = min_t(int, bytes - column, (int) writelen);
2301            chip->pagebuf = -1;
2302            memset(chip->buffers->databuf, 0xff, mtd->writesize);
2303            memcpy(&chip->buffers->databuf[column], buf, bytes);
2304            wbuf = chip->buffers->databuf;
2305        }
2306
2307        if (unlikely(oob)) {
2308            size_t len = min(oobwritelen, oobmaxlen);
2309            oob = nand_fill_oob(chip, oob, len, ops);
2310            oobwritelen -= len;
2311        }
2312
2313        ret = chip->write_page(mtd, chip, wbuf, page, cached,
2314                       (ops->mode == MTD_OOB_RAW));
2315        if (ret)
2316            break;
2317
2318        writelen -= bytes;
2319        if (!writelen)
2320            break;
2321
2322        column = 0;
2323        buf += bytes;
2324        realpage++;
2325
2326        page = realpage & chip->pagemask;
2327        /* Check, if we cross a chip boundary */
2328        if (!page) {
2329            chipnr++;
2330            chip->select_chip(mtd, -1);
2331            chip->select_chip(mtd, chipnr);
2332        }
2333    }
2334
2335    ops->retlen = ops->len - writelen;
2336    if (unlikely(oob))
2337        ops->oobretlen = ops->ooblen;
2338    return ret;
2339}
2340
2341/**
2342 * panic_nand_write - [MTD Interface] NAND write with ECC
2343 * @mtd: MTD device structure
2344 * @to: offset to write to
2345 * @len: number of bytes to write
2346 * @retlen: pointer to variable to store the number of written bytes
2347 * @buf: the data to write
2348 *
2349 * NAND write with ECC. Used when performing writes in interrupt context, this
2350 * may for example be called by mtdoops when writing an oops while in panic.
2351 */
2352static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2353                size_t *retlen, const uint8_t *buf)
2354{
2355    struct nand_chip *chip = mtd->priv;
2356    int ret;
2357
2358    /* Do not allow reads past end of device */
2359    if ((to + len) > mtd->size)
2360        return -EINVAL;
2361    if (!len)
2362        return 0;
2363
2364    /* Wait for the device to get ready. */
2365    panic_nand_wait(mtd, chip, 400);
2366
2367    /* Grab the device. */
2368    panic_nand_get_device(chip, mtd, FL_WRITING);
2369
2370    chip->ops.len = len;
2371    chip->ops.datbuf = (uint8_t *)buf;
2372    chip->ops.oobbuf = NULL;
2373
2374    ret = nand_do_write_ops(mtd, to, &chip->ops);
2375
2376    *retlen = chip->ops.retlen;
2377    return ret;
2378}
2379
2380/**
2381 * nand_write - [MTD Interface] NAND write with ECC
2382 * @mtd: MTD device structure
2383 * @to: offset to write to
2384 * @len: number of bytes to write
2385 * @retlen: pointer to variable to store the number of written bytes
2386 * @buf: the data to write
2387 *
2388 * NAND write with ECC
2389 */
2390static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2391              size_t *retlen, const uint8_t *buf)
2392{
2393    struct nand_chip *chip = mtd->priv;
2394    int ret;
2395
2396    /* Do not allow reads past end of device */
2397    if ((to + len) > mtd->size)
2398        return -EINVAL;
2399    if (!len)
2400        return 0;
2401
2402    nand_get_device(chip, mtd, FL_WRITING);
2403
2404    chip->ops.len = len;
2405    chip->ops.datbuf = (uint8_t *)buf;
2406    chip->ops.oobbuf = NULL;
2407
2408    ret = nand_do_write_ops(mtd, to, &chip->ops);
2409
2410    *retlen = chip->ops.retlen;
2411
2412    nand_release_device(mtd);
2413
2414    return ret;
2415}
2416
2417/**
2418 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2419 * @mtd: MTD device structure
2420 * @to: offset to write to
2421 * @ops: oob operation description structure
2422 *
2423 * NAND write out-of-band
2424 */
2425static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2426                 struct mtd_oob_ops *ops)
2427{
2428    int chipnr, page, status, len;
2429    struct nand_chip *chip = mtd->priv;
2430
2431    DEBUG(MTD_DEBUG_LEVEL3, "%s: to = 0x%08x, len = %i\n",
2432             __func__, (unsigned int)to, (int)ops->ooblen);
2433
2434    if (ops->mode == MTD_OOB_AUTO)
2435        len = chip->ecc.layout->oobavail;
2436    else
2437        len = mtd->oobsize;
2438
2439    /* Do not allow write past end of page */
2440    if ((ops->ooboffs + ops->ooblen) > len) {
2441        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt to write "
2442                "past end of page\n", __func__);
2443        return -EINVAL;
2444    }
2445
2446    if (unlikely(ops->ooboffs >= len)) {
2447        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt to start "
2448                "write outside oob\n", __func__);
2449        return -EINVAL;
2450    }
2451
2452    /* Do not allow write past end of device */
2453    if (unlikely(to >= mtd->size ||
2454             ops->ooboffs + ops->ooblen >
2455            ((mtd->size >> chip->page_shift) -
2456             (to >> chip->page_shift)) * len)) {
2457        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt write beyond "
2458                "end of device\n", __func__);
2459        return -EINVAL;
2460    }
2461
2462    chipnr = (int)(to >> chip->chip_shift);
2463    chip->select_chip(mtd, chipnr);
2464
2465    /* Shift to get page */
2466    page = (int)(to >> chip->page_shift);
2467
2468    /*
2469     * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2470     * of my DiskOnChip 2000 test units) will clear the whole data page too
2471     * if we don't do this. I have no clue why, but I seem to have 'fixed'
2472     * it in the doc2000 driver in August 1999. dwmw2.
2473     */
2474    chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2475
2476    /* Check, if it is write protected */
2477    if (nand_check_wp(mtd))
2478        return -EROFS;
2479
2480    /* Invalidate the page cache, if we write to the cached page */
2481    if (page == chip->pagebuf)
2482        chip->pagebuf = -1;
2483
2484    memset(chip->oob_poi, 0xff, mtd->oobsize);
2485    nand_fill_oob(chip, ops->oobbuf, ops->ooblen, ops);
2486    status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2487    memset(chip->oob_poi, 0xff, mtd->oobsize);
2488
2489    if (status)
2490        return status;
2491
2492    ops->oobretlen = ops->ooblen;
2493
2494    return 0;
2495}
2496
2497/**
2498 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2499 * @mtd: MTD device structure
2500 * @to: offset to write to
2501 * @ops: oob operation description structure
2502 */
2503static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2504              struct mtd_oob_ops *ops)
2505{
2506    struct nand_chip *chip = mtd->priv;
2507    int ret = -ENOTSUPP;
2508
2509    ops->retlen = 0;
2510
2511    /* Do not allow writes past end of device */
2512    if (ops->datbuf && (to + ops->len) > mtd->size) {
2513        DEBUG(MTD_DEBUG_LEVEL0, "%s: Attempt write beyond "
2514                "end of device\n", __func__);
2515        return -EINVAL;
2516    }
2517
2518    nand_get_device(chip, mtd, FL_WRITING);
2519
2520    switch (ops->mode) {
2521    case MTD_OOB_PLACE:
2522    case MTD_OOB_AUTO:
2523    case MTD_OOB_RAW:
2524        break;
2525
2526    default:
2527        goto out;
2528    }
2529
2530    if (!ops->datbuf)
2531        ret = nand_do_write_oob(mtd, to, ops);
2532    else
2533        ret = nand_do_write_ops(mtd, to, ops);
2534
2535out:
2536    nand_release_device(mtd);
2537    return ret;
2538}
2539
2540/**
2541 * single_erease_cmd - [GENERIC] NAND standard block erase command function
2542 * @mtd: MTD device structure
2543 * @page: the page address of the block which will be erased
2544 *
2545 * Standard erase command for NAND chips
2546 */
2547static void single_erase_cmd(struct mtd_info *mtd, int page)
2548{
2549    struct nand_chip *chip = mtd->priv;
2550    /* Send commands to erase a block */
2551    chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2552    chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2553}
2554
2555/**
2556 * multi_erease_cmd - [GENERIC] AND specific block erase command function
2557 * @mtd: MTD device structure
2558 * @page: the page address of the block which will be erased
2559 *
2560 * AND multi block erase command function
2561 * Erase 4 consecutive blocks
2562 */
2563static void multi_erase_cmd(struct mtd_info *mtd, int page)
2564{
2565    struct nand_chip *chip = mtd->priv;
2566    /* Send commands to erase a block */
2567    chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page++);
2568    chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page++);
2569    chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page++);
2570    chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2571    chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2572}
2573
2574/**
2575 * nand_erase - [MTD Interface] erase block(s)
2576 * @mtd: MTD device structure
2577 * @instr: erase instruction
2578 *
2579 * Erase one ore more blocks
2580 */
2581static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2582{
2583    return nand_erase_nand(mtd, instr, 0);
2584}
2585
2586#define BBT_PAGE_MASK 0xffffff3f
2587/**
2588 * nand_erase_nand - [Internal] erase block(s)
2589 * @mtd: MTD device structure
2590 * @instr: erase instruction
2591 * @allowbbt: allow erasing the bbt area
2592 *
2593 * Erase one ore more blocks
2594 */
2595int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2596            int allowbbt)
2597{
2598    int page, status, pages_per_block, ret, chipnr;
2599    struct nand_chip *chip = mtd->priv;
2600    loff_t rewrite_bbt[NAND_MAX_CHIPS] = {0};
2601    unsigned int bbt_masked_page = 0xffffffff;
2602    loff_t len;
2603
2604    DEBUG(MTD_DEBUG_LEVEL3, "%s: start = 0x%012llx, len = %llu\n",
2605                __func__, (unsigned long long)instr->addr,
2606                (unsigned long long)instr->len);
2607
2608    if (check_offs_len(mtd, instr->addr, instr->len))
2609        return -EINVAL;
2610
2611    instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
2612
2613    /* Grab the lock and see if the device is available */
2614    nand_get_device(chip, mtd, FL_ERASING);
2615
2616    /* Shift to get first page */
2617    page = (int)(instr->addr >> chip->page_shift);
2618    chipnr = (int)(instr->addr >> chip->chip_shift);
2619
2620    /* Calculate pages in each block */
2621    pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2622
2623    /* Select the NAND device */
2624    chip->select_chip(mtd, chipnr);
2625
2626    /* Check, if it is write protected */
2627    if (nand_check_wp(mtd)) {
2628        DEBUG(MTD_DEBUG_LEVEL0, "%s: Device is write protected!!!\n",
2629                    __func__);
2630        instr->state = MTD_ERASE_FAILED;
2631        goto erase_exit;
2632    }
2633
2634    /*
2635     * If BBT requires refresh, set the BBT page mask to see if the BBT
2636     * should be rewritten. Otherwise the mask is set to 0xffffffff which
2637     * can not be matched. This is also done when the bbt is actually
2638     * erased to avoid recusrsive updates
2639     */
2640    if (chip->options & BBT_AUTO_REFRESH && !allowbbt)
2641        bbt_masked_page = chip->bbt_td->pages[chipnr] & BBT_PAGE_MASK;
2642
2643    /* Loop through the pages */
2644    len = instr->len;
2645
2646    instr->state = MTD_ERASING;
2647
2648    while (len) {
2649        /*
2650         * heck if we have a bad block, we do not erase bad blocks !
2651         */
2652        if (nand_block_checkbad(mtd, ((loff_t) page) <<
2653                    chip->page_shift, 0, allowbbt)) {
2654            printk(KERN_WARNING "%s: attempt to erase a bad block "
2655                    "at page 0x%08x\n", __func__, page);
2656            instr->state = MTD_ERASE_FAILED;
2657            goto erase_exit;
2658        }
2659
2660        /*
2661         * Invalidate the page cache, if we erase the block which
2662         * contains the current cached page
2663         */
2664        if (page <= chip->pagebuf && chip->pagebuf <
2665            (page + pages_per_block))
2666            chip->pagebuf = -1;
2667
2668        chip->erase_cmd(mtd, page & chip->pagemask);
2669
2670        status = chip->waitfunc(mtd, chip);
2671
2672        /*
2673         * See if operation failed and additional status checks are
2674         * available
2675         */
2676        if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2677            status = chip->errstat(mtd, chip, FL_ERASING,
2678                           status, page);
2679
2680        /* See if block erase succeeded */
2681        if (status & NAND_STATUS_FAIL) {
2682            DEBUG(MTD_DEBUG_LEVEL0, "%s: Failed erase, "
2683                    "page 0x%08x\n", __func__, page);
2684            instr->state = MTD_ERASE_FAILED;
2685            instr->fail_addr =
2686                ((loff_t)page << chip->page_shift);
2687            goto erase_exit;
2688        }
2689
2690        /*
2691         * If BBT requires refresh, set the BBT rewrite flag to the
2692         * page being erased
2693         */
2694        if (bbt_masked_page != 0xffffffff &&
2695            (page & BBT_PAGE_MASK) == bbt_masked_page)
2696                rewrite_bbt[chipnr] =
2697                    ((loff_t)page << chip->page_shift);
2698
2699        /* Increment page address and decrement length */
2700        len -= (1 << chip->phys_erase_shift);
2701        page += pages_per_block;
2702
2703        /* Check, if we cross a chip boundary */
2704        if (len && !(page & chip->pagemask)) {
2705            chipnr++;
2706            chip->select_chip(mtd, -1);
2707            chip->select_chip(mtd, chipnr);
2708
2709            /*
2710             * If BBT requires refresh and BBT-PERCHIP, set the BBT
2711             * page mask to see if this BBT should be rewritten
2712             */
2713            if (bbt_masked_page != 0xffffffff &&
2714                (chip->bbt_td->options & NAND_BBT_PERCHIP))
2715                bbt_masked_page = chip->bbt_td->pages[chipnr] &
2716                    BBT_PAGE_MASK;
2717        }
2718    }
2719    instr->state = MTD_ERASE_DONE;
2720
2721erase_exit:
2722
2723    ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2724
2725    /* Deselect and wake up anyone waiting on the device */
2726    nand_release_device(mtd);
2727
2728    /* Do call back function */
2729    if (!ret)
2730        mtd_erase_callback(instr);
2731
2732    /*
2733     * If BBT requires refresh and erase was successful, rewrite any
2734     * selected bad block tables
2735     */
2736    if (bbt_masked_page == 0xffffffff || ret)
2737        return ret;
2738
2739    for (chipnr = 0; chipnr < chip->numchips; chipnr++) {
2740        if (!rewrite_bbt[chipnr])
2741            continue;
2742        /* update the BBT for chip */
2743        DEBUG(MTD_DEBUG_LEVEL0, "%s: nand_update_bbt "
2744            "(%d:0x%0llx 0x%0x)\n", __func__, chipnr,
2745            rewrite_bbt[chipnr], chip->bbt_td->pages[chipnr]);
2746        nand_update_bbt(mtd, rewrite_bbt[chipnr]);
2747    }
2748
2749    /* Return more or less happy */
2750    return ret;
2751}
2752
2753/**
2754 * nand_sync - [MTD Interface] sync
2755 * @mtd: MTD device structure
2756 *
2757 * Sync is actually a wait for chip ready function
2758 */
2759static void nand_sync(struct mtd_info *mtd)
2760{
2761    struct nand_chip *chip = mtd->priv;
2762
2763    DEBUG(MTD_DEBUG_LEVEL3, "%s: called\n", __func__);
2764
2765    /* Grab the lock and see if the device is available */
2766    nand_get_device(chip, mtd, FL_SYNCING);
2767    /* Release it and go back */
2768    nand_release_device(mtd);
2769}
2770
2771/**
2772 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2773 * @mtd: MTD device structure
2774 * @offs: offset relative to mtd start
2775 */
2776static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2777{
2778    /* Check for invalid offset */
2779    if (offs > mtd->size)
2780        return -EINVAL;
2781
2782    return nand_block_checkbad(mtd, offs, 1, 0);
2783}
2784
2785/**
2786 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
2787 * @mtd: MTD device structure
2788 * @ofs: offset relative to mtd start
2789 */
2790static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
2791{
2792    struct nand_chip *chip = mtd->priv;
2793    int ret;
2794
2795    ret = nand_block_isbad(mtd, ofs);
2796    if (ret) {
2797        /* If it was bad already, return success and do nothing. */
2798        if (ret > 0)
2799            return 0;
2800        return ret;
2801    }
2802
2803    return chip->block_markbad(mtd, ofs);
2804}
2805
2806/**
2807 * nand_suspend - [MTD Interface] Suspend the NAND flash
2808 * @mtd: MTD device structure
2809 */
2810static int nand_suspend(struct mtd_info *mtd)
2811{
2812    struct nand_chip *chip = mtd->priv;
2813
2814    return nand_get_device(chip, mtd, FL_PM_SUSPENDED);
2815}
2816
2817/**
2818 * nand_resume - [MTD Interface] Resume the NAND flash
2819 * @mtd: MTD device structure
2820 */
2821static void nand_resume(struct mtd_info *mtd)
2822{
2823    struct nand_chip *chip = mtd->priv;
2824
2825    if (chip->state == FL_PM_SUSPENDED)
2826        nand_release_device(mtd);
2827    else
2828        printk(KERN_ERR "%s called for a chip which is not "
2829               "in suspended state\n", __func__);
2830}
2831
2832/*
2833 * Set default functions
2834 */
2835static void nand_set_defaults(struct nand_chip *chip, int busw)
2836{
2837    /* check for proper chip_delay setup, set 20us if not */
2838    if (!chip->chip_delay)
2839        chip->chip_delay = 20;
2840
2841    /* check, if a user supplied command function given */
2842    if (chip->cmdfunc == NULL)
2843        chip->cmdfunc = nand_command;
2844
2845    /* check, if a user supplied wait function given */
2846    if (chip->waitfunc == NULL)
2847        chip->waitfunc = nand_wait;
2848
2849    if (!chip->select_chip)
2850        chip->select_chip = nand_select_chip;
2851    if (!chip->read_byte)
2852        chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
2853    if (!chip->read_word)
2854        chip->read_word = nand_read_word;
2855    if (!chip->block_bad)
2856        chip->block_bad = nand_block_bad;
2857    if (!chip->block_markbad)
2858        chip->block_markbad = nand_default_block_markbad;
2859    if (!chip->write_buf)
2860        chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
2861    if (!chip->read_buf)
2862        chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
2863    if (!chip->verify_buf)
2864        chip->verify_buf = busw ? nand_verify_buf16 : nand_verify_buf;
2865    if (!chip->scan_bbt)
2866        chip->scan_bbt = nand_default_bbt;
2867
2868    if (!chip->controller) {
2869        chip->controller = &chip->hwcontrol;
2870        spin_lock_init(&chip->controller->lock);
2871        init_waitqueue_head(&chip->controller->wq);
2872    }
2873
2874}
2875
2876/*
2877 * sanitize ONFI strings so we can safely print them
2878 */
2879static void sanitize_string(uint8_t *s, size_t len)
2880{
2881    ssize_t i;
2882
2883    /* null terminate */
2884    s[len - 1] = 0;
2885
2886    /* remove non printable chars */
2887    for (i = 0; i < len - 1; i++) {
2888        if (s[i] < ' ' || s[i] > 127)
2889            s[i] = '?';
2890    }
2891
2892    /* remove trailing spaces */
2893    strim(s);
2894}
2895
2896static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
2897{
2898    int i;
2899    while (len--) {
2900        crc ^= *p++ << 8;
2901        for (i = 0; i < 8; i++)
2902            crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
2903    }
2904
2905    return crc;
2906}
2907
2908/*
2909 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise
2910 */
2911static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
2912                    int busw)
2913{
2914    struct nand_onfi_params *p = &chip->onfi_params;
2915    int i;
2916    int val;
2917
2918    /* try ONFI for unknow chip or LP */
2919    chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
2920    if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
2921        chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
2922        return 0;
2923
2924    printk(KERN_INFO "ONFI flash detected\n");
2925    chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
2926    for (i = 0; i < 3; i++) {
2927        chip->read_buf(mtd, (uint8_t *)p, sizeof(*p));
2928        if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
2929                le16_to_cpu(p->crc)) {
2930            printk(KERN_INFO "ONFI param page %d valid\n", i);
2931            break;
2932        }
2933    }
2934
2935    if (i == 3)
2936        return 0;
2937
2938    /* check version */
2939    val = le16_to_cpu(p->revision);
2940    if (val & (1 << 5))
2941        chip->onfi_version = 23;
2942    else if (val & (1 << 4))
2943        chip->onfi_version = 22;
2944    else if (val & (1 << 3))
2945        chip->onfi_version = 21;
2946    else if (val & (1 << 2))
2947        chip->onfi_version = 20;
2948    else if (val & (1 << 1))
2949        chip->onfi_version = 10;
2950    else
2951        chip->onfi_version = 0;
2952
2953    if (!chip->onfi_version) {
2954        printk(KERN_INFO "%s: unsupported ONFI version: %d\n",
2955                                __func__, val);
2956        return 0;
2957    }
2958
2959    sanitize_string(p->manufacturer, sizeof(p->manufacturer));
2960    sanitize_string(p->model, sizeof(p->model));
2961    if (!mtd->name)
2962        mtd->name = p->model;
2963    mtd->writesize = le32_to_cpu(p->byte_per_page);
2964    mtd->erasesize = le32_to_cpu(p->pages_per_block) * mtd->writesize;
2965    mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
2966    chip->chipsize = (uint64_t)le32_to_cpu(p->blocks_per_lun) * mtd->erasesize;
2967    busw = 0;
2968    if (le16_to_cpu(p->features) & 1)
2969        busw = NAND_BUSWIDTH_16;
2970
2971    chip->options &= ~NAND_CHIPOPTIONS_MSK;
2972    chip->options |= (NAND_NO_READRDY |
2973            NAND_NO_AUTOINCR) & NAND_CHIPOPTIONS_MSK;
2974
2975    return 1;
2976}
2977
2978/*
2979 * Get the flash and manufacturer id and lookup if the type is supported
2980 */
2981static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
2982                          struct nand_chip *chip,
2983                          int busw,
2984                          int *maf_id, int *dev_id,
2985                          struct nand_flash_dev *type)
2986{
2987    int i, maf_idx;
2988    u8 id_data[8];
2989    int ret;
2990
2991    /* Select the device */
2992    chip->select_chip(mtd, 0);
2993
2994    /*
2995     * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
2996     * after power-up
2997     */
2998    chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2999
3000    /* Send the command for reading device ID */
3001    chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3002
3003    /* Read manufacturer and device IDs */
3004    *maf_id = chip->read_byte(mtd);
3005    *dev_id = chip->read_byte(mtd);
3006
3007    /* Try again to make sure, as some systems the bus-hold or other
3008     * interface concerns can cause random data which looks like a
3009     * possibly credible NAND flash to appear. If the two results do
3010     * not match, ignore the device completely.
3011     */
3012
3013    chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3014
3015    for (i = 0; i < 2; i++)
3016        id_data[i] = chip->read_byte(mtd);
3017
3018    if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3019        printk(KERN_INFO "%s: second ID read did not match "
3020               "%02x,%02x against %02x,%02x\n", __func__,
3021               *maf_id, *dev_id, id_data[0], id_data[1]);
3022        return ERR_PTR(-ENODEV);
3023    }
3024
3025    if (!type)
3026        type = nand_flash_ids;
3027
3028    for (; type->name != NULL; type++)
3029        if (*dev_id == type->id)
3030            break;
3031
3032    chip->onfi_version = 0;
3033    if (!type->name || !type->pagesize) {
3034        /* Check is chip is ONFI compliant */
3035        ret = nand_flash_detect_onfi(mtd, chip, busw);
3036        if (ret)
3037            goto ident_done;
3038    }
3039
3040    chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3041
3042    /* Read entire ID string */
3043
3044    for (i = 0; i < 8; i++)
3045        id_data[i] = chip->read_byte(mtd);
3046
3047    if (!type->name)
3048        return ERR_PTR(-ENODEV);
3049
3050    if (!mtd->name)
3051        mtd->name = type->name;
3052
3053    chip->chipsize = (uint64_t)type->chipsize << 20;
3054
3055    if (!type->pagesize && chip->init_size) {
3056        /* set the pagesize, oobsize, erasesize by the driver*/
3057        busw = chip->init_size(mtd, chip, id_data);
3058    } else if (!type->pagesize) {
3059        int extid;
3060        /* The 3rd id byte holds MLC / multichip data */
3061        chip->cellinfo = id_data[2];
3062        /* The 4th id byte is the important one */
3063        extid = id_data[3];
3064
3065        /*
3066         * Field definitions are in the following datasheets:
3067         * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3068         * New style (6 byte ID): Samsung K9GBG08U0M (p.40)
3069         *
3070         * Check for wraparound + Samsung ID + nonzero 6th byte
3071         * to decide what to do.
3072         */
3073        if (id_data[0] == id_data[6] && id_data[1] == id_data[7] &&
3074                id_data[0] == NAND_MFR_SAMSUNG &&
3075                (chip->cellinfo & NAND_CI_CELLTYPE_MSK) &&
3076                id_data[5] != 0x00) {
3077            /* Calc pagesize */
3078            mtd->writesize = 2048 << (extid & 0x03);
3079            extid >>= 2;
3080            /* Calc oobsize */
3081            switch (extid & 0x03) {
3082            case 1:
3083                mtd->oobsize = 128;
3084                break;
3085            case 2:
3086                mtd->oobsize = 218;
3087                break;
3088            case 3:
3089                mtd->oobsize = 400;
3090                break;
3091            default:
3092                mtd->oobsize = 436;
3093                break;
3094            }
3095            extid >>= 2;
3096            /* Calc blocksize */
3097            mtd->erasesize = (128 * 1024) <<
3098                (((extid >> 1) & 0x04) | (extid & 0x03));
3099            busw = 0;
3100        } else {
3101            /* Calc pagesize */
3102            mtd->writesize = 1024 << (extid & 0x03);
3103            extid >>= 2;
3104            /* Calc oobsize */
3105            mtd->oobsize = (8 << (extid & 0x01)) *
3106                (mtd->writesize >> 9);
3107            extid >>= 2;
3108            /* Calc blocksize. Blocksize is multiples of 64KiB */
3109            mtd->erasesize = (64 * 1024) << (extid & 0x03);
3110            extid >>= 2;
3111            /* Get buswidth information */
3112            busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3113        }
3114    } else {
3115        /*
3116         * Old devices have chip data hardcoded in the device id table
3117         */
3118        mtd->erasesize = type->erasesize;
3119        mtd->writesize = type->pagesize;
3120        mtd->oobsize = mtd->writesize / 32;
3121        busw = type->options & NAND_BUSWIDTH_16;
3122
3123        /*
3124         * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3125         * some Spansion chips have erasesize that conflicts with size
3126         * listed in nand_ids table
3127         * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3128         */
3129        if (*maf_id == NAND_MFR_AMD && id_data[4] != 0x00 &&
3130                id_data[5] == 0x00 && id_data[6] == 0x00 &&
3131                id_data[7] == 0x00 && mtd->writesize == 512) {
3132            mtd->erasesize = 128 * 1024;
3133            mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3134        }
3135    }
3136    /* Get chip options, preserve non chip based options */
3137    chip->options &= ~NAND_CHIPOPTIONS_MSK;
3138    chip->options |= type->options & NAND_CHIPOPTIONS_MSK;
3139
3140    /* Check if chip is a not a samsung device. Do not clear the
3141     * options for chips which are not having an extended id.
3142     */
3143    if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3144        chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3145ident_done:
3146
3147    /*
3148     * Set chip as a default. Board drivers can override it, if necessary
3149     */
3150    chip->options |= NAND_NO_AUTOINCR;
3151
3152    /* Try to identify manufacturer */
3153    for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3154        if (nand_manuf_ids[maf_idx].id == *maf_id)
3155            break;
3156    }
3157
3158    /*
3159     * Check, if buswidth is correct. Hardware drivers should set
3160     * chip correct !
3161     */
3162    if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3163        printk(KERN_INFO "NAND device: Manufacturer ID:"
3164               " 0x%02x, Chip ID: 0x%02x (%s %s)\n", *maf_id,
3165               *dev_id, nand_manuf_ids[maf_idx].name, mtd->name);
3166        printk(KERN_WARNING "NAND bus width %d instead %d bit\n",
3167               (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3168               busw ? 16 : 8);
3169        return ERR_PTR(-EINVAL);
3170    }
3171
3172    /* Calculate the address shift from the page size */
3173    chip->page_shift = ffs(mtd->writesize) - 1;
3174    /* Convert chipsize to number of pages per chip -1. */
3175    chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3176
3177    chip->bbt_erase_shift = chip->phys_erase_shift =
3178        ffs(mtd->erasesize) - 1;
3179    if (chip->chipsize & 0xffffffff)
3180        chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3181    else {
3182        chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3183        chip->chip_shift += 32 - 1;
3184    }
3185
3186    /* Set the bad block position */
3187    if (mtd->writesize > 512 || (busw & NAND_BUSWIDTH_16))
3188        chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3189    else
3190        chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3191
3192    /*
3193     * Bad block marker is stored in the last page of each block
3194     * on Samsung and Hynix MLC devices; stored in first two pages
3195     * of each block on Micron devices with 2KiB pages and on
3196     * SLC Samsung, Hynix, Toshiba and AMD/Spansion. All others scan
3197     * only the first page.
3198     */
3199    if ((chip->cellinfo & NAND_CI_CELLTYPE_MSK) &&
3200            (*maf_id == NAND_MFR_SAMSUNG ||
3201             *maf_id == NAND_MFR_HYNIX))
3202        chip->options |= NAND_BBT_SCANLASTPAGE;
3203    else if ((!(chip->cellinfo & NAND_CI_CELLTYPE_MSK) &&
3204                (*maf_id == NAND_MFR_SAMSUNG ||
3205                 *maf_id == NAND_MFR_HYNIX ||
3206                 *maf_id == NAND_MFR_TOSHIBA ||
3207                 *maf_id == NAND_MFR_AMD)) ||
3208            (mtd->writesize == 2048 &&
3209             *maf_id == NAND_MFR_MICRON))
3210        chip->options |= NAND_BBT_SCAN2NDPAGE;
3211
3212    /*
3213     * Numonyx/ST 2K pages, x8 bus use BOTH byte 1 and 6
3214     */
3215    if (!(busw & NAND_BUSWIDTH_16) &&
3216            *maf_id == NAND_MFR_STMICRO &&
3217            mtd->writesize == 2048) {
3218        chip->options |= NAND_BBT_SCANBYTE1AND6;
3219        chip->badblockpos = 0;
3220    }
3221
3222    /* Check for AND chips with 4 page planes */
3223    if (chip->options & NAND_4PAGE_ARRAY)
3224        chip->erase_cmd = multi_erase_cmd;
3225    else
3226        chip->erase_cmd = single_erase_cmd;
3227
3228    /* Do not replace user supplied command function ! */
3229    if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3230        chip->cmdfunc = nand_command_lp;
3231
3232    /* TODO onfi flash name */
3233    printk(KERN_INFO "NAND device: Manufacturer ID:"
3234        " 0x%02x, Chip ID: 0x%02x (%s %s)\n", *maf_id, *dev_id,
3235        nand_manuf_ids[maf_idx].name,
3236        chip->onfi_version ? chip->onfi_params.model : type->name);
3237
3238    return type;
3239}
3240
3241/**
3242 * nand_scan_ident - [NAND Interface] Scan for the NAND device
3243 * @mtd: MTD device structure
3244 * @maxchips: Number of chips to scan for
3245 * @table: Alternative NAND ID table
3246 *
3247 * This is the first phase of the normal nand_scan() function. It
3248 * reads the flash ID and sets up MTD fields accordingly.
3249 *
3250 * The mtd->owner field must be set to the module of the caller.
3251 */
3252int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3253            struct nand_flash_dev *table)
3254{
3255    int i, busw, nand_maf_id, nand_dev_id;
3256    struct nand_chip *chip = mtd->priv;
3257    struct nand_flash_dev *type;
3258
3259    /* Get buswidth to select the correct functions */
3260    busw = chip->options & NAND_BUSWIDTH_16;
3261    /* Set the default functions */
3262    nand_set_defaults(chip, busw);
3263
3264    /* Read the flash type */
3265    type = nand_get_flash_type(mtd, chip, busw,
3266                &nand_maf_id, &nand_dev_id, table);
3267
3268    if (IS_ERR(type)) {
3269        if (!(chip->options & NAND_SCAN_SILENT_NODEV))
3270            printk(KERN_WARNING "No NAND device found.\n");
3271        chip->select_chip(mtd, -1);
3272        return PTR_ERR(type);
3273    }
3274
3275    /* Check for a chip array */
3276    for (i = 1; i < maxchips; i++) {
3277        chip->select_chip(mtd, i);
3278        /* See comment in nand_get_flash_type for reset */
3279        chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3280        /* Send the command for reading device ID */
3281        chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3282        /* Read manufacturer and device IDs */
3283        if (nand_maf_id != chip->read_byte(mtd) ||
3284            nand_dev_id != chip->read_byte(mtd))
3285            break;
3286    }
3287    if (i > 1)
3288        printk(KERN_INFO "%d NAND chips detected\n", i);
3289
3290    /* Store the number of chips and calc total size for mtd */
3291    chip->numchips = i;
3292    mtd->size = i * chip->chipsize;
3293
3294    return 0;
3295}
3296EXPORT_SYMBOL(nand_scan_ident);
3297
3298
3299/**
3300 * nand_scan_tail - [NAND Interface] Scan for the NAND device
3301 * @mtd: MTD device structure
3302 *
3303 * This is the second phase of the normal nand_scan() function. It
3304 * fills out all the uninitialized function pointers with the defaults
3305 * and scans for a bad block table if appropriate.
3306 */
3307int nand_scan_tail(struct mtd_info *mtd)
3308{
3309    int i;
3310    struct nand_chip *chip = mtd->priv;
3311
3312    if (!(chip->options & NAND_OWN_BUFFERS))
3313        chip->buffers = kmalloc(sizeof(*chip->buffers), GFP_KERNEL);
3314    if (!chip->buffers)
3315        return -ENOMEM;
3316
3317    /* Set the internal oob buffer location, just after the page data */
3318    chip->oob_poi = chip->buffers->databuf + mtd->writesize;
3319
3320    /*
3321     * If no default placement scheme is given, select an appropriate one
3322     */
3323    if (!chip->ecc.layout && (chip->ecc.mode != NAND_ECC_SOFT_BCH)) {
3324        switch (mtd->oobsize) {
3325        case 8:
3326            chip->ecc.layout = &nand_oob_8;
3327            break;
3328        case 16:
3329            chip->ecc.layout = &nand_oob_16;
3330            break;
3331        case 64:
3332            chip->ecc.layout = &nand_oob_64;
3333            break;
3334        case 128:
3335            chip->ecc.layout = &nand_oob_128;
3336            break;
3337        default:
3338            printk(KERN_WARNING "No oob scheme defined for "
3339                   "oobsize %d\n", mtd->oobsize);
3340            BUG();
3341        }
3342    }
3343
3344    if (!chip->write_page)
3345        chip->write_page = nand_write_page;
3346
3347    /*
3348     * check ECC mode, default to software if 3byte/512byte hardware ECC is
3349     * selected and we have 256 byte pagesize fallback to software ECC
3350     */
3351
3352    switch (chip->ecc.mode) {
3353    case NAND_ECC_HW_OOB_FIRST:
3354        /* Similar to NAND_ECC_HW, but a separate read_page handle */
3355        if (!chip->ecc.calculate || !chip->ecc.correct ||
3356             !chip->ecc.hwctl) {
3357            printk(KERN_WARNING "No ECC functions supplied; "
3358                   "Hardware ECC not possible\n");
3359            BUG();
3360        }
3361        if (!chip->ecc.read_page) {
3362            chip->ecc.read_page = nand_read_page_hwecc_oob_first;
3363            if (!chip->ecc.read_subpage)
3364                chip->ecc.read_subpage = nand_read_subpage_hwecc_oob_first;
3365        }
3366
3367    case NAND_ECC_HW:
3368        /* Use standard hwecc read page function ? */
3369        if (!chip->ecc.read_page)
3370            chip->ecc.read_page = nand_read_page_hwecc;
3371        if (!chip->ecc.write_page)
3372            chip->ecc.write_page = nand_write_page_hwecc;
3373        if (!chip->ecc.read_page_raw)
3374            chip->ecc.read_page_raw = nand_read_page_raw;
3375        if (!chip->ecc.write_page_raw)
3376            chip->ecc.write_page_raw = nand_write_page_raw;
3377        if (!chip->ecc.read_oob)
3378            chip->ecc.read_oob = nand_read_oob_std;
3379        if (!chip->ecc.write_oob)
3380            chip->ecc.write_oob = nand_write_oob_std;
3381
3382    case NAND_ECC_HW_SYNDROME:
3383        if ((!chip->ecc.calculate || !chip->ecc.correct ||
3384             !chip->ecc.hwctl) &&
3385            (!chip->ecc.read_page ||
3386             chip->ecc.read_page == nand_read_page_hwecc ||
3387             !chip->ecc.write_page ||
3388             chip->ecc.write_page == nand_write_page_hwecc)) {
3389            printk(KERN_WARNING "No ECC functions supplied; "
3390                   "Hardware ECC not possible\n");
3391            BUG();
3392        }
3393        /* Use standard syndrome read/write page function ? */
3394        if (!chip->ecc.read_page)
3395            chip->ecc.read_page = nand_read_page_syndrome;
3396        if (!chip->ecc.write_page)
3397            chip->ecc.write_page = nand_write_page_syndrome;
3398        if (!chip->ecc.read_page_raw)
3399            chip->ecc.read_page_raw = nand_read_page_raw_syndrome;
3400        if (!chip->ecc.write_page_raw)
3401            chip->ecc.write_page_raw = nand_write_page_raw_syndrome;
3402        if (!chip->ecc.read_oob)
3403            chip->ecc.read_oob = nand_read_oob_syndrome;
3404        if (!chip->ecc.write_oob)
3405            chip->ecc.write_oob = nand_write_oob_syndrome;
3406
3407        if (mtd->writesize >= chip->ecc.size)
3408            break;
3409        printk(KERN_WARNING "%d byte HW ECC not possible on "
3410               "%d byte page size, fallback to SW ECC\n",
3411               chip->ecc.size, mtd->writesize);
3412        chip->ecc.mode = NAND_ECC_SOFT;
3413
3414    case NAND_ECC_SOFT:
3415        chip->ecc.calculate = nand_calculate_ecc;
3416        chip->ecc.correct = nand_correct_data;
3417        chip->ecc.read_page = nand_read_page_swecc;
3418        chip->ecc.read_subpage = nand_read_subpage;
3419        chip->ecc.write_page = nand_write_page_swecc;
3420        chip->ecc.read_page_raw = nand_read_page_raw;
3421        chip->ecc.write_page_raw = nand_write_page_raw;
3422        chip->ecc.read_oob = nand_read_oob_std;
3423        chip->ecc.write_oob = nand_write_oob_std;
3424        if (!chip->ecc.size)
3425            chip->ecc.size = 256;
3426        chip->ecc.bytes = 3;
3427        break;
3428
3429    case NAND_ECC_SOFT_BCH:
3430        if (!mtd_nand_has_bch()) {
3431            printk(KERN_WARNING "CONFIG_MTD_ECC_BCH not enabled\n");
3432            BUG();
3433        }
3434        chip->ecc.calculate = nand_bch_calculate_ecc;
3435        chip->ecc.correct = nand_bch_correct_data;
3436        chip->ecc.read_page = nand_read_page_swecc;
3437        chip->ecc.read_subpage = nand_read_subpage;
3438        chip->ecc.write_page = nand_write_page_swecc;
3439        chip->ecc.read_page_raw = nand_read_page_raw;
3440        chip->ecc.write_page_raw = nand_write_page_raw;
3441        chip->ecc.read_oob = nand_read_oob_std;
3442        chip->ecc.write_oob = nand_write_oob_std;
3443        /*
3444         * Board driver should supply ecc.size and ecc.bytes values to
3445         * select how many bits are correctable; see nand_bch_init()
3446         * for details.
3447         * Otherwise, default to 4 bits for large page devices
3448         */
3449        if (!chip->ecc.size && (mtd->oobsize >= 64)) {
3450            chip->ecc.size = 512;
3451            chip->ecc.bytes = 7;
3452        }
3453        chip->ecc.priv = nand_bch_init(mtd,
3454                           chip->ecc.size,
3455                           chip->ecc.bytes,
3456                           &chip->ecc.layout);
3457        if (!chip->ecc.priv) {
3458            printk(KERN_WARNING "BCH ECC initialization failed!\n");
3459            BUG();
3460        }
3461        break;
3462
3463    case NAND_ECC_NONE:
3464        printk(KERN_WARNING "NAND_ECC_NONE selected by board driver. "
3465               "This is not recommended !!\n");
3466        chip->ecc.read_page = nand_read_page_raw;
3467        chip->ecc.write_page = nand_write_page_raw;
3468        chip->ecc.read_oob = nand_read_oob_std;
3469        chip->ecc.read_page_raw = nand_read_page_raw;
3470        chip->ecc.write_page_raw = nand_write_page_raw;
3471        chip->ecc.write_oob = nand_write_oob_std;
3472        chip->ecc.size = mtd->writesize;
3473        chip->ecc.bytes = 0;
3474        break;
3475
3476    default:
3477        printk(KERN_WARNING "Invalid NAND_ECC_MODE %d\n",
3478               chip->ecc.mode);
3479        BUG();
3480    }
3481
3482    /*
3483     * The number of bytes available for a client to place data into
3484     * the out of band area
3485     */
3486    chip->ecc.layout->oobavail = 0;
3487    for (i = 0; chip->ecc.layout->oobfree[i].length
3488            && i < ARRAY_SIZE(chip->ecc.layout->oobfree); i++)
3489        chip->ecc.layout->oobavail +=
3490            chip->ecc.layout->oobfree[i].length;
3491    mtd->oobavail = chip->ecc.layout->oobavail;
3492
3493    /*
3494     * Set the number of read / write steps for one page depending on ECC
3495     * mode
3496     */
3497    chip->ecc.steps = mtd->writesize / chip->ecc.size;
3498    if (chip->ecc.steps * chip->ecc.size != mtd->writesize) {
3499        printk(KERN_WARNING "Invalid ecc parameters\n");
3500        BUG();
3501    }
3502    chip->ecc.total = chip->ecc.steps * chip->ecc.bytes;
3503
3504    /*
3505     * Allow subpage writes up to ecc.steps. Not possible for MLC
3506     * FLASH.
3507     */
3508    if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3509        !(chip->cellinfo & NAND_CI_CELLTYPE_MSK)) {
3510        switch (chip->ecc.steps) {
3511        case 2:
3512            mtd->subpage_sft = 1;
3513            break;
3514        case 4:
3515        case 8:
3516        case 16:
3517            mtd->subpage_sft = 2;
3518            break;
3519        }
3520    }
3521    chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
3522
3523    /* Initialize state */
3524    chip->state = FL_READY;
3525
3526    /* De-select the device */
3527    chip->select_chip(mtd, -1);
3528
3529    /* Invalidate the pagebuffer reference */
3530    chip->pagebuf = -1;
3531
3532    /* Fill in remaining MTD driver data */
3533    mtd->type = MTD_NANDFLASH;
3534    mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
3535                        MTD_CAP_NANDFLASH;
3536    mtd->erase = nand_erase;
3537    mtd->point = NULL;
3538    mtd->unpoint = NULL;
3539    mtd->read = nand_read;
3540    mtd->write = nand_write;
3541    mtd->panic_write = panic_nand_write;
3542    mtd->read_oob = nand_read_oob;
3543    mtd->write_oob = nand_write_oob;
3544    mtd->sync = nand_sync;
3545    mtd->lock = NULL;
3546    mtd->unlock = NULL;
3547    mtd->suspend = nand_suspend;
3548    mtd->resume = nand_resume;
3549    mtd->block_isbad = nand_block_isbad;
3550    mtd->block_markbad = nand_block_markbad;
3551    mtd->writebufsize = mtd->writesize;
3552
3553    /* propagate ecc.layout to mtd_info */
3554    mtd->ecclayout = chip->ecc.layout;
3555
3556    /* Check, if we should skip the bad block table scan */
3557    if (chip->options & NAND_SKIP_BBTSCAN)
3558        return 0;
3559
3560    /* Build bad block table */
3561    return chip->scan_bbt(mtd);
3562}
3563EXPORT_SYMBOL(nand_scan_tail);
3564
3565/* is_module_text_address() isn't exported, and it's mostly a pointless
3566 * test if this is a module _anyway_ -- they'd have to try _really_ hard
3567 * to call us from in-kernel code if the core NAND support is modular. */
3568#ifdef MODULE
3569#define caller_is_module() (1)
3570#else
3571#define caller_is_module() \
3572    is_module_text_address((unsigned long)__builtin_return_address(0))
3573#endif
3574
3575/**
3576 * nand_scan - [NAND Interface] Scan for the NAND device
3577 * @mtd: MTD device structure
3578 * @maxchips: Number of chips to scan for
3579 *
3580 * This fills out all the uninitialized function pointers
3581 * with the defaults.
3582 * The flash ID is read and the mtd/chip structures are
3583 * filled with the appropriate values.
3584 * The mtd->owner field must be set to the module of the caller
3585 *
3586 */
3587int nand_scan(struct mtd_info *mtd, int maxchips)
3588{
3589    int ret;
3590
3591    /* Many callers got this wrong, so check for it for a while... */
3592    if (!mtd->owner && caller_is_module()) {
3593        printk(KERN_CRIT "%s called with NULL mtd->owner!\n",
3594                __func__);
3595        BUG();
3596    }
3597
3598    ret = nand_scan_ident(mtd, maxchips, NULL);
3599    if (!ret)
3600        ret = nand_scan_tail(mtd);
3601    return ret;
3602}
3603EXPORT_SYMBOL(nand_scan);
3604
3605/**
3606 * nand_release - [NAND Interface] Free resources held by the NAND device
3607 * @mtd: MTD device structure
3608*/
3609void nand_release(struct mtd_info *mtd)
3610{
3611    struct nand_chip *chip = mtd->priv;
3612
3613    if (chip->ecc.mode == NAND_ECC_SOFT_BCH)
3614        nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
3615
3616#ifdef CONFIG_MTD_PARTITIONS
3617    /* Deregister partitions */
3618    del_mtd_partitions(mtd);
3619#endif
3620    /* Deregister the device */
3621    del_mtd_device(mtd);
3622
3623    /* Free bad block table memory */
3624    kfree(chip->bbt);
3625    if (!(chip->options & NAND_OWN_BUFFERS))
3626        kfree(chip->buffers);
3627
3628    /* Free bad block descriptor memory */
3629    if (chip->badblock_pattern && chip->badblock_pattern->options
3630            & NAND_BBT_DYNAMICSTRUCT)
3631        kfree(chip->badblock_pattern);
3632}
3633EXPORT_SYMBOL_GPL(nand_release);
3634
3635static int __init nand_base_init(void)
3636{
3637    led_trigger_register_simple("nand-disk", &nand_led_trigger);
3638    return 0;
3639}
3640
3641static void __exit nand_base_exit(void)
3642{
3643    led_trigger_unregister_simple(nand_led_trigger);
3644}
3645
3646module_init(nand_base_init);
3647module_exit(nand_base_exit);
3648
3649MODULE_LICENSE("GPL");
3650MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
3651MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
3652MODULE_DESCRIPTION("Generic NAND flash driver code");
3653

Archive Download this file



interactive