linux/drivers/mtd/nand/atmel_nand.c
<<
>>
Prefs
   1/*
   2 *  Copyright © 2003 Rick Bronson
   3 *
   4 *  Derived from drivers/mtd/nand/autcpu12.c
   5 *       Copyright © 2001 Thomas Gleixner (gleixner@autronix.de)
   6 *
   7 *  Derived from drivers/mtd/spia.c
   8 *       Copyright © 2000 Steven J. Hill (sjhill@cotw.com)
   9 *
  10 *
  11 *  Add Hardware ECC support for AT91SAM9260 / AT91SAM9263
  12 *     Richard Genoud (richard.genoud@gmail.com), Adeneo Copyright © 2007
  13 *
  14 *     Derived from Das U-Boot source code
  15 *              (u-boot-1.1.5/board/atmel/at91sam9263ek/nand.c)
  16 *     © Copyright 2006 ATMEL Rousset, Lacressonniere Nicolas
  17 *
  18 *  Add Programmable Multibit ECC support for various AT91 SoC
  19 *     © Copyright 2012 ATMEL, Hong Xu
  20 *
  21 *  Add Nand Flash Controller support for SAMA5 SoC
  22 *     © Copyright 2013 ATMEL, Josh Wu (josh.wu@atmel.com)
  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#include <linux/clk.h>
  31#include <linux/dma-mapping.h>
  32#include <linux/slab.h>
  33#include <linux/module.h>
  34#include <linux/moduleparam.h>
  35#include <linux/platform_device.h>
  36#include <linux/of.h>
  37#include <linux/of_device.h>
  38#include <linux/of_gpio.h>
  39#include <linux/of_mtd.h>
  40#include <linux/mtd/mtd.h>
  41#include <linux/mtd/nand.h>
  42#include <linux/mtd/partitions.h>
  43
  44#include <linux/delay.h>
  45#include <linux/dmaengine.h>
  46#include <linux/gpio.h>
  47#include <linux/interrupt.h>
  48#include <linux/io.h>
  49#include <linux/platform_data/atmel.h>
  50
  51static int use_dma = 1;
  52module_param(use_dma, int, 0);
  53
  54static int on_flash_bbt = 0;
  55module_param(on_flash_bbt, int, 0);
  56
  57/* Register access macros */
  58#define ecc_readl(add, reg)                             \
  59        __raw_readl(add + ATMEL_ECC_##reg)
  60#define ecc_writel(add, reg, value)                     \
  61        __raw_writel((value), add + ATMEL_ECC_##reg)
  62
  63#include "atmel_nand_ecc.h"     /* Hardware ECC registers */
  64#include "atmel_nand_nfc.h"     /* Nand Flash Controller definition */
  65
  66/* oob layout for large page size
  67 * bad block info is on bytes 0 and 1
  68 * the bytes have to be consecutives to avoid
  69 * several NAND_CMD_RNDOUT during read
  70 */
  71static struct nand_ecclayout atmel_oobinfo_large = {
  72        .eccbytes = 4,
  73        .eccpos = {60, 61, 62, 63},
  74        .oobfree = {
  75                {2, 58}
  76        },
  77};
  78
  79/* oob layout for small page size
  80 * bad block info is on bytes 4 and 5
  81 * the bytes have to be consecutives to avoid
  82 * several NAND_CMD_RNDOUT during read
  83 */
  84static struct nand_ecclayout atmel_oobinfo_small = {
  85        .eccbytes = 4,
  86        .eccpos = {0, 1, 2, 3},
  87        .oobfree = {
  88                {6, 10}
  89        },
  90};
  91
  92struct atmel_nfc {
  93        void __iomem            *base_cmd_regs;
  94        void __iomem            *hsmc_regs;
  95        void                    *sram_bank0;
  96        dma_addr_t              sram_bank0_phys;
  97        bool                    use_nfc_sram;
  98        bool                    write_by_sram;
  99
 100        struct clk              *clk;
 101
 102        bool                    is_initialized;
 103        struct completion       comp_ready;
 104        struct completion       comp_cmd_done;
 105        struct completion       comp_xfer_done;
 106
 107        /* Point to the sram bank which include readed data via NFC */
 108        void                    *data_in_sram;
 109        bool                    will_write_sram;
 110};
 111static struct atmel_nfc nand_nfc;
 112
 113struct atmel_nand_host {
 114        struct nand_chip        nand_chip;
 115        struct mtd_info         mtd;
 116        void __iomem            *io_base;
 117        dma_addr_t              io_phys;
 118        struct atmel_nand_data  board;
 119        struct device           *dev;
 120        void __iomem            *ecc;
 121
 122        struct completion       comp;
 123        struct dma_chan         *dma_chan;
 124
 125        struct atmel_nfc        *nfc;
 126
 127        bool                    has_pmecc;
 128        u8                      pmecc_corr_cap;
 129        u16                     pmecc_sector_size;
 130        bool                    has_no_lookup_table;
 131        u32                     pmecc_lookup_table_offset;
 132        u32                     pmecc_lookup_table_offset_512;
 133        u32                     pmecc_lookup_table_offset_1024;
 134
 135        int                     pmecc_degree;   /* Degree of remainders */
 136        int                     pmecc_cw_len;   /* Length of codeword */
 137
 138        void __iomem            *pmerrloc_base;
 139        void __iomem            *pmecc_rom_base;
 140
 141        /* lookup table for alpha_to and index_of */
 142        void __iomem            *pmecc_alpha_to;
 143        void __iomem            *pmecc_index_of;
 144
 145        /* data for pmecc computation */
 146        int16_t                 *pmecc_partial_syn;
 147        int16_t                 *pmecc_si;
 148        int16_t                 *pmecc_smu;     /* Sigma table */
 149        int16_t                 *pmecc_lmu;     /* polynomal order */
 150        int                     *pmecc_mu;
 151        int                     *pmecc_dmu;
 152        int                     *pmecc_delta;
 153};
 154
 155static struct nand_ecclayout atmel_pmecc_oobinfo;
 156
 157/*
 158 * Enable NAND.
 159 */
 160static void atmel_nand_enable(struct atmel_nand_host *host)
 161{
 162        if (gpio_is_valid(host->board.enable_pin))
 163                gpio_set_value(host->board.enable_pin, 0);
 164}
 165
 166/*
 167 * Disable NAND.
 168 */
 169static void atmel_nand_disable(struct atmel_nand_host *host)
 170{
 171        if (gpio_is_valid(host->board.enable_pin))
 172                gpio_set_value(host->board.enable_pin, 1);
 173}
 174
 175/*
 176 * Hardware specific access to control-lines
 177 */
 178static void atmel_nand_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl)
 179{
 180        struct nand_chip *nand_chip = mtd->priv;
 181        struct atmel_nand_host *host = nand_chip->priv;
 182
 183        if (ctrl & NAND_CTRL_CHANGE) {
 184                if (ctrl & NAND_NCE)
 185                        atmel_nand_enable(host);
 186                else
 187                        atmel_nand_disable(host);
 188        }
 189        if (cmd == NAND_CMD_NONE)
 190                return;
 191
 192        if (ctrl & NAND_CLE)
 193                writeb(cmd, host->io_base + (1 << host->board.cle));
 194        else
 195                writeb(cmd, host->io_base + (1 << host->board.ale));
 196}
 197
 198/*
 199 * Read the Device Ready pin.
 200 */
 201static int atmel_nand_device_ready(struct mtd_info *mtd)
 202{
 203        struct nand_chip *nand_chip = mtd->priv;
 204        struct atmel_nand_host *host = nand_chip->priv;
 205
 206        return gpio_get_value(host->board.rdy_pin) ^
 207                !!host->board.rdy_pin_active_low;
 208}
 209
 210/* Set up for hardware ready pin and enable pin. */
 211static int atmel_nand_set_enable_ready_pins(struct mtd_info *mtd)
 212{
 213        struct nand_chip *chip = mtd->priv;
 214        struct atmel_nand_host *host = chip->priv;
 215        int res = 0;
 216
 217        if (gpio_is_valid(host->board.rdy_pin)) {
 218                res = devm_gpio_request(host->dev,
 219                                host->board.rdy_pin, "nand_rdy");
 220                if (res < 0) {
 221                        dev_err(host->dev,
 222                                "can't request rdy gpio %d\n",
 223                                host->board.rdy_pin);
 224                        return res;
 225                }
 226
 227                res = gpio_direction_input(host->board.rdy_pin);
 228                if (res < 0) {
 229                        dev_err(host->dev,
 230                                "can't request input direction rdy gpio %d\n",
 231                                host->board.rdy_pin);
 232                        return res;
 233                }
 234
 235                chip->dev_ready = atmel_nand_device_ready;
 236        }
 237
 238        if (gpio_is_valid(host->board.enable_pin)) {
 239                res = devm_gpio_request(host->dev,
 240                                host->board.enable_pin, "nand_enable");
 241                if (res < 0) {
 242                        dev_err(host->dev,
 243                                "can't request enable gpio %d\n",
 244                                host->board.enable_pin);
 245                        return res;
 246                }
 247
 248                res = gpio_direction_output(host->board.enable_pin, 1);
 249                if (res < 0) {
 250                        dev_err(host->dev,
 251                                "can't request output direction enable gpio %d\n",
 252                                host->board.enable_pin);
 253                        return res;
 254                }
 255        }
 256
 257        return res;
 258}
 259
 260/*
 261 * Minimal-overhead PIO for data access.
 262 */
 263static void atmel_read_buf8(struct mtd_info *mtd, u8 *buf, int len)
 264{
 265        struct nand_chip        *nand_chip = mtd->priv;
 266        struct atmel_nand_host *host = nand_chip->priv;
 267
 268        if (host->nfc && host->nfc->use_nfc_sram && host->nfc->data_in_sram) {
 269                memcpy(buf, host->nfc->data_in_sram, len);
 270                host->nfc->data_in_sram += len;
 271        } else {
 272                __raw_readsb(nand_chip->IO_ADDR_R, buf, len);
 273        }
 274}
 275
 276static void atmel_read_buf16(struct mtd_info *mtd, u8 *buf, int len)
 277{
 278        struct nand_chip        *nand_chip = mtd->priv;
 279        struct atmel_nand_host *host = nand_chip->priv;
 280
 281        if (host->nfc && host->nfc->use_nfc_sram && host->nfc->data_in_sram) {
 282                memcpy(buf, host->nfc->data_in_sram, len);
 283                host->nfc->data_in_sram += len;
 284        } else {
 285                __raw_readsw(nand_chip->IO_ADDR_R, buf, len / 2);
 286        }
 287}
 288
 289static void atmel_write_buf8(struct mtd_info *mtd, const u8 *buf, int len)
 290{
 291        struct nand_chip        *nand_chip = mtd->priv;
 292
 293        __raw_writesb(nand_chip->IO_ADDR_W, buf, len);
 294}
 295
 296static void atmel_write_buf16(struct mtd_info *mtd, const u8 *buf, int len)
 297{
 298        struct nand_chip        *nand_chip = mtd->priv;
 299
 300        __raw_writesw(nand_chip->IO_ADDR_W, buf, len / 2);
 301}
 302
 303static void dma_complete_func(void *completion)
 304{
 305        complete(completion);
 306}
 307
 308static int nfc_set_sram_bank(struct atmel_nand_host *host, unsigned int bank)
 309{
 310        /* NFC only has two banks. Must be 0 or 1 */
 311        if (bank > 1)
 312                return -EINVAL;
 313
 314        if (bank) {
 315                /* Only for a 2k-page or lower flash, NFC can handle 2 banks */
 316                if (host->mtd.writesize > 2048)
 317                        return -EINVAL;
 318                nfc_writel(host->nfc->hsmc_regs, BANK, ATMEL_HSMC_NFC_BANK1);
 319        } else {
 320                nfc_writel(host->nfc->hsmc_regs, BANK, ATMEL_HSMC_NFC_BANK0);
 321        }
 322
 323        return 0;
 324}
 325
 326static uint nfc_get_sram_off(struct atmel_nand_host *host)
 327{
 328        if (nfc_readl(host->nfc->hsmc_regs, BANK) & ATMEL_HSMC_NFC_BANK1)
 329                return NFC_SRAM_BANK1_OFFSET;
 330        else
 331                return 0;
 332}
 333
 334static dma_addr_t nfc_sram_phys(struct atmel_nand_host *host)
 335{
 336        if (nfc_readl(host->nfc->hsmc_regs, BANK) & ATMEL_HSMC_NFC_BANK1)
 337                return host->nfc->sram_bank0_phys + NFC_SRAM_BANK1_OFFSET;
 338        else
 339                return host->nfc->sram_bank0_phys;
 340}
 341
 342static int atmel_nand_dma_op(struct mtd_info *mtd, void *buf, int len,
 343                               int is_read)
 344{
 345        struct dma_device *dma_dev;
 346        enum dma_ctrl_flags flags;
 347        dma_addr_t dma_src_addr, dma_dst_addr, phys_addr;
 348        struct dma_async_tx_descriptor *tx = NULL;
 349        dma_cookie_t cookie;
 350        struct nand_chip *chip = mtd->priv;
 351        struct atmel_nand_host *host = chip->priv;
 352        void *p = buf;
 353        int err = -EIO;
 354        enum dma_data_direction dir = is_read ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
 355        struct atmel_nfc *nfc = host->nfc;
 356
 357        if (buf >= high_memory)
 358                goto err_buf;
 359
 360        dma_dev = host->dma_chan->device;
 361
 362        flags = DMA_CTRL_ACK | DMA_PREP_INTERRUPT;
 363
 364        phys_addr = dma_map_single(dma_dev->dev, p, len, dir);
 365        if (dma_mapping_error(dma_dev->dev, phys_addr)) {
 366                dev_err(host->dev, "Failed to dma_map_single\n");
 367                goto err_buf;
 368        }
 369
 370        if (is_read) {
 371                if (nfc && nfc->data_in_sram)
 372                        dma_src_addr = nfc_sram_phys(host) + (nfc->data_in_sram
 373                                - (nfc->sram_bank0 + nfc_get_sram_off(host)));
 374                else
 375                        dma_src_addr = host->io_phys;
 376
 377                dma_dst_addr = phys_addr;
 378        } else {
 379                dma_src_addr = phys_addr;
 380
 381                if (nfc && nfc->write_by_sram)
 382                        dma_dst_addr = nfc_sram_phys(host);
 383                else
 384                        dma_dst_addr = host->io_phys;
 385        }
 386
 387        tx = dma_dev->device_prep_dma_memcpy(host->dma_chan, dma_dst_addr,
 388                                             dma_src_addr, len, flags);
 389        if (!tx) {
 390                dev_err(host->dev, "Failed to prepare DMA memcpy\n");
 391                goto err_dma;
 392        }
 393
 394        init_completion(&host->comp);
 395        tx->callback = dma_complete_func;
 396        tx->callback_param = &host->comp;
 397
 398        cookie = tx->tx_submit(tx);
 399        if (dma_submit_error(cookie)) {
 400                dev_err(host->dev, "Failed to do DMA tx_submit\n");
 401                goto err_dma;
 402        }
 403
 404        dma_async_issue_pending(host->dma_chan);
 405        wait_for_completion(&host->comp);
 406
 407        if (is_read && nfc && nfc->data_in_sram)
 408                /* After read data from SRAM, need to increase the position */
 409                nfc->data_in_sram += len;
 410
 411        err = 0;
 412
 413err_dma:
 414        dma_unmap_single(dma_dev->dev, phys_addr, len, dir);
 415err_buf:
 416        if (err != 0)
 417                dev_dbg(host->dev, "Fall back to CPU I/O\n");
 418        return err;
 419}
 420
 421static void atmel_read_buf(struct mtd_info *mtd, u8 *buf, int len)
 422{
 423        struct nand_chip *chip = mtd->priv;
 424        struct atmel_nand_host *host = chip->priv;
 425
 426        if (use_dma && len > mtd->oobsize)
 427                /* only use DMA for bigger than oob size: better performances */
 428                if (atmel_nand_dma_op(mtd, buf, len, 1) == 0)
 429                        return;
 430
 431        if (host->board.bus_width_16)
 432                atmel_read_buf16(mtd, buf, len);
 433        else
 434                atmel_read_buf8(mtd, buf, len);
 435}
 436
 437static void atmel_write_buf(struct mtd_info *mtd, const u8 *buf, int len)
 438{
 439        struct nand_chip *chip = mtd->priv;
 440        struct atmel_nand_host *host = chip->priv;
 441
 442        if (use_dma && len > mtd->oobsize)
 443                /* only use DMA for bigger than oob size: better performances */
 444                if (atmel_nand_dma_op(mtd, (void *)buf, len, 0) == 0)
 445                        return;
 446
 447        if (host->board.bus_width_16)
 448                atmel_write_buf16(mtd, buf, len);
 449        else
 450                atmel_write_buf8(mtd, buf, len);
 451}
 452
 453/*
 454 * Return number of ecc bytes per sector according to sector size and
 455 * correction capability
 456 *
 457 * Following table shows what at91 PMECC supported:
 458 * Correction Capability        Sector_512_bytes        Sector_1024_bytes
 459 * =====================        ================        =================
 460 *                2-bits                 4-bytes                  4-bytes
 461 *                4-bits                 7-bytes                  7-bytes
 462 *                8-bits                13-bytes                 14-bytes
 463 *               12-bits                20-bytes                 21-bytes
 464 *               24-bits                39-bytes                 42-bytes
 465 */
 466static int pmecc_get_ecc_bytes(int cap, int sector_size)
 467{
 468        int m = 12 + sector_size / 512;
 469        return (m * cap + 7) / 8;
 470}
 471
 472static void pmecc_config_ecc_layout(struct nand_ecclayout *layout,
 473                                    int oobsize, int ecc_len)
 474{
 475        int i;
 476
 477        layout->eccbytes = ecc_len;
 478
 479        /* ECC will occupy the last ecc_len bytes continuously */
 480        for (i = 0; i < ecc_len; i++)
 481                layout->eccpos[i] = oobsize - ecc_len + i;
 482
 483        layout->oobfree[0].offset = 2;
 484        layout->oobfree[0].length =
 485                oobsize - ecc_len - layout->oobfree[0].offset;
 486}
 487
 488static void __iomem *pmecc_get_alpha_to(struct atmel_nand_host *host)
 489{
 490        int table_size;
 491
 492        table_size = host->pmecc_sector_size == 512 ?
 493                PMECC_LOOKUP_TABLE_SIZE_512 : PMECC_LOOKUP_TABLE_SIZE_1024;
 494
 495        return host->pmecc_rom_base + host->pmecc_lookup_table_offset +
 496                        table_size * sizeof(int16_t);
 497}
 498
 499static int pmecc_data_alloc(struct atmel_nand_host *host)
 500{
 501        const int cap = host->pmecc_corr_cap;
 502        int size;
 503
 504        size = (2 * cap + 1) * sizeof(int16_t);
 505        host->pmecc_partial_syn = devm_kzalloc(host->dev, size, GFP_KERNEL);
 506        host->pmecc_si = devm_kzalloc(host->dev, size, GFP_KERNEL);
 507        host->pmecc_lmu = devm_kzalloc(host->dev,
 508                        (cap + 1) * sizeof(int16_t), GFP_KERNEL);
 509        host->pmecc_smu = devm_kzalloc(host->dev,
 510                        (cap + 2) * size, GFP_KERNEL);
 511
 512        size = (cap + 1) * sizeof(int);
 513        host->pmecc_mu = devm_kzalloc(host->dev, size, GFP_KERNEL);
 514        host->pmecc_dmu = devm_kzalloc(host->dev, size, GFP_KERNEL);
 515        host->pmecc_delta = devm_kzalloc(host->dev, size, GFP_KERNEL);
 516
 517        if (!host->pmecc_partial_syn ||
 518                !host->pmecc_si ||
 519                !host->pmecc_lmu ||
 520                !host->pmecc_smu ||
 521                !host->pmecc_mu ||
 522                !host->pmecc_dmu ||
 523                !host->pmecc_delta)
 524                return -ENOMEM;
 525
 526        return 0;
 527}
 528
 529static void pmecc_gen_syndrome(struct mtd_info *mtd, int sector)
 530{
 531        struct nand_chip *nand_chip = mtd->priv;
 532        struct atmel_nand_host *host = nand_chip->priv;
 533        int i;
 534        uint32_t value;
 535
 536        /* Fill odd syndromes */
 537        for (i = 0; i < host->pmecc_corr_cap; i++) {
 538                value = pmecc_readl_rem_relaxed(host->ecc, sector, i / 2);
 539                if (i & 1)
 540                        value >>= 16;
 541                value &= 0xffff;
 542                host->pmecc_partial_syn[(2 * i) + 1] = (int16_t)value;
 543        }
 544}
 545
 546static void pmecc_substitute(struct mtd_info *mtd)
 547{
 548        struct nand_chip *nand_chip = mtd->priv;
 549        struct atmel_nand_host *host = nand_chip->priv;
 550        int16_t __iomem *alpha_to = host->pmecc_alpha_to;
 551        int16_t __iomem *index_of = host->pmecc_index_of;
 552        int16_t *partial_syn = host->pmecc_partial_syn;
 553        const int cap = host->pmecc_corr_cap;
 554        int16_t *si;
 555        int i, j;
 556
 557        /* si[] is a table that holds the current syndrome value,
 558         * an element of that table belongs to the field
 559         */
 560        si = host->pmecc_si;
 561
 562        memset(&si[1], 0, sizeof(int16_t) * (2 * cap - 1));
 563
 564        /* Computation 2t syndromes based on S(x) */
 565        /* Odd syndromes */
 566        for (i = 1; i < 2 * cap; i += 2) {
 567                for (j = 0; j < host->pmecc_degree; j++) {
 568                        if (partial_syn[i] & ((unsigned short)0x1 << j))
 569                                si[i] = readw_relaxed(alpha_to + i * j) ^ si[i];
 570                }
 571        }
 572        /* Even syndrome = (Odd syndrome) ** 2 */
 573        for (i = 2, j = 1; j <= cap; i = ++j << 1) {
 574                if (si[j] == 0) {
 575                        si[i] = 0;
 576                } else {
 577                        int16_t tmp;
 578
 579                        tmp = readw_relaxed(index_of + si[j]);
 580                        tmp = (tmp * 2) % host->pmecc_cw_len;
 581                        si[i] = readw_relaxed(alpha_to + tmp);
 582                }
 583        }
 584
 585        return;
 586}
 587
 588static void pmecc_get_sigma(struct mtd_info *mtd)
 589{
 590        struct nand_chip *nand_chip = mtd->priv;
 591        struct atmel_nand_host *host = nand_chip->priv;
 592
 593        int16_t *lmu = host->pmecc_lmu;
 594        int16_t *si = host->pmecc_si;
 595        int *mu = host->pmecc_mu;
 596        int *dmu = host->pmecc_dmu;     /* Discrepancy */
 597        int *delta = host->pmecc_delta; /* Delta order */
 598        int cw_len = host->pmecc_cw_len;
 599        const int16_t cap = host->pmecc_corr_cap;
 600        const int num = 2 * cap + 1;
 601        int16_t __iomem *index_of = host->pmecc_index_of;
 602        int16_t __iomem *alpha_to = host->pmecc_alpha_to;
 603        int i, j, k;
 604        uint32_t dmu_0_count, tmp;
 605        int16_t *smu = host->pmecc_smu;
 606
 607        /* index of largest delta */
 608        int ro;
 609        int largest;
 610        int diff;
 611
 612        dmu_0_count = 0;
 613
 614        /* First Row */
 615
 616        /* Mu */
 617        mu[0] = -1;
 618
 619        memset(smu, 0, sizeof(int16_t) * num);
 620        smu[0] = 1;
 621
 622        /* discrepancy set to 1 */
 623        dmu[0] = 1;
 624        /* polynom order set to 0 */
 625        lmu[0] = 0;
 626        delta[0] = (mu[0] * 2 - lmu[0]) >> 1;
 627
 628        /* Second Row */
 629
 630        /* Mu */
 631        mu[1] = 0;
 632        /* Sigma(x) set to 1 */
 633        memset(&smu[num], 0, sizeof(int16_t) * num);
 634        smu[num] = 1;
 635
 636        /* discrepancy set to S1 */
 637        dmu[1] = si[1];
 638
 639        /* polynom order set to 0 */
 640        lmu[1] = 0;
 641
 642        delta[1] = (mu[1] * 2 - lmu[1]) >> 1;
 643
 644        /* Init the Sigma(x) last row */
 645        memset(&smu[(cap + 1) * num], 0, sizeof(int16_t) * num);
 646
 647        for (i = 1; i <= cap; i++) {
 648                mu[i + 1] = i << 1;
 649                /* Begin Computing Sigma (Mu+1) and L(mu) */
 650                /* check if discrepancy is set to 0 */
 651                if (dmu[i] == 0) {
 652                        dmu_0_count++;
 653
 654                        tmp = ((cap - (lmu[i] >> 1) - 1) / 2);
 655                        if ((cap - (lmu[i] >> 1) - 1) & 0x1)
 656                                tmp += 2;
 657                        else
 658                                tmp += 1;
 659
 660                        if (dmu_0_count == tmp) {
 661                                for (j = 0; j <= (lmu[i] >> 1) + 1; j++)
 662                                        smu[(cap + 1) * num + j] =
 663                                                        smu[i * num + j];
 664
 665                                lmu[cap + 1] = lmu[i];
 666                                return;
 667                        }
 668
 669                        /* copy polynom */
 670                        for (j = 0; j <= lmu[i] >> 1; j++)
 671                                smu[(i + 1) * num + j] = smu[i * num + j];
 672
 673                        /* copy previous polynom order to the next */
 674                        lmu[i + 1] = lmu[i];
 675                } else {
 676                        ro = 0;
 677                        largest = -1;
 678                        /* find largest delta with dmu != 0 */
 679                        for (j = 0; j < i; j++) {
 680                                if ((dmu[j]) && (delta[j] > largest)) {
 681                                        largest = delta[j];
 682                                        ro = j;
 683                                }
 684                        }
 685
 686                        /* compute difference */
 687                        diff = (mu[i] - mu[ro]);
 688
 689                        /* Compute degree of the new smu polynomial */
 690                        if ((lmu[i] >> 1) > ((lmu[ro] >> 1) + diff))
 691                                lmu[i + 1] = lmu[i];
 692                        else
 693                                lmu[i + 1] = ((lmu[ro] >> 1) + diff) * 2;
 694
 695                        /* Init smu[i+1] with 0 */
 696                        for (k = 0; k < num; k++)
 697                                smu[(i + 1) * num + k] = 0;
 698
 699                        /* Compute smu[i+1] */
 700                        for (k = 0; k <= lmu[ro] >> 1; k++) {
 701                                int16_t a, b, c;
 702
 703                                if (!(smu[ro * num + k] && dmu[i]))
 704                                        continue;
 705                                a = readw_relaxed(index_of + dmu[i]);
 706                                b = readw_relaxed(index_of + dmu[ro]);
 707                                c = readw_relaxed(index_of + smu[ro * num + k]);
 708                                tmp = a + (cw_len - b) + c;
 709                                a = readw_relaxed(alpha_to + tmp % cw_len);
 710                                smu[(i + 1) * num + (k + diff)] = a;
 711                        }
 712
 713                        for (k = 0; k <= lmu[i] >> 1; k++)
 714                                smu[(i + 1) * num + k] ^= smu[i * num + k];
 715                }
 716
 717                /* End Computing Sigma (Mu+1) and L(mu) */
 718                /* In either case compute delta */
 719                delta[i + 1] = (mu[i + 1] * 2 - lmu[i + 1]) >> 1;
 720
 721                /* Do not compute discrepancy for the last iteration */
 722                if (i >= cap)
 723                        continue;
 724
 725                for (k = 0; k <= (lmu[i + 1] >> 1); k++) {
 726                        tmp = 2 * (i - 1);
 727                        if (k == 0) {
 728                                dmu[i + 1] = si[tmp + 3];
 729                        } else if (smu[(i + 1) * num + k] && si[tmp + 3 - k]) {
 730                                int16_t a, b, c;
 731                                a = readw_relaxed(index_of +
 732                                                smu[(i + 1) * num + k]);
 733                                b = si[2 * (i - 1) + 3 - k];
 734                                c = readw_relaxed(index_of + b);
 735                                tmp = a + c;
 736                                tmp %= cw_len;
 737                                dmu[i + 1] = readw_relaxed(alpha_to + tmp) ^
 738                                        dmu[i + 1];
 739                        }
 740                }
 741        }
 742
 743        return;
 744}
 745
 746static int pmecc_err_location(struct mtd_info *mtd)
 747{
 748        struct nand_chip *nand_chip = mtd->priv;
 749        struct atmel_nand_host *host = nand_chip->priv;
 750        unsigned long end_time;
 751        const int cap = host->pmecc_corr_cap;
 752        const int num = 2 * cap + 1;
 753        int sector_size = host->pmecc_sector_size;
 754        int err_nbr = 0;        /* number of error */
 755        int roots_nbr;          /* number of roots */
 756        int i;
 757        uint32_t val;
 758        int16_t *smu = host->pmecc_smu;
 759
 760        pmerrloc_writel(host->pmerrloc_base, ELDIS, PMERRLOC_DISABLE);
 761
 762        for (i = 0; i <= host->pmecc_lmu[cap + 1] >> 1; i++) {
 763                pmerrloc_writel_sigma_relaxed(host->pmerrloc_base, i,
 764                                      smu[(cap + 1) * num + i]);
 765                err_nbr++;
 766        }
 767
 768        val = (err_nbr - 1) << 16;
 769        if (sector_size == 1024)
 770                val |= 1;
 771
 772        pmerrloc_writel(host->pmerrloc_base, ELCFG, val);
 773        pmerrloc_writel(host->pmerrloc_base, ELEN,
 774                        sector_size * 8 + host->pmecc_degree * cap);
 775
 776        end_time = jiffies + msecs_to_jiffies(PMECC_MAX_TIMEOUT_MS);
 777        while (!(pmerrloc_readl_relaxed(host->pmerrloc_base, ELISR)
 778                 & PMERRLOC_CALC_DONE)) {
 779                if (unlikely(time_after(jiffies, end_time))) {
 780                        dev_err(host->dev, "PMECC: Timeout to calculate error location.\n");
 781                        return -1;
 782                }
 783                cpu_relax();
 784        }
 785
 786        roots_nbr = (pmerrloc_readl_relaxed(host->pmerrloc_base, ELISR)
 787                & PMERRLOC_ERR_NUM_MASK) >> 8;
 788        /* Number of roots == degree of smu hence <= cap */
 789        if (roots_nbr == host->pmecc_lmu[cap + 1] >> 1)
 790                return err_nbr - 1;
 791
 792        /* Number of roots does not match the degree of smu
 793         * unable to correct error */
 794        return -1;
 795}
 796
 797static void pmecc_correct_data(struct mtd_info *mtd, uint8_t *buf, uint8_t *ecc,
 798                int sector_num, int extra_bytes, int err_nbr)
 799{
 800        struct nand_chip *nand_chip = mtd->priv;
 801        struct atmel_nand_host *host = nand_chip->priv;
 802        int i = 0;
 803        int byte_pos, bit_pos, sector_size, pos;
 804        uint32_t tmp;
 805        uint8_t err_byte;
 806
 807        sector_size = host->pmecc_sector_size;
 808
 809        while (err_nbr) {
 810                tmp = pmerrloc_readl_el_relaxed(host->pmerrloc_base, i) - 1;
 811                byte_pos = tmp / 8;
 812                bit_pos  = tmp % 8;
 813
 814                if (byte_pos >= (sector_size + extra_bytes))
 815                        BUG();  /* should never happen */
 816
 817                if (byte_pos < sector_size) {
 818                        err_byte = *(buf + byte_pos);
 819                        *(buf + byte_pos) ^= (1 << bit_pos);
 820
 821                        pos = sector_num * host->pmecc_sector_size + byte_pos;
 822                        dev_info(host->dev, "Bit flip in data area, byte_pos: %d, bit_pos: %d, 0x%02x -> 0x%02x\n",
 823                                pos, bit_pos, err_byte, *(buf + byte_pos));
 824                } else {
 825                        /* Bit flip in OOB area */
 826                        tmp = sector_num * nand_chip->ecc.bytes
 827                                        + (byte_pos - sector_size);
 828                        err_byte = ecc[tmp];
 829                        ecc[tmp] ^= (1 << bit_pos);
 830
 831                        pos = tmp + nand_chip->ecc.layout->eccpos[0];
 832                        dev_info(host->dev, "Bit flip in OOB, oob_byte_pos: %d, bit_pos: %d, 0x%02x -> 0x%02x\n",
 833                                pos, bit_pos, err_byte, ecc[tmp]);
 834                }
 835
 836                i++;
 837                err_nbr--;
 838        }
 839
 840        return;
 841}
 842
 843static int pmecc_correction(struct mtd_info *mtd, u32 pmecc_stat, uint8_t *buf,
 844        u8 *ecc)
 845{
 846        struct nand_chip *nand_chip = mtd->priv;
 847        struct atmel_nand_host *host = nand_chip->priv;
 848        int i, err_nbr;
 849        uint8_t *buf_pos;
 850        int total_err = 0;
 851
 852        for (i = 0; i < nand_chip->ecc.total; i++)
 853                if (ecc[i] != 0xff)
 854                        goto normal_check;
 855        /* Erased page, return OK */
 856        return 0;
 857
 858normal_check:
 859        for (i = 0; i < nand_chip->ecc.steps; i++) {
 860                err_nbr = 0;
 861                if (pmecc_stat & 0x1) {
 862                        buf_pos = buf + i * host->pmecc_sector_size;
 863
 864                        pmecc_gen_syndrome(mtd, i);
 865                        pmecc_substitute(mtd);
 866                        pmecc_get_sigma(mtd);
 867
 868                        err_nbr = pmecc_err_location(mtd);
 869                        if (err_nbr == -1) {
 870                                dev_err(host->dev, "PMECC: Too many errors\n");
 871                                mtd->ecc_stats.failed++;
 872                                return -EIO;
 873                        } else {
 874                                pmecc_correct_data(mtd, buf_pos, ecc, i,
 875                                        nand_chip->ecc.bytes, err_nbr);
 876                                mtd->ecc_stats.corrected += err_nbr;
 877                                total_err += err_nbr;
 878                        }
 879                }
 880                pmecc_stat >>= 1;
 881        }
 882
 883        return total_err;
 884}
 885
 886static void pmecc_enable(struct atmel_nand_host *host, int ecc_op)
 887{
 888        u32 val;
 889
 890        if (ecc_op != NAND_ECC_READ && ecc_op != NAND_ECC_WRITE) {
 891                dev_err(host->dev, "atmel_nand: wrong pmecc operation type!");
 892                return;
 893        }
 894
 895        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_RST);
 896        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
 897        val = pmecc_readl_relaxed(host->ecc, CFG);
 898
 899        if (ecc_op == NAND_ECC_READ)
 900                pmecc_writel(host->ecc, CFG, (val & ~PMECC_CFG_WRITE_OP)
 901                        | PMECC_CFG_AUTO_ENABLE);
 902        else
 903                pmecc_writel(host->ecc, CFG, (val | PMECC_CFG_WRITE_OP)
 904                        & ~PMECC_CFG_AUTO_ENABLE);
 905
 906        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_ENABLE);
 907        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DATA);
 908}
 909
 910static int atmel_nand_pmecc_read_page(struct mtd_info *mtd,
 911        struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
 912{
 913        struct atmel_nand_host *host = chip->priv;
 914        int eccsize = chip->ecc.size * chip->ecc.steps;
 915        uint8_t *oob = chip->oob_poi;
 916        uint32_t *eccpos = chip->ecc.layout->eccpos;
 917        uint32_t stat;
 918        unsigned long end_time;
 919        int bitflips = 0;
 920
 921        if (!host->nfc || !host->nfc->use_nfc_sram)
 922                pmecc_enable(host, NAND_ECC_READ);
 923
 924        chip->read_buf(mtd, buf, eccsize);
 925        chip->read_buf(mtd, oob, mtd->oobsize);
 926
 927        end_time = jiffies + msecs_to_jiffies(PMECC_MAX_TIMEOUT_MS);
 928        while ((pmecc_readl_relaxed(host->ecc, SR) & PMECC_SR_BUSY)) {
 929                if (unlikely(time_after(jiffies, end_time))) {
 930                        dev_err(host->dev, "PMECC: Timeout to get error status.\n");
 931                        return -EIO;
 932                }
 933                cpu_relax();
 934        }
 935
 936        stat = pmecc_readl_relaxed(host->ecc, ISR);
 937        if (stat != 0) {
 938                bitflips = pmecc_correction(mtd, stat, buf, &oob[eccpos[0]]);
 939                if (bitflips < 0)
 940                        /* uncorrectable errors */
 941                        return 0;
 942        }
 943
 944        return bitflips;
 945}
 946
 947static int atmel_nand_pmecc_write_page(struct mtd_info *mtd,
 948                struct nand_chip *chip, const uint8_t *buf, int oob_required)
 949{
 950        struct atmel_nand_host *host = chip->priv;
 951        uint32_t *eccpos = chip->ecc.layout->eccpos;
 952        int i, j;
 953        unsigned long end_time;
 954
 955        if (!host->nfc || !host->nfc->write_by_sram) {
 956                pmecc_enable(host, NAND_ECC_WRITE);
 957                chip->write_buf(mtd, (u8 *)buf, mtd->writesize);
 958        }
 959
 960        end_time = jiffies + msecs_to_jiffies(PMECC_MAX_TIMEOUT_MS);
 961        while ((pmecc_readl_relaxed(host->ecc, SR) & PMECC_SR_BUSY)) {
 962                if (unlikely(time_after(jiffies, end_time))) {
 963                        dev_err(host->dev, "PMECC: Timeout to get ECC value.\n");
 964                        return -EIO;
 965                }
 966                cpu_relax();
 967        }
 968
 969        for (i = 0; i < chip->ecc.steps; i++) {
 970                for (j = 0; j < chip->ecc.bytes; j++) {
 971                        int pos;
 972
 973                        pos = i * chip->ecc.bytes + j;
 974                        chip->oob_poi[eccpos[pos]] =
 975                                pmecc_readb_ecc_relaxed(host->ecc, i, j);
 976                }
 977        }
 978        chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
 979
 980        return 0;
 981}
 982
 983static void atmel_pmecc_core_init(struct mtd_info *mtd)
 984{
 985        struct nand_chip *nand_chip = mtd->priv;
 986        struct atmel_nand_host *host = nand_chip->priv;
 987        uint32_t val = 0;
 988        struct nand_ecclayout *ecc_layout;
 989
 990        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_RST);
 991        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
 992
 993        switch (host->pmecc_corr_cap) {
 994        case 2:
 995                val = PMECC_CFG_BCH_ERR2;
 996                break;
 997        case 4:
 998                val = PMECC_CFG_BCH_ERR4;
 999                break;
1000        case 8:
1001                val = PMECC_CFG_BCH_ERR8;
1002                break;
1003        case 12:
1004                val = PMECC_CFG_BCH_ERR12;
1005                break;
1006        case 24:
1007                val = PMECC_CFG_BCH_ERR24;
1008                break;
1009        }
1010
1011        if (host->pmecc_sector_size == 512)
1012                val |= PMECC_CFG_SECTOR512;
1013        else if (host->pmecc_sector_size == 1024)
1014                val |= PMECC_CFG_SECTOR1024;
1015
1016        switch (nand_chip->ecc.steps) {
1017        case 1:
1018                val |= PMECC_CFG_PAGE_1SECTOR;
1019                break;
1020        case 2:
1021                val |= PMECC_CFG_PAGE_2SECTORS;
1022                break;
1023        case 4:
1024                val |= PMECC_CFG_PAGE_4SECTORS;
1025                break;
1026        case 8:
1027                val |= PMECC_CFG_PAGE_8SECTORS;
1028                break;
1029        }
1030
1031        val |= (PMECC_CFG_READ_OP | PMECC_CFG_SPARE_DISABLE
1032                | PMECC_CFG_AUTO_DISABLE);
1033        pmecc_writel(host->ecc, CFG, val);
1034
1035        ecc_layout = nand_chip->ecc.layout;
1036        pmecc_writel(host->ecc, SAREA, mtd->oobsize - 1);
1037        pmecc_writel(host->ecc, SADDR, ecc_layout->eccpos[0]);
1038        pmecc_writel(host->ecc, EADDR,
1039                        ecc_layout->eccpos[ecc_layout->eccbytes - 1]);
1040        /* See datasheet about PMECC Clock Control Register */
1041        pmecc_writel(host->ecc, CLK, 2);
1042        pmecc_writel(host->ecc, IDR, 0xff);
1043        pmecc_writel(host->ecc, CTRL, PMECC_CTRL_ENABLE);
1044}
1045
1046/*
1047 * Get minimum ecc requirements from NAND.
1048 * If pmecc-cap, pmecc-sector-size in DTS are not specified, this function
1049 * will set them according to minimum ecc requirement. Otherwise, use the
1050 * value in DTS file.
1051 * return 0 if success. otherwise return error code.
1052 */
1053static int pmecc_choose_ecc(struct atmel_nand_host *host,
1054                int *cap, int *sector_size)
1055{
1056        /* Get minimum ECC requirements */
1057        if (host->nand_chip.ecc_strength_ds) {
1058                *cap = host->nand_chip.ecc_strength_ds;
1059                *sector_size = host->nand_chip.ecc_step_ds;
1060                dev_info(host->dev, "minimum ECC: %d bits in %d bytes\n",
1061                                *cap, *sector_size);
1062        } else {
1063                *cap = 2;
1064                *sector_size = 512;
1065                dev_info(host->dev, "can't detect min. ECC, assume 2 bits in 512 bytes\n");
1066        }
1067
1068        /* If device tree doesn't specify, use NAND's minimum ECC parameters */
1069        if (host->pmecc_corr_cap == 0) {
1070                /* use the most fitable ecc bits (the near bigger one ) */
1071                if (*cap <= 2)
1072                        host->pmecc_corr_cap = 2;
1073                else if (*cap <= 4)
1074                        host->pmecc_corr_cap = 4;
1075                else if (*cap <= 8)
1076                        host->pmecc_corr_cap = 8;
1077                else if (*cap <= 12)
1078                        host->pmecc_corr_cap = 12;
1079                else if (*cap <= 24)
1080                        host->pmecc_corr_cap = 24;
1081                else
1082                        return -EINVAL;
1083        }
1084        if (host->pmecc_sector_size == 0) {
1085                /* use the most fitable sector size (the near smaller one ) */
1086                if (*sector_size >= 1024)
1087                        host->pmecc_sector_size = 1024;
1088                else if (*sector_size >= 512)
1089                        host->pmecc_sector_size = 512;
1090                else
1091                        return -EINVAL;
1092        }
1093        return 0;
1094}
1095
1096static inline int deg(unsigned int poly)
1097{
1098        /* polynomial degree is the most-significant bit index */
1099        return fls(poly) - 1;
1100}
1101
1102static int build_gf_tables(int mm, unsigned int poly,
1103                int16_t *index_of, int16_t *alpha_to)
1104{
1105        unsigned int i, x = 1;
1106        const unsigned int k = 1 << deg(poly);
1107        unsigned int nn = (1 << mm) - 1;
1108
1109        /* primitive polynomial must be of degree m */
1110        if (k != (1u << mm))
1111                return -EINVAL;
1112
1113        for (i = 0; i < nn; i++) {
1114                alpha_to[i] = x;
1115                index_of[x] = i;
1116                if (i && (x == 1))
1117                        /* polynomial is not primitive (a^i=1 with 0<i<2^m-1) */
1118                        return -EINVAL;
1119                x <<= 1;
1120                if (x & k)
1121                        x ^= poly;
1122        }
1123        alpha_to[nn] = 1;
1124        index_of[0] = 0;
1125
1126        return 0;
1127}
1128
1129static uint16_t *create_lookup_table(struct device *dev, int sector_size)
1130{
1131        int degree = (sector_size == 512) ?
1132                        PMECC_GF_DIMENSION_13 :
1133                        PMECC_GF_DIMENSION_14;
1134        unsigned int poly = (sector_size == 512) ?
1135                        PMECC_GF_13_PRIMITIVE_POLY :
1136                        PMECC_GF_14_PRIMITIVE_POLY;
1137        int table_size = (sector_size == 512) ?
1138                        PMECC_LOOKUP_TABLE_SIZE_512 :
1139                        PMECC_LOOKUP_TABLE_SIZE_1024;
1140
1141        int16_t *addr = devm_kzalloc(dev, 2 * table_size * sizeof(uint16_t),
1142                        GFP_KERNEL);
1143        if (addr && build_gf_tables(degree, poly, addr, addr + table_size))
1144                return NULL;
1145
1146        return addr;
1147}
1148
1149static int atmel_pmecc_nand_init_params(struct platform_device *pdev,
1150                                         struct atmel_nand_host *host)
1151{
1152        struct mtd_info *mtd = &host->mtd;
1153        struct nand_chip *nand_chip = &host->nand_chip;
1154        struct resource *regs, *regs_pmerr, *regs_rom;
1155        uint16_t *galois_table;
1156        int cap, sector_size, err_no;
1157
1158        err_no = pmecc_choose_ecc(host, &cap, &sector_size);
1159        if (err_no) {
1160                dev_err(host->dev, "The NAND flash's ECC requirement are not support!");
1161                return err_no;
1162        }
1163
1164        if (cap > host->pmecc_corr_cap ||
1165                        sector_size != host->pmecc_sector_size)
1166                dev_info(host->dev, "WARNING: Be Caution! Using different PMECC parameters from Nand ONFI ECC reqirement.\n");
1167
1168        cap = host->pmecc_corr_cap;
1169        sector_size = host->pmecc_sector_size;
1170        host->pmecc_lookup_table_offset = (sector_size == 512) ?
1171                        host->pmecc_lookup_table_offset_512 :
1172                        host->pmecc_lookup_table_offset_1024;
1173
1174        dev_info(host->dev, "Initialize PMECC params, cap: %d, sector: %d\n",
1175                 cap, sector_size);
1176
1177        regs = platform_get_resource(pdev, IORESOURCE_MEM, 1);
1178        if (!regs) {
1179                dev_warn(host->dev,
1180                        "Can't get I/O resource regs for PMECC controller, rolling back on software ECC\n");
1181                nand_chip->ecc.mode = NAND_ECC_SOFT;
1182                return 0;
1183        }
1184
1185        host->ecc = devm_ioremap_resource(&pdev->dev, regs);
1186        if (IS_ERR(host->ecc)) {
1187                err_no = PTR_ERR(host->ecc);
1188                goto err;
1189        }
1190
1191        regs_pmerr = platform_get_resource(pdev, IORESOURCE_MEM, 2);
1192        host->pmerrloc_base = devm_ioremap_resource(&pdev->dev, regs_pmerr);
1193        if (IS_ERR(host->pmerrloc_base)) {
1194                err_no = PTR_ERR(host->pmerrloc_base);
1195                goto err;
1196        }
1197
1198        regs_rom = platform_get_resource(pdev, IORESOURCE_MEM, 3);
1199        host->pmecc_rom_base = devm_ioremap_resource(&pdev->dev, regs_rom);
1200        if (IS_ERR(host->pmecc_rom_base)) {
1201                if (!host->has_no_lookup_table)
1202                        /* Don't display the information again */
1203                        dev_err(host->dev, "Can not get I/O resource for ROM, will build a lookup table in runtime!\n");
1204
1205                host->has_no_lookup_table = true;
1206        }
1207
1208        if (host->has_no_lookup_table) {
1209                /* Build the look-up table in runtime */
1210                galois_table = create_lookup_table(host->dev, sector_size);
1211                if (!galois_table) {
1212                        dev_err(host->dev, "Failed to build a lookup table in runtime!\n");
1213                        err_no = -EINVAL;
1214                        goto err;
1215                }
1216
1217                host->pmecc_rom_base = (void __iomem *)galois_table;
1218                host->pmecc_lookup_table_offset = 0;
1219        }
1220
1221        nand_chip->ecc.size = sector_size;
1222
1223        /* set ECC page size and oob layout */
1224        switch (mtd->writesize) {
1225        case 512:
1226        case 1024:
1227        case 2048:
1228        case 4096:
1229        case 8192:
1230                if (sector_size > mtd->writesize) {
1231                        dev_err(host->dev, "pmecc sector size is bigger than the page size!\n");
1232                        err_no = -EINVAL;
1233                        goto err;
1234                }
1235
1236                host->pmecc_degree = (sector_size == 512) ?
1237                        PMECC_GF_DIMENSION_13 : PMECC_GF_DIMENSION_14;
1238                host->pmecc_cw_len = (1 << host->pmecc_degree) - 1;
1239                host->pmecc_alpha_to = pmecc_get_alpha_to(host);
1240                host->pmecc_index_of = host->pmecc_rom_base +
1241                        host->pmecc_lookup_table_offset;
1242
1243                nand_chip->ecc.strength = cap;
1244                nand_chip->ecc.bytes = pmecc_get_ecc_bytes(cap, sector_size);
1245                nand_chip->ecc.steps = mtd->writesize / sector_size;
1246                nand_chip->ecc.total = nand_chip->ecc.bytes *
1247                        nand_chip->ecc.steps;
1248                if (nand_chip->ecc.total > mtd->oobsize - 2) {
1249                        dev_err(host->dev, "No room for ECC bytes\n");
1250                        err_no = -EINVAL;
1251                        goto err;
1252                }
1253                pmecc_config_ecc_layout(&atmel_pmecc_oobinfo,
1254                                        mtd->oobsize,
1255                                        nand_chip->ecc.total);
1256
1257                nand_chip->ecc.layout = &atmel_pmecc_oobinfo;
1258                break;
1259        default:
1260                dev_warn(host->dev,
1261                        "Unsupported page size for PMECC, use Software ECC\n");
1262                /* page size not handled by HW ECC */
1263                /* switching back to soft ECC */
1264                nand_chip->ecc.mode = NAND_ECC_SOFT;
1265                return 0;
1266        }
1267
1268        /* Allocate data for PMECC computation */
1269        err_no = pmecc_data_alloc(host);
1270        if (err_no) {
1271                dev_err(host->dev,
1272                                "Cannot allocate memory for PMECC computation!\n");
1273                goto err;
1274        }
1275
1276        nand_chip->options |= NAND_NO_SUBPAGE_WRITE;
1277        nand_chip->ecc.read_page = atmel_nand_pmecc_read_page;
1278        nand_chip->ecc.write_page = atmel_nand_pmecc_write_page;
1279
1280        atmel_pmecc_core_init(mtd);
1281
1282        return 0;
1283
1284err:
1285        return err_no;
1286}
1287
1288/*
1289 * Calculate HW ECC
1290 *
1291 * function called after a write
1292 *
1293 * mtd:        MTD block structure
1294 * dat:        raw data (unused)
1295 * ecc_code:   buffer for ECC
1296 */
1297static int atmel_nand_calculate(struct mtd_info *mtd,
1298                const u_char *dat, unsigned char *ecc_code)
1299{
1300        struct nand_chip *nand_chip = mtd->priv;
1301        struct atmel_nand_host *host = nand_chip->priv;
1302        unsigned int ecc_value;
1303
1304        /* get the first 2 ECC bytes */
1305        ecc_value = ecc_readl(host->ecc, PR);
1306
1307        ecc_code[0] = ecc_value & 0xFF;
1308        ecc_code[1] = (ecc_value >> 8) & 0xFF;
1309
1310        /* get the last 2 ECC bytes */
1311        ecc_value = ecc_readl(host->ecc, NPR) & ATMEL_ECC_NPARITY;
1312
1313        ecc_code[2] = ecc_value & 0xFF;
1314        ecc_code[3] = (ecc_value >> 8) & 0xFF;
1315
1316        return 0;
1317}
1318
1319/*
1320 * HW ECC read page function
1321 *
1322 * mtd:        mtd info structure
1323 * chip:       nand chip info structure
1324 * buf:        buffer to store read data
1325 * oob_required:    caller expects OOB data read to chip->oob_poi
1326 */
1327static int atmel_nand_read_page(struct mtd_info *mtd, struct nand_chip *chip,
1328                                uint8_t *buf, int oob_required, int page)
1329{
1330        int eccsize = chip->ecc.size;
1331        int eccbytes = chip->ecc.bytes;
1332        uint32_t *eccpos = chip->ecc.layout->eccpos;
1333        uint8_t *p = buf;
1334        uint8_t *oob = chip->oob_poi;
1335        uint8_t *ecc_pos;
1336        int stat;
1337        unsigned int max_bitflips = 0;
1338
1339        /*
1340         * Errata: ALE is incorrectly wired up to the ECC controller
1341         * on the AP7000, so it will include the address cycles in the
1342         * ECC calculation.
1343         *
1344         * Workaround: Reset the parity registers before reading the
1345         * actual data.
1346         */
1347        struct atmel_nand_host *host = chip->priv;
1348        if (host->board.need_reset_workaround)
1349                ecc_writel(host->ecc, CR, ATMEL_ECC_RST);
1350
1351        /* read the page */
1352        chip->read_buf(mtd, p, eccsize);
1353
1354        /* move to ECC position if needed */
1355        if (eccpos[0] != 0) {
1356                /* This only works on large pages
1357                 * because the ECC controller waits for
1358                 * NAND_CMD_RNDOUTSTART after the
1359                 * NAND_CMD_RNDOUT.
1360                 * anyway, for small pages, the eccpos[0] == 0
1361                 */
1362                chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1363                                mtd->writesize + eccpos[0], -1);
1364        }
1365
1366        /* the ECC controller needs to read the ECC just after the data */
1367        ecc_pos = oob + eccpos[0];
1368        chip->read_buf(mtd, ecc_pos, eccbytes);
1369
1370        /* check if there's an error */
1371        stat = chip->ecc.correct(mtd, p, oob, NULL);
1372
1373        if (stat < 0) {
1374                mtd->ecc_stats.failed++;
1375        } else {
1376                mtd->ecc_stats.corrected += stat;
1377                max_bitflips = max_t(unsigned int, max_bitflips, stat);
1378        }
1379
1380        /* get back to oob start (end of page) */
1381        chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1382
1383        /* read the oob */
1384        chip->read_buf(mtd, oob, mtd->oobsize);
1385
1386        return max_bitflips;
1387}
1388
1389/*
1390 * HW ECC Correction
1391 *
1392 * function called after a read
1393 *
1394 * mtd:        MTD block structure
1395 * dat:        raw data read from the chip
1396 * read_ecc:   ECC from the chip (unused)
1397 * isnull:     unused
1398 *
1399 * Detect and correct a 1 bit error for a page
1400 */
1401static int atmel_nand_correct(struct mtd_info *mtd, u_char *dat,
1402                u_char *read_ecc, u_char *isnull)
1403{
1404        struct nand_chip *nand_chip = mtd->priv;
1405        struct atmel_nand_host *host = nand_chip->priv;
1406        unsigned int ecc_status;
1407        unsigned int ecc_word, ecc_bit;
1408
1409        /* get the status from the Status Register */
1410        ecc_status = ecc_readl(host->ecc, SR);
1411
1412        /* if there's no error */
1413        if (likely(!(ecc_status & ATMEL_ECC_RECERR)))
1414                return 0;
1415
1416        /* get error bit offset (4 bits) */
1417        ecc_bit = ecc_readl(host->ecc, PR) & ATMEL_ECC_BITADDR;
1418        /* get word address (12 bits) */
1419        ecc_word = ecc_readl(host->ecc, PR) & ATMEL_ECC_WORDADDR;
1420        ecc_word >>= 4;
1421
1422        /* if there are multiple errors */
1423        if (ecc_status & ATMEL_ECC_MULERR) {
1424                /* check if it is a freshly erased block
1425                 * (filled with 0xff) */
1426                if ((ecc_bit == ATMEL_ECC_BITADDR)
1427                                && (ecc_word == (ATMEL_ECC_WORDADDR >> 4))) {
1428                        /* the block has just been erased, return OK */
1429                        return 0;
1430                }
1431                /* it doesn't seems to be a freshly
1432                 * erased block.
1433                 * We can't correct so many errors */
1434                dev_dbg(host->dev, "atmel_nand : multiple errors detected."
1435                                " Unable to correct.\n");
1436                return -EIO;
1437        }
1438
1439        /* if there's a single bit error : we can correct it */
1440        if (ecc_status & ATMEL_ECC_ECCERR) {
1441                /* there's nothing much to do here.
1442                 * the bit error is on the ECC itself.
1443                 */
1444                dev_dbg(host->dev, "atmel_nand : one bit error on ECC code."
1445                                " Nothing to correct\n");
1446                return 0;
1447        }
1448
1449        dev_dbg(host->dev, "atmel_nand : one bit error on data."
1450                        " (word offset in the page :"
1451                        " 0x%x bit offset : 0x%x)\n",
1452                        ecc_word, ecc_bit);
1453        /* correct the error */
1454        if (nand_chip->options & NAND_BUSWIDTH_16) {
1455                /* 16 bits words */
1456                ((unsigned short *) dat)[ecc_word] ^= (1 << ecc_bit);
1457        } else {
1458                /* 8 bits words */
1459                dat[ecc_word] ^= (1 << ecc_bit);
1460        }
1461        dev_dbg(host->dev, "atmel_nand : error corrected\n");
1462        return 1;
1463}
1464
1465/*
1466 * Enable HW ECC : unused on most chips
1467 */
1468static void atmel_nand_hwctl(struct mtd_info *mtd, int mode)
1469{
1470        struct nand_chip *nand_chip = mtd->priv;
1471        struct atmel_nand_host *host = nand_chip->priv;
1472
1473        if (host->board.need_reset_workaround)
1474                ecc_writel(host->ecc, CR, ATMEL_ECC_RST);
1475}
1476
1477static int atmel_of_init_port(struct atmel_nand_host *host,
1478                              struct device_node *np)
1479{
1480        u32 val;
1481        u32 offset[2];
1482        int ecc_mode;
1483        struct atmel_nand_data *board = &host->board;
1484        enum of_gpio_flags flags = 0;
1485
1486        if (of_property_read_u32(np, "atmel,nand-addr-offset", &val) == 0) {
1487                if (val >= 32) {
1488                        dev_err(host->dev, "invalid addr-offset %u\n", val);
1489                        return -EINVAL;
1490                }
1491                board->ale = val;
1492        }
1493
1494        if (of_property_read_u32(np, "atmel,nand-cmd-offset", &val) == 0) {
1495                if (val >= 32) {
1496                        dev_err(host->dev, "invalid cmd-offset %u\n", val);
1497                        return -EINVAL;
1498                }
1499                board->cle = val;
1500        }
1501
1502        ecc_mode = of_get_nand_ecc_mode(np);
1503
1504        board->ecc_mode = ecc_mode < 0 ? NAND_ECC_SOFT : ecc_mode;
1505
1506        board->on_flash_bbt = of_get_nand_on_flash_bbt(np);
1507
1508        board->has_dma = of_property_read_bool(np, "atmel,nand-has-dma");
1509
1510        if (of_get_nand_bus_width(np) == 16)
1511                board->bus_width_16 = 1;
1512
1513        board->rdy_pin = of_get_gpio_flags(np, 0, &flags);
1514        board->rdy_pin_active_low = (flags == OF_GPIO_ACTIVE_LOW);
1515
1516        board->enable_pin = of_get_gpio(np, 1);
1517        board->det_pin = of_get_gpio(np, 2);
1518
1519        host->has_pmecc = of_property_read_bool(np, "atmel,has-pmecc");
1520
1521        /* load the nfc driver if there is */
1522        of_platform_populate(np, NULL, NULL, host->dev);
1523
1524        if (!(board->ecc_mode == NAND_ECC_HW) || !host->has_pmecc)
1525                return 0;       /* Not using PMECC */
1526
1527        /* use PMECC, get correction capability, sector size and lookup
1528         * table offset.
1529         * If correction bits and sector size are not specified, then find
1530         * them from NAND ONFI parameters.
1531         */
1532        if (of_property_read_u32(np, "atmel,pmecc-cap", &val) == 0) {
1533                if ((val != 2) && (val != 4) && (val != 8) && (val != 12) &&
1534                                (val != 24)) {
1535                        dev_err(host->dev,
1536                                "Unsupported PMECC correction capability: %d; should be 2, 4, 8, 12 or 24\n",
1537                                val);
1538                        return -EINVAL;
1539                }
1540                host->pmecc_corr_cap = (u8)val;
1541        }
1542
1543        if (of_property_read_u32(np, "atmel,pmecc-sector-size", &val) == 0) {
1544                if ((val != 512) && (val != 1024)) {
1545                        dev_err(host->dev,
1546                                "Unsupported PMECC sector size: %d; should be 512 or 1024 bytes\n",
1547                                val);
1548                        return -EINVAL;
1549                }
1550                host->pmecc_sector_size = (u16)val;
1551        }
1552
1553        if (of_property_read_u32_array(np, "atmel,pmecc-lookup-table-offset",
1554                        offset, 2) != 0) {
1555                dev_err(host->dev, "Cannot get PMECC lookup table offset, will build a lookup table in runtime.\n");
1556                host->has_no_lookup_table = true;
1557                /* Will build a lookup table and initialize the offset later */
1558                return 0;
1559        }
1560        if (!offset[0] && !offset[1]) {
1561                dev_err(host->dev, "Invalid PMECC lookup table offset\n");
1562                return -EINVAL;
1563        }
1564        host->pmecc_lookup_table_offset_512 = offset[0];
1565        host->pmecc_lookup_table_offset_1024 = offset[1];
1566
1567        return 0;
1568}
1569
1570static int atmel_hw_nand_init_params(struct platform_device *pdev,
1571                                         struct atmel_nand_host *host)
1572{
1573        struct mtd_info *mtd = &host->mtd;
1574        struct nand_chip *nand_chip = &host->nand_chip;
1575        struct resource         *regs;
1576
1577        regs = platform_get_resource(pdev, IORESOURCE_MEM, 1);
1578        if (!regs) {
1579                dev_err(host->dev,
1580                        "Can't get I/O resource regs, use software ECC\n");
1581                nand_chip->ecc.mode = NAND_ECC_SOFT;
1582                return 0;
1583        }
1584
1585        host->ecc = devm_ioremap_resource(&pdev->dev, regs);
1586        if (IS_ERR(host->ecc))
1587                return PTR_ERR(host->ecc);
1588
1589        /* ECC is calculated for the whole page (1 step) */
1590        nand_chip->ecc.size = mtd->writesize;
1591
1592        /* set ECC page size and oob layout */
1593        switch (mtd->writesize) {
1594        case 512:
1595                nand_chip->ecc.layout = &atmel_oobinfo_small;
1596                ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_528);
1597                break;
1598        case 1024:
1599                nand_chip->ecc.layout = &atmel_oobinfo_large;
1600                ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_1056);
1601                break;
1602        case 2048:
1603                nand_chip->ecc.layout = &atmel_oobinfo_large;
1604                ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_2112);
1605                break;
1606        case 4096:
1607                nand_chip->ecc.layout = &atmel_oobinfo_large;
1608                ecc_writel(host->ecc, MR, ATMEL_ECC_PAGESIZE_4224);
1609                break;
1610        default:
1611                /* page size not handled by HW ECC */
1612                /* switching back to soft ECC */
1613                nand_chip->ecc.mode = NAND_ECC_SOFT;
1614                return 0;
1615        }
1616
1617        /* set up for HW ECC */
1618        nand_chip->ecc.calculate = atmel_nand_calculate;
1619        nand_chip->ecc.correct = atmel_nand_correct;
1620        nand_chip->ecc.hwctl = atmel_nand_hwctl;
1621        nand_chip->ecc.read_page = atmel_nand_read_page;
1622        nand_chip->ecc.bytes = 4;
1623        nand_chip->ecc.strength = 1;
1624
1625        return 0;
1626}
1627
1628static inline u32 nfc_read_status(struct atmel_nand_host *host)
1629{
1630        u32 err_flags = NFC_SR_DTOE | NFC_SR_UNDEF | NFC_SR_AWB | NFC_SR_ASE;
1631        u32 nfc_status = nfc_readl(host->nfc->hsmc_regs, SR);
1632
1633        if (unlikely(nfc_status & err_flags)) {
1634                if (nfc_status & NFC_SR_DTOE)
1635                        dev_err(host->dev, "NFC: Waiting Nand R/B Timeout Error\n");
1636                else if (nfc_status & NFC_SR_UNDEF)
1637                        dev_err(host->dev, "NFC: Access Undefined Area Error\n");
1638                else if (nfc_status & NFC_SR_AWB)
1639                        dev_err(host->dev, "NFC: Access memory While NFC is busy\n");
1640                else if (nfc_status & NFC_SR_ASE)
1641                        dev_err(host->dev, "NFC: Access memory Size Error\n");
1642        }
1643
1644        return nfc_status;
1645}
1646
1647/* SMC interrupt service routine */
1648static irqreturn_t hsmc_interrupt(int irq, void *dev_id)
1649{
1650        struct atmel_nand_host *host = dev_id;
1651        u32 status, mask, pending;
1652        irqreturn_t ret = IRQ_NONE;
1653
1654        status = nfc_read_status(host);
1655        mask = nfc_readl(host->nfc->hsmc_regs, IMR);
1656        pending = status & mask;
1657
1658        if (pending & NFC_SR_XFR_DONE) {
1659                complete(&host->nfc->comp_xfer_done);
1660                nfc_writel(host->nfc->hsmc_regs, IDR, NFC_SR_XFR_DONE);
1661                ret = IRQ_HANDLED;
1662        }
1663        if (pending & NFC_SR_RB_EDGE) {
1664                complete(&host->nfc->comp_ready);
1665                nfc_writel(host->nfc->hsmc_regs, IDR, NFC_SR_RB_EDGE);
1666                ret = IRQ_HANDLED;
1667        }
1668        if (pending & NFC_SR_CMD_DONE) {
1669                complete(&host->nfc->comp_cmd_done);
1670                nfc_writel(host->nfc->hsmc_regs, IDR, NFC_SR_CMD_DONE);
1671                ret = IRQ_HANDLED;
1672        }
1673
1674        return ret;
1675}
1676
1677/* NFC(Nand Flash Controller) related functions */
1678static void nfc_prepare_interrupt(struct atmel_nand_host *host, u32 flag)
1679{
1680        if (flag & NFC_SR_XFR_DONE)
1681                init_completion(&host->nfc->comp_xfer_done);
1682
1683        if (flag & NFC_SR_RB_EDGE)
1684                init_completion(&host->nfc->comp_ready);
1685
1686        if (flag & NFC_SR_CMD_DONE)
1687                init_completion(&host->nfc->comp_cmd_done);
1688
1689        /* Enable interrupt that need to wait for */
1690        nfc_writel(host->nfc->hsmc_regs, IER, flag);
1691}
1692
1693static int nfc_wait_interrupt(struct atmel_nand_host *host, u32 flag)
1694{
1695        int i, index = 0;
1696        struct completion *comp[3];     /* Support 3 interrupt completion */
1697
1698        if (flag & NFC_SR_XFR_DONE)
1699                comp[index++] = &host->nfc->comp_xfer_done;
1700
1701        if (flag & NFC_SR_RB_EDGE)
1702                comp[index++] = &host->nfc->comp_ready;
1703
1704        if (flag & NFC_SR_CMD_DONE)
1705                comp[index++] = &host->nfc->comp_cmd_done;
1706
1707        if (index == 0) {
1708                dev_err(host->dev, "Unkown interrupt flag: 0x%08x\n", flag);
1709                return -EINVAL;
1710        }
1711
1712        for (i = 0; i < index; i++) {
1713                if (wait_for_completion_timeout(comp[i],
1714                                msecs_to_jiffies(NFC_TIME_OUT_MS)))
1715                        continue;       /* wait for next completion */
1716                else
1717                        goto err_timeout;
1718        }
1719
1720        return 0;
1721
1722err_timeout:
1723        dev_err(host->dev, "Time out to wait for interrupt: 0x%08x\n", flag);
1724        /* Disable the interrupt as it is not handled by interrupt handler */
1725        nfc_writel(host->nfc->hsmc_regs, IDR, flag);
1726        return -ETIMEDOUT;
1727}
1728
1729static int nfc_send_command(struct atmel_nand_host *host,
1730        unsigned int cmd, unsigned int addr, unsigned char cycle0)
1731{
1732        unsigned long timeout;
1733        u32 flag = NFC_SR_CMD_DONE;
1734        flag |= cmd & NFCADDR_CMD_DATAEN ? NFC_SR_XFR_DONE : 0;
1735
1736        dev_dbg(host->dev,
1737                "nfc_cmd: 0x%08x, addr1234: 0x%08x, cycle0: 0x%02x\n",
1738                cmd, addr, cycle0);
1739
1740        timeout = jiffies + msecs_to_jiffies(NFC_TIME_OUT_MS);
1741        while (nfc_cmd_readl(NFCADDR_CMD_NFCBUSY, host->nfc->base_cmd_regs)
1742                        & NFCADDR_CMD_NFCBUSY) {
1743                if (time_after(jiffies, timeout)) {
1744                        dev_err(host->dev,
1745                                "Time out to wait CMD_NFCBUSY ready!\n");
1746                        return -ETIMEDOUT;
1747                }
1748        }
1749
1750        nfc_prepare_interrupt(host, flag);
1751        nfc_writel(host->nfc->hsmc_regs, CYCLE0, cycle0);
1752        nfc_cmd_addr1234_writel(cmd, addr, host->nfc->base_cmd_regs);
1753        return nfc_wait_interrupt(host, flag);
1754}
1755
1756static int nfc_device_ready(struct mtd_info *mtd)
1757{
1758        u32 status, mask;
1759        struct nand_chip *nand_chip = mtd->priv;
1760        struct atmel_nand_host *host = nand_chip->priv;
1761
1762        status = nfc_read_status(host);
1763        mask = nfc_readl(host->nfc->hsmc_regs, IMR);
1764
1765        /* The mask should be 0. If not we may lost interrupts */
1766        if (unlikely(mask & status))
1767                dev_err(host->dev, "Lost the interrupt flags: 0x%08x\n",
1768                                mask & status);
1769
1770        return status & NFC_SR_RB_EDGE;
1771}
1772
1773static void nfc_select_chip(struct mtd_info *mtd, int chip)
1774{
1775        struct nand_chip *nand_chip = mtd->priv;
1776        struct atmel_nand_host *host = nand_chip->priv;
1777
1778        if (chip == -1)
1779                nfc_writel(host->nfc->hsmc_regs, CTRL, NFC_CTRL_DISABLE);
1780        else
1781                nfc_writel(host->nfc->hsmc_regs, CTRL, NFC_CTRL_ENABLE);
1782}
1783
1784static int nfc_make_addr(struct mtd_info *mtd, int command, int column,
1785                int page_addr, unsigned int *addr1234, unsigned int *cycle0)
1786{
1787        struct nand_chip *chip = mtd->priv;
1788
1789        int acycle = 0;
1790        unsigned char addr_bytes[8];
1791        int index = 0, bit_shift;
1792
1793        BUG_ON(addr1234 == NULL || cycle0 == NULL);
1794
1795        *cycle0 = 0;
1796        *addr1234 = 0;
1797
1798        if (column != -1) {
1799                if (chip->options & NAND_BUSWIDTH_16 &&
1800                                !nand_opcode_8bits(command))
1801                        column >>= 1;
1802                addr_bytes[acycle++] = column & 0xff;
1803                if (mtd->writesize > 512)
1804                        addr_bytes[acycle++] = (column >> 8) & 0xff;
1805        }
1806
1807        if (page_addr != -1) {
1808                addr_bytes[acycle++] = page_addr & 0xff;
1809                addr_bytes[acycle++] = (page_addr >> 8) & 0xff;
1810                if (chip->chipsize > (128 << 20))
1811                        addr_bytes[acycle++] = (page_addr >> 16) & 0xff;
1812        }
1813
1814        if (acycle > 4)
1815                *cycle0 = addr_bytes[index++];
1816
1817        for (bit_shift = 0; index < acycle; bit_shift += 8)
1818                *addr1234 += addr_bytes[index++] << bit_shift;
1819
1820        /* return acycle in cmd register */
1821        return acycle << NFCADDR_CMD_ACYCLE_BIT_POS;
1822}
1823
1824static void nfc_nand_command(struct mtd_info *mtd, unsigned int command,
1825                                int column, int page_addr)
1826{
1827        struct nand_chip *chip = mtd->priv;
1828        struct atmel_nand_host *host = chip->priv;
1829        unsigned long timeout;
1830        unsigned int nfc_addr_cmd = 0;
1831
1832        unsigned int cmd1 = command << NFCADDR_CMD_CMD1_BIT_POS;
1833
1834        /* Set default settings: no cmd2, no addr cycle. read from nand */
1835        unsigned int cmd2 = 0;
1836        unsigned int vcmd2 = 0;
1837        int acycle = NFCADDR_CMD_ACYCLE_NONE;
1838        int csid = NFCADDR_CMD_CSID_3;
1839        int dataen = NFCADDR_CMD_DATADIS;
1840        int nfcwr = NFCADDR_CMD_NFCRD;
1841        unsigned int addr1234 = 0;
1842        unsigned int cycle0 = 0;
1843        bool do_addr = true;
1844        host->nfc->data_in_sram = NULL;
1845
1846        dev_dbg(host->dev, "%s: cmd = 0x%02x, col = 0x%08x, page = 0x%08x\n",
1847             __func__, command, column, page_addr);
1848
1849        switch (command) {
1850        case NAND_CMD_RESET:
1851                nfc_addr_cmd = cmd1 | acycle | csid | dataen | nfcwr;
1852                nfc_send_command(host, nfc_addr_cmd, addr1234, cycle0);
1853                udelay(chip->chip_delay);
1854
1855                nfc_nand_command(mtd, NAND_CMD_STATUS, -1, -1);
1856                timeout = jiffies + msecs_to_jiffies(NFC_TIME_OUT_MS);
1857                while (!(chip->read_byte(mtd) & NAND_STATUS_READY)) {
1858                        if (time_after(jiffies, timeout)) {
1859                                dev_err(host->dev,
1860                                        "Time out to wait status ready!\n");
1861                                break;
1862                        }
1863                }
1864                return;
1865        case NAND_CMD_STATUS:
1866                do_addr = false;
1867                break;
1868        case NAND_CMD_PARAM:
1869        case NAND_CMD_READID:
1870                do_addr = false;
1871                acycle = NFCADDR_CMD_ACYCLE_1;
1872                if (column != -1)
1873                        addr1234 = column;
1874                break;
1875        case NAND_CMD_RNDOUT:
1876                cmd2 = NAND_CMD_RNDOUTSTART << NFCADDR_CMD_CMD2_BIT_POS;
1877                vcmd2 = NFCADDR_CMD_VCMD2;
1878                break;
1879        case NAND_CMD_READ0:
1880        case NAND_CMD_READOOB:
1881                if (command == NAND_CMD_READOOB) {
1882                        column += mtd->writesize;
1883                        command = NAND_CMD_READ0; /* only READ0 is valid */
1884                        cmd1 = command << NFCADDR_CMD_CMD1_BIT_POS;
1885                }
1886                if (host->nfc->use_nfc_sram) {
1887                        /* Enable Data transfer to sram */
1888                        dataen = NFCADDR_CMD_DATAEN;
1889
1890                        /* Need enable PMECC now, since NFC will transfer
1891                         * data in bus after sending nfc read command.
1892                         */
1893                        if (chip->ecc.mode == NAND_ECC_HW && host->has_pmecc)
1894                                pmecc_enable(host, NAND_ECC_READ);
1895                }
1896
1897                cmd2 = NAND_CMD_READSTART << NFCADDR_CMD_CMD2_BIT_POS;
1898                vcmd2 = NFCADDR_CMD_VCMD2;
1899                break;
1900        /* For prgramming command, the cmd need set to write enable */
1901        case NAND_CMD_PAGEPROG:
1902        case NAND_CMD_SEQIN:
1903        case NAND_CMD_RNDIN:
1904                nfcwr = NFCADDR_CMD_NFCWR;
1905                if (host->nfc->will_write_sram && command == NAND_CMD_SEQIN)
1906                        dataen = NFCADDR_CMD_DATAEN;
1907                break;
1908        default:
1909                break;
1910        }
1911
1912        if (do_addr)
1913                acycle = nfc_make_addr(mtd, command, column, page_addr,
1914                                &addr1234, &cycle0);
1915
1916        nfc_addr_cmd = cmd1 | cmd2 | vcmd2 | acycle | csid | dataen | nfcwr;
1917        nfc_send_command(host, nfc_addr_cmd, addr1234, cycle0);
1918
1919        /*
1920         * Program and erase have their own busy handlers status, sequential
1921         * in, and deplete1 need no delay.
1922         */
1923        switch (command) {
1924        case NAND_CMD_CACHEDPROG:
1925        case NAND_CMD_PAGEPROG:
1926        case NAND_CMD_ERASE1:
1927        case NAND_CMD_ERASE2:
1928        case NAND_CMD_RNDIN:
1929        case NAND_CMD_STATUS:
1930        case NAND_CMD_RNDOUT:
1931        case NAND_CMD_SEQIN:
1932        case NAND_CMD_READID:
1933                return;
1934
1935        case NAND_CMD_READ0:
1936                if (dataen == NFCADDR_CMD_DATAEN) {
1937                        host->nfc->data_in_sram = host->nfc->sram_bank0 +
1938                                nfc_get_sram_off(host);
1939                        return;
1940                }
1941                /* fall through */
1942        default:
1943                nfc_prepare_interrupt(host, NFC_SR_RB_EDGE);
1944                nfc_wait_interrupt(host, NFC_SR_RB_EDGE);
1945        }
1946}
1947
1948static int nfc_sram_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1949                        uint32_t offset, int data_len, const uint8_t *buf,
1950                        int oob_required, int page, int cached, int raw)
1951{
1952        int cfg, len;
1953        int status = 0;
1954        struct atmel_nand_host *host = chip->priv;
1955        void *sram = host->nfc->sram_bank0 + nfc_get_sram_off(host);
1956
1957        /* Subpage write is not supported */
1958        if (offset || (data_len < mtd->writesize))
1959                return -EINVAL;
1960
1961        len = mtd->writesize;
1962        /* Copy page data to sram that will write to nand via NFC */
1963        if (use_dma) {
1964                if (atmel_nand_dma_op(mtd, (void *)buf, len, 0) != 0)
1965                        /* Fall back to use cpu copy */
1966                        memcpy(sram, buf, len);
1967        } else {
1968                memcpy(sram, buf, len);
1969        }
1970
1971        cfg = nfc_readl(host->nfc->hsmc_regs, CFG);
1972        if (unlikely(raw) && oob_required) {
1973                memcpy(sram + len, chip->oob_poi, mtd->oobsize);
1974                len += mtd->oobsize;
1975                nfc_writel(host->nfc->hsmc_regs, CFG, cfg | NFC_CFG_WSPARE);
1976        } else {
1977                nfc_writel(host->nfc->hsmc_regs, CFG, cfg & ~NFC_CFG_WSPARE);
1978        }
1979
1980        if (chip->ecc.mode == NAND_ECC_HW && host->has_pmecc)
1981                /*
1982                 * When use NFC sram, need set up PMECC before send
1983                 * NAND_CMD_SEQIN command. Since when the nand command
1984                 * is sent, nfc will do transfer from sram and nand.
1985                 */
1986                pmecc_enable(host, NAND_ECC_WRITE);
1987
1988        host->nfc->will_write_sram = true;
1989        chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
1990        host->nfc->will_write_sram = false;
1991
1992        if (likely(!raw))
1993                /* Need to write ecc into oob */
1994                status = chip->ecc.write_page(mtd, chip, buf, oob_required);
1995
1996        if (status < 0)
1997                return status;
1998
1999        chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2000        status = chip->waitfunc(mtd, chip);
2001
2002        if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2003                status = chip->errstat(mtd, chip, FL_WRITING, status, page);
2004
2005        if (status & NAND_STATUS_FAIL)
2006                return -EIO;
2007
2008        return 0;
2009}
2010
2011static int nfc_sram_init(struct mtd_info *mtd)
2012{
2013        struct nand_chip *chip = mtd->priv;
2014        struct atmel_nand_host *host = chip->priv;
2015        int res = 0;
2016
2017        /* Initialize the NFC CFG register */
2018        unsigned int cfg_nfc = 0;
2019
2020        /* set page size and oob layout */
2021        switch (mtd->writesize) {
2022        case 512:
2023                cfg_nfc = NFC_CFG_PAGESIZE_512;
2024                break;
2025        case 1024:
2026                cfg_nfc = NFC_CFG_PAGESIZE_1024;
2027                break;
2028        case 2048:
2029                cfg_nfc = NFC_CFG_PAGESIZE_2048;
2030                break;
2031        case 4096:
2032                cfg_nfc = NFC_CFG_PAGESIZE_4096;
2033                break;
2034        case 8192:
2035                cfg_nfc = NFC_CFG_PAGESIZE_8192;
2036                break;
2037        default:
2038                dev_err(host->dev, "Unsupported page size for NFC.\n");
2039                res = -ENXIO;
2040                return res;
2041        }
2042
2043        /* oob bytes size = (NFCSPARESIZE + 1) * 4
2044         * Max support spare size is 512 bytes. */
2045        cfg_nfc |= (((mtd->oobsize / 4) - 1) << NFC_CFG_NFC_SPARESIZE_BIT_POS
2046                & NFC_CFG_NFC_SPARESIZE);
2047        /* default set a max timeout */
2048        cfg_nfc |= NFC_CFG_RSPARE |
2049                        NFC_CFG_NFC_DTOCYC | NFC_CFG_NFC_DTOMUL;
2050
2051        nfc_writel(host->nfc->hsmc_regs, CFG, cfg_nfc);
2052
2053        host->nfc->will_write_sram = false;
2054        nfc_set_sram_bank(host, 0);
2055
2056        /* Use Write page with NFC SRAM only for PMECC or ECC NONE. */
2057        if (host->nfc->write_by_sram) {
2058                if ((chip->ecc.mode == NAND_ECC_HW && host->has_pmecc) ||
2059                                chip->ecc.mode == NAND_ECC_NONE)
2060                        chip->write_page = nfc_sram_write_page;
2061                else
2062                        host->nfc->write_by_sram = false;
2063        }
2064
2065        dev_info(host->dev, "Using NFC Sram read %s\n",
2066                        host->nfc->write_by_sram ? "and write" : "");
2067        return 0;
2068}
2069
2070static struct platform_driver atmel_nand_nfc_driver;
2071/*
2072 * Probe for the NAND device.
2073 */
2074static int atmel_nand_probe(struct platform_device *pdev)
2075{
2076        struct atmel_nand_host *host;
2077        struct mtd_info *mtd;
2078        struct nand_chip *nand_chip;
2079        struct resource *mem;
2080        struct mtd_part_parser_data ppdata = {};
2081        int res, irq;
2082
2083        /* Allocate memory for the device structure (and zero it) */
2084        host = devm_kzalloc(&pdev->dev, sizeof(*host), GFP_KERNEL);
2085        if (!host)
2086                return -ENOMEM;
2087
2088        res = platform_driver_register(&atmel_nand_nfc_driver);
2089        if (res)
2090                dev_err(&pdev->dev, "atmel_nand: can't register NFC driver\n");
2091
2092        mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2093        host->io_base = devm_ioremap_resource(&pdev->dev, mem);
2094        if (IS_ERR(host->io_base)) {
2095                res = PTR_ERR(host->io_base);
2096                goto err_nand_ioremap;
2097        }
2098        host->io_phys = (dma_addr_t)mem->start;
2099
2100        mtd = &host->mtd;
2101        nand_chip = &host->nand_chip;
2102        host->dev = &pdev->dev;
2103        if (IS_ENABLED(CONFIG_OF) && pdev->dev.of_node) {
2104                /* Only when CONFIG_OF is enabled of_node can be parsed */
2105                res = atmel_of_init_port(host, pdev->dev.of_node);
2106                if (res)
2107                        goto err_nand_ioremap;
2108        } else {
2109                memcpy(&host->board, dev_get_platdata(&pdev->dev),
2110                       sizeof(struct atmel_nand_data));
2111        }
2112
2113        nand_chip->priv = host;         /* link the private data structures */
2114        mtd->priv = nand_chip;
2115        mtd->owner = THIS_MODULE;
2116
2117        /* Set address of NAND IO lines */
2118        nand_chip->IO_ADDR_R = host->io_base;
2119        nand_chip->IO_ADDR_W = host->io_base;
2120
2121        if (nand_nfc.is_initialized) {
2122                /* NFC driver is probed and initialized */
2123                host->nfc = &nand_nfc;
2124
2125                nand_chip->select_chip = nfc_select_chip;
2126                nand_chip->dev_ready = nfc_device_ready;
2127                nand_chip->cmdfunc = nfc_nand_command;
2128
2129                /* Initialize the interrupt for NFC */
2130                irq = platform_get_irq(pdev, 0);
2131                if (irq < 0) {
2132                        dev_err(host->dev, "Cannot get HSMC irq!\n");
2133                        res = irq;
2134                        goto err_nand_ioremap;
2135                }
2136
2137                res = devm_request_irq(&pdev->dev, irq, hsmc_interrupt,
2138                                0, "hsmc", host);
2139                if (res) {
2140                        dev_err(&pdev->dev, "Unable to request HSMC irq %d\n",
2141                                irq);
2142                        goto err_nand_ioremap;
2143                }
2144        } else {
2145                res = atmel_nand_set_enable_ready_pins(mtd);
2146                if (res)
2147                        goto err_nand_ioremap;
2148
2149                nand_chip->cmd_ctrl = atmel_nand_cmd_ctrl;
2150        }
2151
2152        nand_chip->ecc.mode = host->board.ecc_mode;
2153        nand_chip->chip_delay = 40;             /* 40us command delay time */
2154
2155        if (host->board.bus_width_16)   /* 16-bit bus width */
2156                nand_chip->options |= NAND_BUSWIDTH_16;
2157
2158        nand_chip->read_buf = atmel_read_buf;
2159        nand_chip->write_buf = atmel_write_buf;
2160
2161        platform_set_drvdata(pdev, host);
2162        atmel_nand_enable(host);
2163
2164        if (gpio_is_valid(host->board.det_pin)) {
2165                res = devm_gpio_request(&pdev->dev,
2166                                host->board.det_pin, "nand_det");
2167                if (res < 0) {
2168                        dev_err(&pdev->dev,
2169                                "can't request det gpio %d\n",
2170                                host->board.det_pin);
2171                        goto err_no_card;
2172                }
2173
2174                res = gpio_direction_input(host->board.det_pin);
2175                if (res < 0) {
2176                        dev_err(&pdev->dev,
2177                                "can't request input direction det gpio %d\n",
2178                                host->board.det_pin);
2179                        goto err_no_card;
2180                }
2181
2182                if (gpio_get_value(host->board.det_pin)) {
2183                        dev_info(&pdev->dev, "No SmartMedia card inserted.\n");
2184                        res = -ENXIO;
2185                        goto err_no_card;
2186                }
2187        }
2188
2189        if (host->board.on_flash_bbt || on_flash_bbt) {
2190                dev_info(&pdev->dev, "Use On Flash BBT\n");
2191                nand_chip->bbt_options |= NAND_BBT_USE_FLASH;
2192        }
2193
2194        if (!host->board.has_dma)
2195                use_dma = 0;
2196
2197        if (use_dma) {
2198                dma_cap_mask_t mask;
2199
2200                dma_cap_zero(mask);
2201                dma_cap_set(DMA_MEMCPY, mask);
2202                host->dma_chan = dma_request_channel(mask, NULL, NULL);
2203                if (!host->dma_chan) {
2204                        dev_err(host->dev, "Failed to request DMA channel\n");
2205                        use_dma = 0;
2206                }
2207        }
2208        if (use_dma)
2209                dev_info(host->dev, "Using %s for DMA transfers.\n",
2210                                        dma_chan_name(host->dma_chan));
2211        else
2212                dev_info(host->dev, "No DMA support for NAND access.\n");
2213
2214        /* first scan to find the device and get the page size */
2215        if (nand_scan_ident(mtd, 1, NULL)) {
2216                res = -ENXIO;
2217                goto err_scan_ident;
2218        }
2219
2220        if (nand_chip->ecc.mode == NAND_ECC_HW) {
2221                if (host->has_pmecc)
2222                        res = atmel_pmecc_nand_init_params(pdev, host);
2223                else
2224                        res = atmel_hw_nand_init_params(pdev, host);
2225
2226                if (res != 0)
2227                        goto err_hw_ecc;
2228        }
2229
2230        /* initialize the nfc configuration register */
2231        if (host->nfc && host->nfc->use_nfc_sram) {
2232                res = nfc_sram_init(mtd);
2233                if (res) {
2234                        host->nfc->use_nfc_sram = false;
2235                        dev_err(host->dev, "Disable use nfc sram for data transfer.\n");
2236                }
2237        }
2238
2239        /* second phase scan */
2240        if (nand_scan_tail(mtd)) {
2241                res = -ENXIO;
2242                goto err_scan_tail;
2243        }
2244
2245        mtd->name = "atmel_nand";
2246        ppdata.of_node = pdev->dev.of_node;
2247        res = mtd_device_parse_register(mtd, NULL, &ppdata,
2248                        host->board.parts, host->board.num_parts);
2249        if (!res)
2250                return res;
2251
2252err_scan_tail:
2253        if (host->has_pmecc && host->nand_chip.ecc.mode == NAND_ECC_HW)
2254                pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
2255err_hw_ecc:
2256err_scan_ident:
2257err_no_card:
2258        atmel_nand_disable(host);
2259        if (host->dma_chan)
2260                dma_release_channel(host->dma_chan);
2261err_nand_ioremap:
2262        return res;
2263}
2264
2265/*
2266 * Remove a NAND device.
2267 */
2268static int atmel_nand_remove(struct platform_device *pdev)
2269{
2270        struct atmel_nand_host *host = platform_get_drvdata(pdev);
2271        struct mtd_info *mtd = &host->mtd;
2272
2273        nand_release(mtd);
2274
2275        atmel_nand_disable(host);
2276
2277        if (host->has_pmecc && host->nand_chip.ecc.mode == NAND_ECC_HW) {
2278                pmecc_writel(host->ecc, CTRL, PMECC_CTRL_DISABLE);
2279                pmerrloc_writel(host->pmerrloc_base, ELDIS,
2280                                PMERRLOC_DISABLE);
2281        }
2282
2283        if (host->dma_chan)
2284                dma_release_channel(host->dma_chan);
2285
2286        platform_driver_unregister(&atmel_nand_nfc_driver);
2287
2288        return 0;
2289}
2290
2291static const struct of_device_id atmel_nand_dt_ids[] = {
2292        { .compatible = "atmel,at91rm9200-nand" },
2293        { /* sentinel */ }
2294};
2295
2296MODULE_DEVICE_TABLE(of, atmel_nand_dt_ids);
2297
2298static int atmel_nand_nfc_probe(struct platform_device *pdev)
2299{
2300        struct atmel_nfc *nfc = &nand_nfc;
2301        struct resource *nfc_cmd_regs, *nfc_hsmc_regs, *nfc_sram;
2302        int ret;
2303
2304        nfc_cmd_regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2305        nfc->base_cmd_regs = devm_ioremap_resource(&pdev->dev, nfc_cmd_regs);
2306        if (IS_ERR(nfc->base_cmd_regs))
2307                return PTR_ERR(nfc->base_cmd_regs);
2308
2309        nfc_hsmc_regs = platform_get_resource(pdev, IORESOURCE_MEM, 1);
2310        nfc->hsmc_regs = devm_ioremap_resource(&pdev->dev, nfc_hsmc_regs);
2311        if (IS_ERR(nfc->hsmc_regs))
2312                return PTR_ERR(nfc->hsmc_regs);
2313
2314        nfc_sram = platform_get_resource(pdev, IORESOURCE_MEM, 2);
2315        if (nfc_sram) {
2316                nfc->sram_bank0 = (void * __force)
2317                                devm_ioremap_resource(&pdev->dev, nfc_sram);
2318                if (IS_ERR(nfc->sram_bank0)) {
2319                        dev_warn(&pdev->dev, "Fail to ioremap the NFC sram with error: %ld. So disable NFC sram.\n",
2320                                        PTR_ERR(nfc->sram_bank0));
2321                } else {
2322                        nfc->use_nfc_sram = true;
2323                        nfc->sram_bank0_phys = (dma_addr_t)nfc_sram->start;
2324
2325                        if (pdev->dev.of_node)
2326                                nfc->write_by_sram = of_property_read_bool(
2327                                                pdev->dev.of_node,
2328                                                "atmel,write-by-sram");
2329                }
2330        }
2331
2332        nfc_writel(nfc->hsmc_regs, IDR, 0xffffffff);
2333        nfc_readl(nfc->hsmc_regs, SR);  /* clear the NFC_SR */
2334
2335        nfc->clk = devm_clk_get(&pdev->dev, NULL);
2336        if (!IS_ERR(nfc->clk)) {
2337                ret = clk_prepare_enable(nfc->clk);
2338                if (ret)
2339                        return ret;
2340        } else {
2341                dev_warn(&pdev->dev, "NFC clock missing, update your Device Tree");
2342        }
2343
2344        nfc->is_initialized = true;
2345        dev_info(&pdev->dev, "NFC is probed.\n");
2346
2347        return 0;
2348}
2349
2350static int atmel_nand_nfc_remove(struct platform_device *pdev)
2351{
2352        struct atmel_nfc *nfc = &nand_nfc;
2353
2354        if (!IS_ERR(nfc->clk))
2355                clk_disable_unprepare(nfc->clk);
2356
2357        return 0;
2358}
2359
2360static const struct of_device_id atmel_nand_nfc_match[] = {
2361        { .compatible = "atmel,sama5d3-nfc" },
2362        { /* sentinel */ }
2363};
2364MODULE_DEVICE_TABLE(of, atmel_nand_nfc_match);
2365
2366static struct platform_driver atmel_nand_nfc_driver = {
2367        .driver = {
2368                .name = "atmel_nand_nfc",
2369                .of_match_table = of_match_ptr(atmel_nand_nfc_match),
2370        },
2371        .probe = atmel_nand_nfc_probe,
2372        .remove = atmel_nand_nfc_remove,
2373};
2374
2375static struct platform_driver atmel_nand_driver = {
2376        .probe          = atmel_nand_probe,
2377        .remove         = atmel_nand_remove,
2378        .driver         = {
2379                .name   = "atmel_nand",
2380                .of_match_table = of_match_ptr(atmel_nand_dt_ids),
2381        },
2382};
2383
2384module_platform_driver(atmel_nand_driver);
2385
2386MODULE_LICENSE("GPL");
2387MODULE_AUTHOR("Rick Bronson");
2388MODULE_DESCRIPTION("NAND/SmartMedia driver for AT91 / AVR32");
2389MODULE_ALIAS("platform:atmel_nand");
2390