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