linux/drivers/mtd/nand/gpmi-nand/gpmi-nand.c
<<
>>
Prefs
   1/*
   2 * Freescale GPMI NAND Flash Driver
   3 *
   4 * Copyright (C) 2010-2015 Freescale Semiconductor, Inc.
   5 * Copyright (C) 2008 Embedded Alley Solutions, Inc.
   6 *
   7 * This program is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License as published by
   9 * the Free Software Foundation; either version 2 of the License, or
  10 * (at your option) any later version.
  11 *
  12 * This program is distributed in the hope that it will be useful,
  13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15 * GNU General Public License for more details.
  16 *
  17 * You should have received a copy of the GNU General Public License along
  18 * with this program; if not, write to the Free Software Foundation, Inc.,
  19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20 */
  21#include <linux/clk.h>
  22#include <linux/slab.h>
  23#include <linux/interrupt.h>
  24#include <linux/module.h>
  25#include <linux/mtd/partitions.h>
  26#include <linux/of.h>
  27#include <linux/of_device.h>
  28#include "gpmi-nand.h"
  29#include "bch-regs.h"
  30
  31/* Resource names for the GPMI NAND driver. */
  32#define GPMI_NAND_GPMI_REGS_ADDR_RES_NAME  "gpmi-nand"
  33#define GPMI_NAND_BCH_REGS_ADDR_RES_NAME   "bch"
  34#define GPMI_NAND_BCH_INTERRUPT_RES_NAME   "bch"
  35
  36/* add our owner bbt descriptor */
  37static uint8_t scan_ff_pattern[] = { 0xff };
  38static struct nand_bbt_descr gpmi_bbt_descr = {
  39        .options        = 0,
  40        .offs           = 0,
  41        .len            = 1,
  42        .pattern        = scan_ff_pattern
  43};
  44
  45/*
  46 * We may change the layout if we can get the ECC info from the datasheet,
  47 * else we will use all the (page + OOB).
  48 */
  49static int gpmi_ooblayout_ecc(struct mtd_info *mtd, int section,
  50                              struct mtd_oob_region *oobregion)
  51{
  52        struct nand_chip *chip = mtd_to_nand(mtd);
  53        struct gpmi_nand_data *this = nand_get_controller_data(chip);
  54        struct bch_geometry *geo = &this->bch_geometry;
  55
  56        if (section)
  57                return -ERANGE;
  58
  59        oobregion->offset = 0;
  60        oobregion->length = geo->page_size - mtd->writesize;
  61
  62        return 0;
  63}
  64
  65static int gpmi_ooblayout_free(struct mtd_info *mtd, int section,
  66                               struct mtd_oob_region *oobregion)
  67{
  68        struct nand_chip *chip = mtd_to_nand(mtd);
  69        struct gpmi_nand_data *this = nand_get_controller_data(chip);
  70        struct bch_geometry *geo = &this->bch_geometry;
  71
  72        if (section)
  73                return -ERANGE;
  74
  75        /* The available oob size we have. */
  76        if (geo->page_size < mtd->writesize + mtd->oobsize) {
  77                oobregion->offset = geo->page_size - mtd->writesize;
  78                oobregion->length = mtd->oobsize - oobregion->offset;
  79        }
  80
  81        return 0;
  82}
  83
  84static const struct mtd_ooblayout_ops gpmi_ooblayout_ops = {
  85        .ecc = gpmi_ooblayout_ecc,
  86        .free = gpmi_ooblayout_free,
  87};
  88
  89static const struct gpmi_devdata gpmi_devdata_imx23 = {
  90        .type = IS_MX23,
  91        .bch_max_ecc_strength = 20,
  92        .max_chain_delay = 16,
  93};
  94
  95static const struct gpmi_devdata gpmi_devdata_imx28 = {
  96        .type = IS_MX28,
  97        .bch_max_ecc_strength = 20,
  98        .max_chain_delay = 16,
  99};
 100
 101static const struct gpmi_devdata gpmi_devdata_imx6q = {
 102        .type = IS_MX6Q,
 103        .bch_max_ecc_strength = 40,
 104        .max_chain_delay = 12,
 105};
 106
 107static const struct gpmi_devdata gpmi_devdata_imx6sx = {
 108        .type = IS_MX6SX,
 109        .bch_max_ecc_strength = 62,
 110        .max_chain_delay = 12,
 111};
 112
 113static irqreturn_t bch_irq(int irq, void *cookie)
 114{
 115        struct gpmi_nand_data *this = cookie;
 116
 117        gpmi_clear_bch(this);
 118        complete(&this->bch_done);
 119        return IRQ_HANDLED;
 120}
 121
 122/*
 123 *  Calculate the ECC strength by hand:
 124 *      E : The ECC strength.
 125 *      G : the length of Galois Field.
 126 *      N : The chunk count of per page.
 127 *      O : the oobsize of the NAND chip.
 128 *      M : the metasize of per page.
 129 *
 130 *      The formula is :
 131 *              E * G * N
 132 *            ------------ <= (O - M)
 133 *                  8
 134 *
 135 *      So, we get E by:
 136 *                    (O - M) * 8
 137 *              E <= -------------
 138 *                       G * N
 139 */
 140static inline int get_ecc_strength(struct gpmi_nand_data *this)
 141{
 142        struct bch_geometry *geo = &this->bch_geometry;
 143        struct mtd_info *mtd = nand_to_mtd(&this->nand);
 144        int ecc_strength;
 145
 146        ecc_strength = ((mtd->oobsize - geo->metadata_size) * 8)
 147                        / (geo->gf_len * geo->ecc_chunk_count);
 148
 149        /* We need the minor even number. */
 150        return round_down(ecc_strength, 2);
 151}
 152
 153static inline bool gpmi_check_ecc(struct gpmi_nand_data *this)
 154{
 155        struct bch_geometry *geo = &this->bch_geometry;
 156
 157        /* Do the sanity check. */
 158        if (GPMI_IS_MX23(this) || GPMI_IS_MX28(this)) {
 159                /* The mx23/mx28 only support the GF13. */
 160                if (geo->gf_len == 14)
 161                        return false;
 162        }
 163        return geo->ecc_strength <= this->devdata->bch_max_ecc_strength;
 164}
 165
 166/*
 167 * If we can get the ECC information from the nand chip, we do not
 168 * need to calculate them ourselves.
 169 *
 170 * We may have available oob space in this case.
 171 */
 172static int set_geometry_by_ecc_info(struct gpmi_nand_data *this)
 173{
 174        struct bch_geometry *geo = &this->bch_geometry;
 175        struct nand_chip *chip = &this->nand;
 176        struct mtd_info *mtd = nand_to_mtd(chip);
 177        unsigned int block_mark_bit_offset;
 178
 179        if (!(chip->ecc_strength_ds > 0 && chip->ecc_step_ds > 0))
 180                return -EINVAL;
 181
 182        switch (chip->ecc_step_ds) {
 183        case SZ_512:
 184                geo->gf_len = 13;
 185                break;
 186        case SZ_1K:
 187                geo->gf_len = 14;
 188                break;
 189        default:
 190                dev_err(this->dev,
 191                        "unsupported nand chip. ecc bits : %d, ecc size : %d\n",
 192                        chip->ecc_strength_ds, chip->ecc_step_ds);
 193                return -EINVAL;
 194        }
 195        geo->ecc_chunk_size = chip->ecc_step_ds;
 196        geo->ecc_strength = round_up(chip->ecc_strength_ds, 2);
 197        if (!gpmi_check_ecc(this))
 198                return -EINVAL;
 199
 200        /* Keep the C >= O */
 201        if (geo->ecc_chunk_size < mtd->oobsize) {
 202                dev_err(this->dev,
 203                        "unsupported nand chip. ecc size: %d, oob size : %d\n",
 204                        chip->ecc_step_ds, mtd->oobsize);
 205                return -EINVAL;
 206        }
 207
 208        /* The default value, see comment in the legacy_set_geometry(). */
 209        geo->metadata_size = 10;
 210
 211        geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
 212
 213        /*
 214         * Now, the NAND chip with 2K page(data chunk is 512byte) shows below:
 215         *
 216         *    |                          P                            |
 217         *    |<----------------------------------------------------->|
 218         *    |                                                       |
 219         *    |                                        (Block Mark)   |
 220         *    |                      P'                      |      | |     |
 221         *    |<-------------------------------------------->|  D   | |  O' |
 222         *    |                                              |<---->| |<--->|
 223         *    V                                              V      V V     V
 224         *    +---+----------+-+----------+-+----------+-+----------+-+-----+
 225         *    | M |   data   |E|   data   |E|   data   |E|   data   |E|     |
 226         *    +---+----------+-+----------+-+----------+-+----------+-+-----+
 227         *                                                   ^              ^
 228         *                                                   |      O       |
 229         *                                                   |<------------>|
 230         *                                                   |              |
 231         *
 232         *      P : the page size for BCH module.
 233         *      E : The ECC strength.
 234         *      G : the length of Galois Field.
 235         *      N : The chunk count of per page.
 236         *      M : the metasize of per page.
 237         *      C : the ecc chunk size, aka the "data" above.
 238         *      P': the nand chip's page size.
 239         *      O : the nand chip's oob size.
 240         *      O': the free oob.
 241         *
 242         *      The formula for P is :
 243         *
 244         *                  E * G * N
 245         *             P = ------------ + P' + M
 246         *                      8
 247         *
 248         * The position of block mark moves forward in the ECC-based view
 249         * of page, and the delta is:
 250         *
 251         *                   E * G * (N - 1)
 252         *             D = (---------------- + M)
 253         *                          8
 254         *
 255         * Please see the comment in legacy_set_geometry().
 256         * With the condition C >= O , we still can get same result.
 257         * So the bit position of the physical block mark within the ECC-based
 258         * view of the page is :
 259         *             (P' - D) * 8
 260         */
 261        geo->page_size = mtd->writesize + geo->metadata_size +
 262                (geo->gf_len * geo->ecc_strength * geo->ecc_chunk_count) / 8;
 263
 264        geo->payload_size = mtd->writesize;
 265
 266        geo->auxiliary_status_offset = ALIGN(geo->metadata_size, 4);
 267        geo->auxiliary_size = ALIGN(geo->metadata_size, 4)
 268                                + ALIGN(geo->ecc_chunk_count, 4);
 269
 270        if (!this->swap_block_mark)
 271                return 0;
 272
 273        /* For bit swap. */
 274        block_mark_bit_offset = mtd->writesize * 8 -
 275                (geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
 276                                + geo->metadata_size * 8);
 277
 278        geo->block_mark_byte_offset = block_mark_bit_offset / 8;
 279        geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
 280        return 0;
 281}
 282
 283static int legacy_set_geometry(struct gpmi_nand_data *this)
 284{
 285        struct bch_geometry *geo = &this->bch_geometry;
 286        struct mtd_info *mtd = nand_to_mtd(&this->nand);
 287        unsigned int metadata_size;
 288        unsigned int status_size;
 289        unsigned int block_mark_bit_offset;
 290
 291        /*
 292         * The size of the metadata can be changed, though we set it to 10
 293         * bytes now. But it can't be too large, because we have to save
 294         * enough space for BCH.
 295         */
 296        geo->metadata_size = 10;
 297
 298        /* The default for the length of Galois Field. */
 299        geo->gf_len = 13;
 300
 301        /* The default for chunk size. */
 302        geo->ecc_chunk_size = 512;
 303        while (geo->ecc_chunk_size < mtd->oobsize) {
 304                geo->ecc_chunk_size *= 2; /* keep C >= O */
 305                geo->gf_len = 14;
 306        }
 307
 308        geo->ecc_chunk_count = mtd->writesize / geo->ecc_chunk_size;
 309
 310        /* We use the same ECC strength for all chunks. */
 311        geo->ecc_strength = get_ecc_strength(this);
 312        if (!gpmi_check_ecc(this)) {
 313                dev_err(this->dev,
 314                        "ecc strength: %d cannot be supported by the controller (%d)\n"
 315                        "try to use minimum ecc strength that NAND chip required\n",
 316                        geo->ecc_strength,
 317                        this->devdata->bch_max_ecc_strength);
 318                return -EINVAL;
 319        }
 320
 321        geo->page_size = mtd->writesize + mtd->oobsize;
 322        geo->payload_size = mtd->writesize;
 323
 324        /*
 325         * The auxiliary buffer contains the metadata and the ECC status. The
 326         * metadata is padded to the nearest 32-bit boundary. The ECC status
 327         * contains one byte for every ECC chunk, and is also padded to the
 328         * nearest 32-bit boundary.
 329         */
 330        metadata_size = ALIGN(geo->metadata_size, 4);
 331        status_size   = ALIGN(geo->ecc_chunk_count, 4);
 332
 333        geo->auxiliary_size = metadata_size + status_size;
 334        geo->auxiliary_status_offset = metadata_size;
 335
 336        if (!this->swap_block_mark)
 337                return 0;
 338
 339        /*
 340         * We need to compute the byte and bit offsets of
 341         * the physical block mark within the ECC-based view of the page.
 342         *
 343         * NAND chip with 2K page shows below:
 344         *                                             (Block Mark)
 345         *                                                   |      |
 346         *                                                   |  D   |
 347         *                                                   |<---->|
 348         *                                                   V      V
 349         *    +---+----------+-+----------+-+----------+-+----------+-+
 350         *    | M |   data   |E|   data   |E|   data   |E|   data   |E|
 351         *    +---+----------+-+----------+-+----------+-+----------+-+
 352         *
 353         * The position of block mark moves forward in the ECC-based view
 354         * of page, and the delta is:
 355         *
 356         *                   E * G * (N - 1)
 357         *             D = (---------------- + M)
 358         *                          8
 359         *
 360         * With the formula to compute the ECC strength, and the condition
 361         *       : C >= O         (C is the ecc chunk size)
 362         *
 363         * It's easy to deduce to the following result:
 364         *
 365         *         E * G       (O - M)      C - M         C - M
 366         *      ----------- <= ------- <=  --------  <  ---------
 367         *           8            N           N          (N - 1)
 368         *
 369         *  So, we get:
 370         *
 371         *                   E * G * (N - 1)
 372         *             D = (---------------- + M) < C
 373         *                          8
 374         *
 375         *  The above inequality means the position of block mark
 376         *  within the ECC-based view of the page is still in the data chunk,
 377         *  and it's NOT in the ECC bits of the chunk.
 378         *
 379         *  Use the following to compute the bit position of the
 380         *  physical block mark within the ECC-based view of the page:
 381         *          (page_size - D) * 8
 382         *
 383         *  --Huang Shijie
 384         */
 385        block_mark_bit_offset = mtd->writesize * 8 -
 386                (geo->ecc_strength * geo->gf_len * (geo->ecc_chunk_count - 1)
 387                                + geo->metadata_size * 8);
 388
 389        geo->block_mark_byte_offset = block_mark_bit_offset / 8;
 390        geo->block_mark_bit_offset  = block_mark_bit_offset % 8;
 391        return 0;
 392}
 393
 394int common_nfc_set_geometry(struct gpmi_nand_data *this)
 395{
 396        if ((of_property_read_bool(this->dev->of_node, "fsl,use-minimum-ecc"))
 397                                || legacy_set_geometry(this))
 398                return set_geometry_by_ecc_info(this);
 399
 400        return 0;
 401}
 402
 403struct dma_chan *get_dma_chan(struct gpmi_nand_data *this)
 404{
 405        /* We use the DMA channel 0 to access all the nand chips. */
 406        return this->dma_chans[0];
 407}
 408
 409/* Can we use the upper's buffer directly for DMA? */
 410void prepare_data_dma(struct gpmi_nand_data *this, enum dma_data_direction dr)
 411{
 412        struct scatterlist *sgl = &this->data_sgl;
 413        int ret;
 414
 415        /* first try to map the upper buffer directly */
 416        if (virt_addr_valid(this->upper_buf) &&
 417                !object_is_on_stack(this->upper_buf)) {
 418                sg_init_one(sgl, this->upper_buf, this->upper_len);
 419                ret = dma_map_sg(this->dev, sgl, 1, dr);
 420                if (ret == 0)
 421                        goto map_fail;
 422
 423                this->direct_dma_map_ok = true;
 424                return;
 425        }
 426
 427map_fail:
 428        /* We have to use our own DMA buffer. */
 429        sg_init_one(sgl, this->data_buffer_dma, this->upper_len);
 430
 431        if (dr == DMA_TO_DEVICE)
 432                memcpy(this->data_buffer_dma, this->upper_buf, this->upper_len);
 433
 434        dma_map_sg(this->dev, sgl, 1, dr);
 435
 436        this->direct_dma_map_ok = false;
 437}
 438
 439/* This will be called after the DMA operation is finished. */
 440static void dma_irq_callback(void *param)
 441{
 442        struct gpmi_nand_data *this = param;
 443        struct completion *dma_c = &this->dma_done;
 444
 445        switch (this->dma_type) {
 446        case DMA_FOR_COMMAND:
 447                dma_unmap_sg(this->dev, &this->cmd_sgl, 1, DMA_TO_DEVICE);
 448                break;
 449
 450        case DMA_FOR_READ_DATA:
 451                dma_unmap_sg(this->dev, &this->data_sgl, 1, DMA_FROM_DEVICE);
 452                if (this->direct_dma_map_ok == false)
 453                        memcpy(this->upper_buf, this->data_buffer_dma,
 454                                this->upper_len);
 455                break;
 456
 457        case DMA_FOR_WRITE_DATA:
 458                dma_unmap_sg(this->dev, &this->data_sgl, 1, DMA_TO_DEVICE);
 459                break;
 460
 461        case DMA_FOR_READ_ECC_PAGE:
 462        case DMA_FOR_WRITE_ECC_PAGE:
 463                /* We have to wait the BCH interrupt to finish. */
 464                break;
 465
 466        default:
 467                dev_err(this->dev, "in wrong DMA operation.\n");
 468        }
 469
 470        complete(dma_c);
 471}
 472
 473int start_dma_without_bch_irq(struct gpmi_nand_data *this,
 474                                struct dma_async_tx_descriptor *desc)
 475{
 476        struct completion *dma_c = &this->dma_done;
 477        unsigned long timeout;
 478
 479        init_completion(dma_c);
 480
 481        desc->callback          = dma_irq_callback;
 482        desc->callback_param    = this;
 483        dmaengine_submit(desc);
 484        dma_async_issue_pending(get_dma_chan(this));
 485
 486        /* Wait for the interrupt from the DMA block. */
 487        timeout = wait_for_completion_timeout(dma_c, msecs_to_jiffies(1000));
 488        if (!timeout) {
 489                dev_err(this->dev, "DMA timeout, last DMA :%d\n",
 490                        this->last_dma_type);
 491                gpmi_dump_info(this);
 492                return -ETIMEDOUT;
 493        }
 494        return 0;
 495}
 496
 497/*
 498 * This function is used in BCH reading or BCH writing pages.
 499 * It will wait for the BCH interrupt as long as ONE second.
 500 * Actually, we must wait for two interrupts :
 501 *      [1] firstly the DMA interrupt and
 502 *      [2] secondly the BCH interrupt.
 503 */
 504int start_dma_with_bch_irq(struct gpmi_nand_data *this,
 505                        struct dma_async_tx_descriptor *desc)
 506{
 507        struct completion *bch_c = &this->bch_done;
 508        unsigned long timeout;
 509
 510        /* Prepare to receive an interrupt from the BCH block. */
 511        init_completion(bch_c);
 512
 513        /* start the DMA */
 514        start_dma_without_bch_irq(this, desc);
 515
 516        /* Wait for the interrupt from the BCH block. */
 517        timeout = wait_for_completion_timeout(bch_c, msecs_to_jiffies(1000));
 518        if (!timeout) {
 519                dev_err(this->dev, "BCH timeout, last DMA :%d\n",
 520                        this->last_dma_type);
 521                gpmi_dump_info(this);
 522                return -ETIMEDOUT;
 523        }
 524        return 0;
 525}
 526
 527static int acquire_register_block(struct gpmi_nand_data *this,
 528                                  const char *res_name)
 529{
 530        struct platform_device *pdev = this->pdev;
 531        struct resources *res = &this->resources;
 532        struct resource *r;
 533        void __iomem *p;
 534
 535        r = platform_get_resource_byname(pdev, IORESOURCE_MEM, res_name);
 536        p = devm_ioremap_resource(&pdev->dev, r);
 537        if (IS_ERR(p))
 538                return PTR_ERR(p);
 539
 540        if (!strcmp(res_name, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME))
 541                res->gpmi_regs = p;
 542        else if (!strcmp(res_name, GPMI_NAND_BCH_REGS_ADDR_RES_NAME))
 543                res->bch_regs = p;
 544        else
 545                dev_err(this->dev, "unknown resource name : %s\n", res_name);
 546
 547        return 0;
 548}
 549
 550static int acquire_bch_irq(struct gpmi_nand_data *this, irq_handler_t irq_h)
 551{
 552        struct platform_device *pdev = this->pdev;
 553        const char *res_name = GPMI_NAND_BCH_INTERRUPT_RES_NAME;
 554        struct resource *r;
 555        int err;
 556
 557        r = platform_get_resource_byname(pdev, IORESOURCE_IRQ, res_name);
 558        if (!r) {
 559                dev_err(this->dev, "Can't get resource for %s\n", res_name);
 560                return -ENODEV;
 561        }
 562
 563        err = devm_request_irq(this->dev, r->start, irq_h, 0, res_name, this);
 564        if (err)
 565                dev_err(this->dev, "error requesting BCH IRQ\n");
 566
 567        return err;
 568}
 569
 570static void release_dma_channels(struct gpmi_nand_data *this)
 571{
 572        unsigned int i;
 573        for (i = 0; i < DMA_CHANS; i++)
 574                if (this->dma_chans[i]) {
 575                        dma_release_channel(this->dma_chans[i]);
 576                        this->dma_chans[i] = NULL;
 577                }
 578}
 579
 580static int acquire_dma_channels(struct gpmi_nand_data *this)
 581{
 582        struct platform_device *pdev = this->pdev;
 583        struct dma_chan *dma_chan;
 584
 585        /* request dma channel */
 586        dma_chan = dma_request_slave_channel(&pdev->dev, "rx-tx");
 587        if (!dma_chan) {
 588                dev_err(this->dev, "Failed to request DMA channel.\n");
 589                goto acquire_err;
 590        }
 591
 592        this->dma_chans[0] = dma_chan;
 593        return 0;
 594
 595acquire_err:
 596        release_dma_channels(this);
 597        return -EINVAL;
 598}
 599
 600static char *extra_clks_for_mx6q[GPMI_CLK_MAX] = {
 601        "gpmi_apb", "gpmi_bch", "gpmi_bch_apb", "per1_bch",
 602};
 603
 604static int gpmi_get_clks(struct gpmi_nand_data *this)
 605{
 606        struct resources *r = &this->resources;
 607        char **extra_clks = NULL;
 608        struct clk *clk;
 609        int err, i;
 610
 611        /* The main clock is stored in the first. */
 612        r->clock[0] = devm_clk_get(this->dev, "gpmi_io");
 613        if (IS_ERR(r->clock[0])) {
 614                err = PTR_ERR(r->clock[0]);
 615                goto err_clock;
 616        }
 617
 618        /* Get extra clocks */
 619        if (GPMI_IS_MX6(this))
 620                extra_clks = extra_clks_for_mx6q;
 621        if (!extra_clks)
 622                return 0;
 623
 624        for (i = 1; i < GPMI_CLK_MAX; i++) {
 625                if (extra_clks[i - 1] == NULL)
 626                        break;
 627
 628                clk = devm_clk_get(this->dev, extra_clks[i - 1]);
 629                if (IS_ERR(clk)) {
 630                        err = PTR_ERR(clk);
 631                        goto err_clock;
 632                }
 633
 634                r->clock[i] = clk;
 635        }
 636
 637        if (GPMI_IS_MX6(this))
 638                /*
 639                 * Set the default value for the gpmi clock.
 640                 *
 641                 * If you want to use the ONFI nand which is in the
 642                 * Synchronous Mode, you should change the clock as you need.
 643                 */
 644                clk_set_rate(r->clock[0], 22000000);
 645
 646        return 0;
 647
 648err_clock:
 649        dev_dbg(this->dev, "failed in finding the clocks.\n");
 650        return err;
 651}
 652
 653static int acquire_resources(struct gpmi_nand_data *this)
 654{
 655        int ret;
 656
 657        ret = acquire_register_block(this, GPMI_NAND_GPMI_REGS_ADDR_RES_NAME);
 658        if (ret)
 659                goto exit_regs;
 660
 661        ret = acquire_register_block(this, GPMI_NAND_BCH_REGS_ADDR_RES_NAME);
 662        if (ret)
 663                goto exit_regs;
 664
 665        ret = acquire_bch_irq(this, bch_irq);
 666        if (ret)
 667                goto exit_regs;
 668
 669        ret = acquire_dma_channels(this);
 670        if (ret)
 671                goto exit_regs;
 672
 673        ret = gpmi_get_clks(this);
 674        if (ret)
 675                goto exit_clock;
 676        return 0;
 677
 678exit_clock:
 679        release_dma_channels(this);
 680exit_regs:
 681        return ret;
 682}
 683
 684static void release_resources(struct gpmi_nand_data *this)
 685{
 686        release_dma_channels(this);
 687}
 688
 689static int init_hardware(struct gpmi_nand_data *this)
 690{
 691        int ret;
 692
 693        /*
 694         * This structure contains the "safe" GPMI timing that should succeed
 695         * with any NAND Flash device
 696         * (although, with less-than-optimal performance).
 697         */
 698        struct nand_timing  safe_timing = {
 699                .data_setup_in_ns        = 80,
 700                .data_hold_in_ns         = 60,
 701                .address_setup_in_ns     = 25,
 702                .gpmi_sample_delay_in_ns =  6,
 703                .tREA_in_ns              = -1,
 704                .tRLOH_in_ns             = -1,
 705                .tRHOH_in_ns             = -1,
 706        };
 707
 708        /* Initialize the hardwares. */
 709        ret = gpmi_init(this);
 710        if (ret)
 711                return ret;
 712
 713        this->timing = safe_timing;
 714        return 0;
 715}
 716
 717static int read_page_prepare(struct gpmi_nand_data *this,
 718                        void *destination, unsigned length,
 719                        void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
 720                        void **use_virt, dma_addr_t *use_phys)
 721{
 722        struct device *dev = this->dev;
 723
 724        if (virt_addr_valid(destination)) {
 725                dma_addr_t dest_phys;
 726
 727                dest_phys = dma_map_single(dev, destination,
 728                                                length, DMA_FROM_DEVICE);
 729                if (dma_mapping_error(dev, dest_phys)) {
 730                        if (alt_size < length) {
 731                                dev_err(dev, "Alternate buffer is too small\n");
 732                                return -ENOMEM;
 733                        }
 734                        goto map_failed;
 735                }
 736                *use_virt = destination;
 737                *use_phys = dest_phys;
 738                this->direct_dma_map_ok = true;
 739                return 0;
 740        }
 741
 742map_failed:
 743        *use_virt = alt_virt;
 744        *use_phys = alt_phys;
 745        this->direct_dma_map_ok = false;
 746        return 0;
 747}
 748
 749static inline void read_page_end(struct gpmi_nand_data *this,
 750                        void *destination, unsigned length,
 751                        void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
 752                        void *used_virt, dma_addr_t used_phys)
 753{
 754        if (this->direct_dma_map_ok)
 755                dma_unmap_single(this->dev, used_phys, length, DMA_FROM_DEVICE);
 756}
 757
 758static inline void read_page_swap_end(struct gpmi_nand_data *this,
 759                        void *destination, unsigned length,
 760                        void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
 761                        void *used_virt, dma_addr_t used_phys)
 762{
 763        if (!this->direct_dma_map_ok)
 764                memcpy(destination, alt_virt, length);
 765}
 766
 767static int send_page_prepare(struct gpmi_nand_data *this,
 768                        const void *source, unsigned length,
 769                        void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
 770                        const void **use_virt, dma_addr_t *use_phys)
 771{
 772        struct device *dev = this->dev;
 773
 774        if (virt_addr_valid(source)) {
 775                dma_addr_t source_phys;
 776
 777                source_phys = dma_map_single(dev, (void *)source, length,
 778                                                DMA_TO_DEVICE);
 779                if (dma_mapping_error(dev, source_phys)) {
 780                        if (alt_size < length) {
 781                                dev_err(dev, "Alternate buffer is too small\n");
 782                                return -ENOMEM;
 783                        }
 784                        goto map_failed;
 785                }
 786                *use_virt = source;
 787                *use_phys = source_phys;
 788                return 0;
 789        }
 790map_failed:
 791        /*
 792         * Copy the content of the source buffer into the alternate
 793         * buffer and set up the return values accordingly.
 794         */
 795        memcpy(alt_virt, source, length);
 796
 797        *use_virt = alt_virt;
 798        *use_phys = alt_phys;
 799        return 0;
 800}
 801
 802static void send_page_end(struct gpmi_nand_data *this,
 803                        const void *source, unsigned length,
 804                        void *alt_virt, dma_addr_t alt_phys, unsigned alt_size,
 805                        const void *used_virt, dma_addr_t used_phys)
 806{
 807        struct device *dev = this->dev;
 808        if (used_virt == source)
 809                dma_unmap_single(dev, used_phys, length, DMA_TO_DEVICE);
 810}
 811
 812static void gpmi_free_dma_buffer(struct gpmi_nand_data *this)
 813{
 814        struct device *dev = this->dev;
 815
 816        if (this->page_buffer_virt && virt_addr_valid(this->page_buffer_virt))
 817                dma_free_coherent(dev, this->page_buffer_size,
 818                                        this->page_buffer_virt,
 819                                        this->page_buffer_phys);
 820        kfree(this->cmd_buffer);
 821        kfree(this->data_buffer_dma);
 822        kfree(this->raw_buffer);
 823
 824        this->cmd_buffer        = NULL;
 825        this->data_buffer_dma   = NULL;
 826        this->raw_buffer        = NULL;
 827        this->page_buffer_virt  = NULL;
 828        this->page_buffer_size  =  0;
 829}
 830
 831/* Allocate the DMA buffers */
 832static int gpmi_alloc_dma_buffer(struct gpmi_nand_data *this)
 833{
 834        struct bch_geometry *geo = &this->bch_geometry;
 835        struct device *dev = this->dev;
 836        struct mtd_info *mtd = nand_to_mtd(&this->nand);
 837
 838        /* [1] Allocate a command buffer. PAGE_SIZE is enough. */
 839        this->cmd_buffer = kzalloc(PAGE_SIZE, GFP_DMA | GFP_KERNEL);
 840        if (this->cmd_buffer == NULL)
 841                goto error_alloc;
 842
 843        /*
 844         * [2] Allocate a read/write data buffer.
 845         *     The gpmi_alloc_dma_buffer can be called twice.
 846         *     We allocate a PAGE_SIZE length buffer if gpmi_alloc_dma_buffer
 847         *     is called before the nand_scan_ident; and we allocate a buffer
 848         *     of the real NAND page size when the gpmi_alloc_dma_buffer is
 849         *     called after the nand_scan_ident.
 850         */
 851        this->data_buffer_dma = kzalloc(mtd->writesize ?: PAGE_SIZE,
 852                                        GFP_DMA | GFP_KERNEL);
 853        if (this->data_buffer_dma == NULL)
 854                goto error_alloc;
 855
 856        /*
 857         * [3] Allocate the page buffer.
 858         *
 859         * Both the payload buffer and the auxiliary buffer must appear on
 860         * 32-bit boundaries. We presume the size of the payload buffer is a
 861         * power of two and is much larger than four, which guarantees the
 862         * auxiliary buffer will appear on a 32-bit boundary.
 863         */
 864        this->page_buffer_size = geo->payload_size + geo->auxiliary_size;
 865        this->page_buffer_virt = dma_alloc_coherent(dev, this->page_buffer_size,
 866                                        &this->page_buffer_phys, GFP_DMA);
 867        if (!this->page_buffer_virt)
 868                goto error_alloc;
 869
 870        this->raw_buffer = kzalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
 871        if (!this->raw_buffer)
 872                goto error_alloc;
 873
 874        /* Slice up the page buffer. */
 875        this->payload_virt = this->page_buffer_virt;
 876        this->payload_phys = this->page_buffer_phys;
 877        this->auxiliary_virt = this->payload_virt + geo->payload_size;
 878        this->auxiliary_phys = this->payload_phys + geo->payload_size;
 879        return 0;
 880
 881error_alloc:
 882        gpmi_free_dma_buffer(this);
 883        return -ENOMEM;
 884}
 885
 886static void gpmi_cmd_ctrl(struct mtd_info *mtd, int data, unsigned int ctrl)
 887{
 888        struct nand_chip *chip = mtd_to_nand(mtd);
 889        struct gpmi_nand_data *this = nand_get_controller_data(chip);
 890        int ret;
 891
 892        /*
 893         * Every operation begins with a command byte and a series of zero or
 894         * more address bytes. These are distinguished by either the Address
 895         * Latch Enable (ALE) or Command Latch Enable (CLE) signals being
 896         * asserted. When MTD is ready to execute the command, it will deassert
 897         * both latch enables.
 898         *
 899         * Rather than run a separate DMA operation for every single byte, we
 900         * queue them up and run a single DMA operation for the entire series
 901         * of command and data bytes. NAND_CMD_NONE means the END of the queue.
 902         */
 903        if ((ctrl & (NAND_ALE | NAND_CLE))) {
 904                if (data != NAND_CMD_NONE)
 905                        this->cmd_buffer[this->command_length++] = data;
 906                return;
 907        }
 908
 909        if (!this->command_length)
 910                return;
 911
 912        ret = gpmi_send_command(this);
 913        if (ret)
 914                dev_err(this->dev, "Chip: %u, Error %d\n",
 915                        this->current_chip, ret);
 916
 917        this->command_length = 0;
 918}
 919
 920static int gpmi_dev_ready(struct mtd_info *mtd)
 921{
 922        struct nand_chip *chip = mtd_to_nand(mtd);
 923        struct gpmi_nand_data *this = nand_get_controller_data(chip);
 924
 925        return gpmi_is_ready(this, this->current_chip);
 926}
 927
 928static void gpmi_select_chip(struct mtd_info *mtd, int chipnr)
 929{
 930        struct nand_chip *chip = mtd_to_nand(mtd);
 931        struct gpmi_nand_data *this = nand_get_controller_data(chip);
 932
 933        if ((this->current_chip < 0) && (chipnr >= 0))
 934                gpmi_begin(this);
 935        else if ((this->current_chip >= 0) && (chipnr < 0))
 936                gpmi_end(this);
 937
 938        this->current_chip = chipnr;
 939}
 940
 941static void gpmi_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
 942{
 943        struct nand_chip *chip = mtd_to_nand(mtd);
 944        struct gpmi_nand_data *this = nand_get_controller_data(chip);
 945
 946        dev_dbg(this->dev, "len is %d\n", len);
 947        this->upper_buf = buf;
 948        this->upper_len = len;
 949
 950        gpmi_read_data(this);
 951}
 952
 953static void gpmi_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
 954{
 955        struct nand_chip *chip = mtd_to_nand(mtd);
 956        struct gpmi_nand_data *this = nand_get_controller_data(chip);
 957
 958        dev_dbg(this->dev, "len is %d\n", len);
 959        this->upper_buf = (uint8_t *)buf;
 960        this->upper_len = len;
 961
 962        gpmi_send_data(this);
 963}
 964
 965static uint8_t gpmi_read_byte(struct mtd_info *mtd)
 966{
 967        struct nand_chip *chip = mtd_to_nand(mtd);
 968        struct gpmi_nand_data *this = nand_get_controller_data(chip);
 969        uint8_t *buf = this->data_buffer_dma;
 970
 971        gpmi_read_buf(mtd, buf, 1);
 972        return buf[0];
 973}
 974
 975/*
 976 * Handles block mark swapping.
 977 * It can be called in swapping the block mark, or swapping it back,
 978 * because the the operations are the same.
 979 */
 980static void block_mark_swapping(struct gpmi_nand_data *this,
 981                                void *payload, void *auxiliary)
 982{
 983        struct bch_geometry *nfc_geo = &this->bch_geometry;
 984        unsigned char *p;
 985        unsigned char *a;
 986        unsigned int  bit;
 987        unsigned char mask;
 988        unsigned char from_data;
 989        unsigned char from_oob;
 990
 991        if (!this->swap_block_mark)
 992                return;
 993
 994        /*
 995         * If control arrives here, we're swapping. Make some convenience
 996         * variables.
 997         */
 998        bit = nfc_geo->block_mark_bit_offset;
 999        p   = payload + nfc_geo->block_mark_byte_offset;
1000        a   = auxiliary;
1001
1002        /*
1003         * Get the byte from the data area that overlays the block mark. Since
1004         * the ECC engine applies its own view to the bits in the page, the
1005         * physical block mark won't (in general) appear on a byte boundary in
1006         * the data.
1007         */
1008        from_data = (p[0] >> bit) | (p[1] << (8 - bit));
1009
1010        /* Get the byte from the OOB. */
1011        from_oob = a[0];
1012
1013        /* Swap them. */
1014        a[0] = from_data;
1015
1016        mask = (0x1 << bit) - 1;
1017        p[0] = (p[0] & mask) | (from_oob << bit);
1018
1019        mask = ~0 << bit;
1020        p[1] = (p[1] & mask) | (from_oob >> (8 - bit));
1021}
1022
1023static int gpmi_ecc_read_page(struct mtd_info *mtd, struct nand_chip *chip,
1024                                uint8_t *buf, int oob_required, int page)
1025{
1026        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1027        struct bch_geometry *nfc_geo = &this->bch_geometry;
1028        void          *payload_virt;
1029        dma_addr_t    payload_phys;
1030        void          *auxiliary_virt;
1031        dma_addr_t    auxiliary_phys;
1032        unsigned int  i;
1033        unsigned char *status;
1034        unsigned int  max_bitflips = 0;
1035        int           ret;
1036
1037        dev_dbg(this->dev, "page number is : %d\n", page);
1038        ret = read_page_prepare(this, buf, nfc_geo->payload_size,
1039                                        this->payload_virt, this->payload_phys,
1040                                        nfc_geo->payload_size,
1041                                        &payload_virt, &payload_phys);
1042        if (ret) {
1043                dev_err(this->dev, "Inadequate DMA buffer\n");
1044                ret = -ENOMEM;
1045                return ret;
1046        }
1047        auxiliary_virt = this->auxiliary_virt;
1048        auxiliary_phys = this->auxiliary_phys;
1049
1050        /* go! */
1051        ret = gpmi_read_page(this, payload_phys, auxiliary_phys);
1052        read_page_end(this, buf, nfc_geo->payload_size,
1053                        this->payload_virt, this->payload_phys,
1054                        nfc_geo->payload_size,
1055                        payload_virt, payload_phys);
1056        if (ret) {
1057                dev_err(this->dev, "Error in ECC-based read: %d\n", ret);
1058                return ret;
1059        }
1060
1061        /* handle the block mark swapping */
1062        block_mark_swapping(this, payload_virt, auxiliary_virt);
1063
1064        /* Loop over status bytes, accumulating ECC status. */
1065        status = auxiliary_virt + nfc_geo->auxiliary_status_offset;
1066
1067        read_page_swap_end(this, buf, nfc_geo->payload_size,
1068                           this->payload_virt, this->payload_phys,
1069                           nfc_geo->payload_size,
1070                           payload_virt, payload_phys);
1071
1072        for (i = 0; i < nfc_geo->ecc_chunk_count; i++, status++) {
1073                if ((*status == STATUS_GOOD) || (*status == STATUS_ERASED))
1074                        continue;
1075
1076                if (*status == STATUS_UNCORRECTABLE) {
1077                        int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1078                        u8 *eccbuf = this->raw_buffer;
1079                        int offset, bitoffset;
1080                        int eccbytes;
1081                        int flips;
1082
1083                        /* Read ECC bytes into our internal raw_buffer */
1084                        offset = nfc_geo->metadata_size * 8;
1085                        offset += ((8 * nfc_geo->ecc_chunk_size) + eccbits) * (i + 1);
1086                        offset -= eccbits;
1087                        bitoffset = offset % 8;
1088                        eccbytes = DIV_ROUND_UP(offset + eccbits, 8);
1089                        offset /= 8;
1090                        eccbytes -= offset;
1091                        chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset, -1);
1092                        chip->read_buf(mtd, eccbuf, eccbytes);
1093
1094                        /*
1095                         * ECC data are not byte aligned and we may have
1096                         * in-band data in the first and last byte of
1097                         * eccbuf. Set non-eccbits to one so that
1098                         * nand_check_erased_ecc_chunk() does not count them
1099                         * as bitflips.
1100                         */
1101                        if (bitoffset)
1102                                eccbuf[0] |= GENMASK(bitoffset - 1, 0);
1103
1104                        bitoffset = (bitoffset + eccbits) % 8;
1105                        if (bitoffset)
1106                                eccbuf[eccbytes - 1] |= GENMASK(7, bitoffset);
1107
1108                        /*
1109                         * The ECC hardware has an uncorrectable ECC status
1110                         * code in case we have bitflips in an erased page. As
1111                         * nothing was written into this subpage the ECC is
1112                         * obviously wrong and we can not trust it. We assume
1113                         * at this point that we are reading an erased page and
1114                         * try to correct the bitflips in buffer up to
1115                         * ecc_strength bitflips. If this is a page with random
1116                         * data, we exceed this number of bitflips and have a
1117                         * ECC failure. Otherwise we use the corrected buffer.
1118                         */
1119                        if (i == 0) {
1120                                /* The first block includes metadata */
1121                                flips = nand_check_erased_ecc_chunk(
1122                                                buf + i * nfc_geo->ecc_chunk_size,
1123                                                nfc_geo->ecc_chunk_size,
1124                                                eccbuf, eccbytes,
1125                                                auxiliary_virt,
1126                                                nfc_geo->metadata_size,
1127                                                nfc_geo->ecc_strength);
1128                        } else {
1129                                flips = nand_check_erased_ecc_chunk(
1130                                                buf + i * nfc_geo->ecc_chunk_size,
1131                                                nfc_geo->ecc_chunk_size,
1132                                                eccbuf, eccbytes,
1133                                                NULL, 0,
1134                                                nfc_geo->ecc_strength);
1135                        }
1136
1137                        if (flips > 0) {
1138                                max_bitflips = max_t(unsigned int, max_bitflips,
1139                                                     flips);
1140                                mtd->ecc_stats.corrected += flips;
1141                                continue;
1142                        }
1143
1144                        mtd->ecc_stats.failed++;
1145                        continue;
1146                }
1147
1148                mtd->ecc_stats.corrected += *status;
1149                max_bitflips = max_t(unsigned int, max_bitflips, *status);
1150        }
1151
1152        if (oob_required) {
1153                /*
1154                 * It's time to deliver the OOB bytes. See gpmi_ecc_read_oob()
1155                 * for details about our policy for delivering the OOB.
1156                 *
1157                 * We fill the caller's buffer with set bits, and then copy the
1158                 * block mark to th caller's buffer. Note that, if block mark
1159                 * swapping was necessary, it has already been done, so we can
1160                 * rely on the first byte of the auxiliary buffer to contain
1161                 * the block mark.
1162                 */
1163                memset(chip->oob_poi, ~0, mtd->oobsize);
1164                chip->oob_poi[0] = ((uint8_t *) auxiliary_virt)[0];
1165        }
1166
1167        return max_bitflips;
1168}
1169
1170/* Fake a virtual small page for the subpage read */
1171static int gpmi_ecc_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1172                        uint32_t offs, uint32_t len, uint8_t *buf, int page)
1173{
1174        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1175        void __iomem *bch_regs = this->resources.bch_regs;
1176        struct bch_geometry old_geo = this->bch_geometry;
1177        struct bch_geometry *geo = &this->bch_geometry;
1178        int size = chip->ecc.size; /* ECC chunk size */
1179        int meta, n, page_size;
1180        u32 r1_old, r2_old, r1_new, r2_new;
1181        unsigned int max_bitflips;
1182        int first, last, marker_pos;
1183        int ecc_parity_size;
1184        int col = 0;
1185        int old_swap_block_mark = this->swap_block_mark;
1186
1187        /* The size of ECC parity */
1188        ecc_parity_size = geo->gf_len * geo->ecc_strength / 8;
1189
1190        /* Align it with the chunk size */
1191        first = offs / size;
1192        last = (offs + len - 1) / size;
1193
1194        if (this->swap_block_mark) {
1195                /*
1196                 * Find the chunk which contains the Block Marker.
1197                 * If this chunk is in the range of [first, last],
1198                 * we have to read out the whole page.
1199                 * Why? since we had swapped the data at the position of Block
1200                 * Marker to the metadata which is bound with the chunk 0.
1201                 */
1202                marker_pos = geo->block_mark_byte_offset / size;
1203                if (last >= marker_pos && first <= marker_pos) {
1204                        dev_dbg(this->dev,
1205                                "page:%d, first:%d, last:%d, marker at:%d\n",
1206                                page, first, last, marker_pos);
1207                        return gpmi_ecc_read_page(mtd, chip, buf, 0, page);
1208                }
1209        }
1210
1211        meta = geo->metadata_size;
1212        if (first) {
1213                col = meta + (size + ecc_parity_size) * first;
1214                chip->cmdfunc(mtd, NAND_CMD_RNDOUT, col, -1);
1215
1216                meta = 0;
1217                buf = buf + first * size;
1218        }
1219
1220        /* Save the old environment */
1221        r1_old = r1_new = readl(bch_regs + HW_BCH_FLASH0LAYOUT0);
1222        r2_old = r2_new = readl(bch_regs + HW_BCH_FLASH0LAYOUT1);
1223
1224        /* change the BCH registers and bch_geometry{} */
1225        n = last - first + 1;
1226        page_size = meta + (size + ecc_parity_size) * n;
1227
1228        r1_new &= ~(BM_BCH_FLASH0LAYOUT0_NBLOCKS |
1229                        BM_BCH_FLASH0LAYOUT0_META_SIZE);
1230        r1_new |= BF_BCH_FLASH0LAYOUT0_NBLOCKS(n - 1)
1231                        | BF_BCH_FLASH0LAYOUT0_META_SIZE(meta);
1232        writel(r1_new, bch_regs + HW_BCH_FLASH0LAYOUT0);
1233
1234        r2_new &= ~BM_BCH_FLASH0LAYOUT1_PAGE_SIZE;
1235        r2_new |= BF_BCH_FLASH0LAYOUT1_PAGE_SIZE(page_size);
1236        writel(r2_new, bch_regs + HW_BCH_FLASH0LAYOUT1);
1237
1238        geo->ecc_chunk_count = n;
1239        geo->payload_size = n * size;
1240        geo->page_size = page_size;
1241        geo->auxiliary_status_offset = ALIGN(meta, 4);
1242
1243        dev_dbg(this->dev, "page:%d(%d:%d)%d, chunk:(%d:%d), BCH PG size:%d\n",
1244                page, offs, len, col, first, n, page_size);
1245
1246        /* Read the subpage now */
1247        this->swap_block_mark = false;
1248        max_bitflips = gpmi_ecc_read_page(mtd, chip, buf, 0, page);
1249
1250        /* Restore */
1251        writel(r1_old, bch_regs + HW_BCH_FLASH0LAYOUT0);
1252        writel(r2_old, bch_regs + HW_BCH_FLASH0LAYOUT1);
1253        this->bch_geometry = old_geo;
1254        this->swap_block_mark = old_swap_block_mark;
1255
1256        return max_bitflips;
1257}
1258
1259static int gpmi_ecc_write_page(struct mtd_info *mtd, struct nand_chip *chip,
1260                                const uint8_t *buf, int oob_required, int page)
1261{
1262        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1263        struct bch_geometry *nfc_geo = &this->bch_geometry;
1264        const void *payload_virt;
1265        dma_addr_t payload_phys;
1266        const void *auxiliary_virt;
1267        dma_addr_t auxiliary_phys;
1268        int        ret;
1269
1270        dev_dbg(this->dev, "ecc write page.\n");
1271        if (this->swap_block_mark) {
1272                /*
1273                 * If control arrives here, we're doing block mark swapping.
1274                 * Since we can't modify the caller's buffers, we must copy them
1275                 * into our own.
1276                 */
1277                memcpy(this->payload_virt, buf, mtd->writesize);
1278                payload_virt = this->payload_virt;
1279                payload_phys = this->payload_phys;
1280
1281                memcpy(this->auxiliary_virt, chip->oob_poi,
1282                                nfc_geo->auxiliary_size);
1283                auxiliary_virt = this->auxiliary_virt;
1284                auxiliary_phys = this->auxiliary_phys;
1285
1286                /* Handle block mark swapping. */
1287                block_mark_swapping(this,
1288                                (void *)payload_virt, (void *)auxiliary_virt);
1289        } else {
1290                /*
1291                 * If control arrives here, we're not doing block mark swapping,
1292                 * so we can to try and use the caller's buffers.
1293                 */
1294                ret = send_page_prepare(this,
1295                                buf, mtd->writesize,
1296                                this->payload_virt, this->payload_phys,
1297                                nfc_geo->payload_size,
1298                                &payload_virt, &payload_phys);
1299                if (ret) {
1300                        dev_err(this->dev, "Inadequate payload DMA buffer\n");
1301                        return 0;
1302                }
1303
1304                ret = send_page_prepare(this,
1305                                chip->oob_poi, mtd->oobsize,
1306                                this->auxiliary_virt, this->auxiliary_phys,
1307                                nfc_geo->auxiliary_size,
1308                                &auxiliary_virt, &auxiliary_phys);
1309                if (ret) {
1310                        dev_err(this->dev, "Inadequate auxiliary DMA buffer\n");
1311                        goto exit_auxiliary;
1312                }
1313        }
1314
1315        /* Ask the NFC. */
1316        ret = gpmi_send_page(this, payload_phys, auxiliary_phys);
1317        if (ret)
1318                dev_err(this->dev, "Error in ECC-based write: %d\n", ret);
1319
1320        if (!this->swap_block_mark) {
1321                send_page_end(this, chip->oob_poi, mtd->oobsize,
1322                                this->auxiliary_virt, this->auxiliary_phys,
1323                                nfc_geo->auxiliary_size,
1324                                auxiliary_virt, auxiliary_phys);
1325exit_auxiliary:
1326                send_page_end(this, buf, mtd->writesize,
1327                                this->payload_virt, this->payload_phys,
1328                                nfc_geo->payload_size,
1329                                payload_virt, payload_phys);
1330        }
1331
1332        return 0;
1333}
1334
1335/*
1336 * There are several places in this driver where we have to handle the OOB and
1337 * block marks. This is the function where things are the most complicated, so
1338 * this is where we try to explain it all. All the other places refer back to
1339 * here.
1340 *
1341 * These are the rules, in order of decreasing importance:
1342 *
1343 * 1) Nothing the caller does can be allowed to imperil the block mark.
1344 *
1345 * 2) In read operations, the first byte of the OOB we return must reflect the
1346 *    true state of the block mark, no matter where that block mark appears in
1347 *    the physical page.
1348 *
1349 * 3) ECC-based read operations return an OOB full of set bits (since we never
1350 *    allow ECC-based writes to the OOB, it doesn't matter what ECC-based reads
1351 *    return).
1352 *
1353 * 4) "Raw" read operations return a direct view of the physical bytes in the
1354 *    page, using the conventional definition of which bytes are data and which
1355 *    are OOB. This gives the caller a way to see the actual, physical bytes
1356 *    in the page, without the distortions applied by our ECC engine.
1357 *
1358 *
1359 * What we do for this specific read operation depends on two questions:
1360 *
1361 * 1) Are we doing a "raw" read, or an ECC-based read?
1362 *
1363 * 2) Are we using block mark swapping or transcription?
1364 *
1365 * There are four cases, illustrated by the following Karnaugh map:
1366 *
1367 *                    |           Raw           |         ECC-based       |
1368 *       -------------+-------------------------+-------------------------+
1369 *                    | Read the conventional   |                         |
1370 *                    | OOB at the end of the   |                         |
1371 *       Swapping     | page and return it. It  |                         |
1372 *                    | contains exactly what   |                         |
1373 *                    | we want.                | Read the block mark and |
1374 *       -------------+-------------------------+ return it in a buffer   |
1375 *                    | Read the conventional   | full of set bits.       |
1376 *                    | OOB at the end of the   |                         |
1377 *                    | page and also the block |                         |
1378 *       Transcribing | mark in the metadata.   |                         |
1379 *                    | Copy the block mark     |                         |
1380 *                    | into the first byte of  |                         |
1381 *                    | the OOB.                |                         |
1382 *       -------------+-------------------------+-------------------------+
1383 *
1384 * Note that we break rule #4 in the Transcribing/Raw case because we're not
1385 * giving an accurate view of the actual, physical bytes in the page (we're
1386 * overwriting the block mark). That's OK because it's more important to follow
1387 * rule #2.
1388 *
1389 * It turns out that knowing whether we want an "ECC-based" or "raw" read is not
1390 * easy. When reading a page, for example, the NAND Flash MTD code calls our
1391 * ecc.read_page or ecc.read_page_raw function. Thus, the fact that MTD wants an
1392 * ECC-based or raw view of the page is implicit in which function it calls
1393 * (there is a similar pair of ECC-based/raw functions for writing).
1394 */
1395static int gpmi_ecc_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
1396                                int page)
1397{
1398        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1399
1400        dev_dbg(this->dev, "page number is %d\n", page);
1401        /* clear the OOB buffer */
1402        memset(chip->oob_poi, ~0, mtd->oobsize);
1403
1404        /* Read out the conventional OOB. */
1405        chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1406        chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1407
1408        /*
1409         * Now, we want to make sure the block mark is correct. In the
1410         * non-transcribing case (!GPMI_IS_MX23()), we already have it.
1411         * Otherwise, we need to explicitly read it.
1412         */
1413        if (GPMI_IS_MX23(this)) {
1414                /* Read the block mark into the first byte of the OOB buffer. */
1415                chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1416                chip->oob_poi[0] = chip->read_byte(mtd);
1417        }
1418
1419        return 0;
1420}
1421
1422static int
1423gpmi_ecc_write_oob(struct mtd_info *mtd, struct nand_chip *chip, int page)
1424{
1425        struct mtd_oob_region of = { };
1426        int status = 0;
1427
1428        /* Do we have available oob area? */
1429        mtd_ooblayout_free(mtd, 0, &of);
1430        if (!of.length)
1431                return -EPERM;
1432
1433        if (!nand_is_slc(chip))
1434                return -EPERM;
1435
1436        chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize + of.offset, page);
1437        chip->write_buf(mtd, chip->oob_poi + of.offset, of.length);
1438        chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1439
1440        status = chip->waitfunc(mtd, chip);
1441        return status & NAND_STATUS_FAIL ? -EIO : 0;
1442}
1443
1444/*
1445 * This function reads a NAND page without involving the ECC engine (no HW
1446 * ECC correction).
1447 * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1448 * inline (interleaved with payload DATA), and do not align data chunk on
1449 * byte boundaries.
1450 * We thus need to take care moving the payload data and ECC bits stored in the
1451 * page into the provided buffers, which is why we're using gpmi_copy_bits.
1452 *
1453 * See set_geometry_by_ecc_info inline comments to have a full description
1454 * of the layout used by the GPMI controller.
1455 */
1456static int gpmi_ecc_read_page_raw(struct mtd_info *mtd,
1457                                  struct nand_chip *chip, uint8_t *buf,
1458                                  int oob_required, int page)
1459{
1460        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1461        struct bch_geometry *nfc_geo = &this->bch_geometry;
1462        int eccsize = nfc_geo->ecc_chunk_size;
1463        int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1464        u8 *tmp_buf = this->raw_buffer;
1465        size_t src_bit_off;
1466        size_t oob_bit_off;
1467        size_t oob_byte_off;
1468        uint8_t *oob = chip->oob_poi;
1469        int step;
1470
1471        chip->read_buf(mtd, tmp_buf,
1472                       mtd->writesize + mtd->oobsize);
1473
1474        /*
1475         * If required, swap the bad block marker and the data stored in the
1476         * metadata section, so that we don't wrongly consider a block as bad.
1477         *
1478         * See the layout description for a detailed explanation on why this
1479         * is needed.
1480         */
1481        if (this->swap_block_mark) {
1482                u8 swap = tmp_buf[0];
1483
1484                tmp_buf[0] = tmp_buf[mtd->writesize];
1485                tmp_buf[mtd->writesize] = swap;
1486        }
1487
1488        /*
1489         * Copy the metadata section into the oob buffer (this section is
1490         * guaranteed to be aligned on a byte boundary).
1491         */
1492        if (oob_required)
1493                memcpy(oob, tmp_buf, nfc_geo->metadata_size);
1494
1495        oob_bit_off = nfc_geo->metadata_size * 8;
1496        src_bit_off = oob_bit_off;
1497
1498        /* Extract interleaved payload data and ECC bits */
1499        for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1500                if (buf)
1501                        gpmi_copy_bits(buf, step * eccsize * 8,
1502                                       tmp_buf, src_bit_off,
1503                                       eccsize * 8);
1504                src_bit_off += eccsize * 8;
1505
1506                /* Align last ECC block to align a byte boundary */
1507                if (step == nfc_geo->ecc_chunk_count - 1 &&
1508                    (oob_bit_off + eccbits) % 8)
1509                        eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1510
1511                if (oob_required)
1512                        gpmi_copy_bits(oob, oob_bit_off,
1513                                       tmp_buf, src_bit_off,
1514                                       eccbits);
1515
1516                src_bit_off += eccbits;
1517                oob_bit_off += eccbits;
1518        }
1519
1520        if (oob_required) {
1521                oob_byte_off = oob_bit_off / 8;
1522
1523                if (oob_byte_off < mtd->oobsize)
1524                        memcpy(oob + oob_byte_off,
1525                               tmp_buf + mtd->writesize + oob_byte_off,
1526                               mtd->oobsize - oob_byte_off);
1527        }
1528
1529        return 0;
1530}
1531
1532/*
1533 * This function writes a NAND page without involving the ECC engine (no HW
1534 * ECC generation).
1535 * The tricky part in the GPMI/BCH controller is that it stores ECC bits
1536 * inline (interleaved with payload DATA), and do not align data chunk on
1537 * byte boundaries.
1538 * We thus need to take care moving the OOB area at the right place in the
1539 * final page, which is why we're using gpmi_copy_bits.
1540 *
1541 * See set_geometry_by_ecc_info inline comments to have a full description
1542 * of the layout used by the GPMI controller.
1543 */
1544static int gpmi_ecc_write_page_raw(struct mtd_info *mtd,
1545                                   struct nand_chip *chip,
1546                                   const uint8_t *buf,
1547                                   int oob_required, int page)
1548{
1549        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1550        struct bch_geometry *nfc_geo = &this->bch_geometry;
1551        int eccsize = nfc_geo->ecc_chunk_size;
1552        int eccbits = nfc_geo->ecc_strength * nfc_geo->gf_len;
1553        u8 *tmp_buf = this->raw_buffer;
1554        uint8_t *oob = chip->oob_poi;
1555        size_t dst_bit_off;
1556        size_t oob_bit_off;
1557        size_t oob_byte_off;
1558        int step;
1559
1560        /*
1561         * Initialize all bits to 1 in case we don't have a buffer for the
1562         * payload or oob data in order to leave unspecified bits of data
1563         * to their initial state.
1564         */
1565        if (!buf || !oob_required)
1566                memset(tmp_buf, 0xff, mtd->writesize + mtd->oobsize);
1567
1568        /*
1569         * First copy the metadata section (stored in oob buffer) at the
1570         * beginning of the page, as imposed by the GPMI layout.
1571         */
1572        memcpy(tmp_buf, oob, nfc_geo->metadata_size);
1573        oob_bit_off = nfc_geo->metadata_size * 8;
1574        dst_bit_off = oob_bit_off;
1575
1576        /* Interleave payload data and ECC bits */
1577        for (step = 0; step < nfc_geo->ecc_chunk_count; step++) {
1578                if (buf)
1579                        gpmi_copy_bits(tmp_buf, dst_bit_off,
1580                                       buf, step * eccsize * 8, eccsize * 8);
1581                dst_bit_off += eccsize * 8;
1582
1583                /* Align last ECC block to align a byte boundary */
1584                if (step == nfc_geo->ecc_chunk_count - 1 &&
1585                    (oob_bit_off + eccbits) % 8)
1586                        eccbits += 8 - ((oob_bit_off + eccbits) % 8);
1587
1588                if (oob_required)
1589                        gpmi_copy_bits(tmp_buf, dst_bit_off,
1590                                       oob, oob_bit_off, eccbits);
1591
1592                dst_bit_off += eccbits;
1593                oob_bit_off += eccbits;
1594        }
1595
1596        oob_byte_off = oob_bit_off / 8;
1597
1598        if (oob_required && oob_byte_off < mtd->oobsize)
1599                memcpy(tmp_buf + mtd->writesize + oob_byte_off,
1600                       oob + oob_byte_off, mtd->oobsize - oob_byte_off);
1601
1602        /*
1603         * If required, swap the bad block marker and the first byte of the
1604         * metadata section, so that we don't modify the bad block marker.
1605         *
1606         * See the layout description for a detailed explanation on why this
1607         * is needed.
1608         */
1609        if (this->swap_block_mark) {
1610                u8 swap = tmp_buf[0];
1611
1612                tmp_buf[0] = tmp_buf[mtd->writesize];
1613                tmp_buf[mtd->writesize] = swap;
1614        }
1615
1616        chip->write_buf(mtd, tmp_buf, mtd->writesize + mtd->oobsize);
1617
1618        return 0;
1619}
1620
1621static int gpmi_ecc_read_oob_raw(struct mtd_info *mtd, struct nand_chip *chip,
1622                                 int page)
1623{
1624        chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1625
1626        return gpmi_ecc_read_page_raw(mtd, chip, NULL, 1, page);
1627}
1628
1629static int gpmi_ecc_write_oob_raw(struct mtd_info *mtd, struct nand_chip *chip,
1630                                 int page)
1631{
1632        chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0, page);
1633
1634        return gpmi_ecc_write_page_raw(mtd, chip, NULL, 1, page);
1635}
1636
1637static int gpmi_block_markbad(struct mtd_info *mtd, loff_t ofs)
1638{
1639        struct nand_chip *chip = mtd_to_nand(mtd);
1640        struct gpmi_nand_data *this = nand_get_controller_data(chip);
1641        int ret = 0;
1642        uint8_t *block_mark;
1643        int column, page, status, chipnr;
1644
1645        chipnr = (int)(ofs >> chip->chip_shift);
1646        chip->select_chip(mtd, chipnr);
1647
1648        column = !GPMI_IS_MX23(this) ? mtd->writesize : 0;
1649
1650        /* Write the block mark. */
1651        block_mark = this->data_buffer_dma;
1652        block_mark[0] = 0; /* bad block marker */
1653
1654        /* Shift to get page */
1655        page = (int)(ofs >> chip->page_shift);
1656
1657        chip->cmdfunc(mtd, NAND_CMD_SEQIN, column, page);
1658        chip->write_buf(mtd, block_mark, 1);
1659        chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1660
1661        status = chip->waitfunc(mtd, chip);
1662        if (status & NAND_STATUS_FAIL)
1663                ret = -EIO;
1664
1665        chip->select_chip(mtd, -1);
1666
1667        return ret;
1668}
1669
1670static int nand_boot_set_geometry(struct gpmi_nand_data *this)
1671{
1672        struct boot_rom_geometry *geometry = &this->rom_geometry;
1673
1674        /*
1675         * Set the boot block stride size.
1676         *
1677         * In principle, we should be reading this from the OTP bits, since
1678         * that's where the ROM is going to get it. In fact, we don't have any
1679         * way to read the OTP bits, so we go with the default and hope for the
1680         * best.
1681         */
1682        geometry->stride_size_in_pages = 64;
1683
1684        /*
1685         * Set the search area stride exponent.
1686         *
1687         * In principle, we should be reading this from the OTP bits, since
1688         * that's where the ROM is going to get it. In fact, we don't have any
1689         * way to read the OTP bits, so we go with the default and hope for the
1690         * best.
1691         */
1692        geometry->search_area_stride_exponent = 2;
1693        return 0;
1694}
1695
1696static const char  *fingerprint = "STMP";
1697static int mx23_check_transcription_stamp(struct gpmi_nand_data *this)
1698{
1699        struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1700        struct device *dev = this->dev;
1701        struct nand_chip *chip = &this->nand;
1702        struct mtd_info *mtd = nand_to_mtd(chip);
1703        unsigned int search_area_size_in_strides;
1704        unsigned int stride;
1705        unsigned int page;
1706        uint8_t *buffer = chip->buffers->databuf;
1707        int saved_chip_number;
1708        int found_an_ncb_fingerprint = false;
1709
1710        /* Compute the number of strides in a search area. */
1711        search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1712
1713        saved_chip_number = this->current_chip;
1714        chip->select_chip(mtd, 0);
1715
1716        /*
1717         * Loop through the first search area, looking for the NCB fingerprint.
1718         */
1719        dev_dbg(dev, "Scanning for an NCB fingerprint...\n");
1720
1721        for (stride = 0; stride < search_area_size_in_strides; stride++) {
1722                /* Compute the page addresses. */
1723                page = stride * rom_geo->stride_size_in_pages;
1724
1725                dev_dbg(dev, "Looking for a fingerprint in page 0x%x\n", page);
1726
1727                /*
1728                 * Read the NCB fingerprint. The fingerprint is four bytes long
1729                 * and starts in the 12th byte of the page.
1730                 */
1731                chip->cmdfunc(mtd, NAND_CMD_READ0, 12, page);
1732                chip->read_buf(mtd, buffer, strlen(fingerprint));
1733
1734                /* Look for the fingerprint. */
1735                if (!memcmp(buffer, fingerprint, strlen(fingerprint))) {
1736                        found_an_ncb_fingerprint = true;
1737                        break;
1738                }
1739
1740        }
1741
1742        chip->select_chip(mtd, saved_chip_number);
1743
1744        if (found_an_ncb_fingerprint)
1745                dev_dbg(dev, "\tFound a fingerprint\n");
1746        else
1747                dev_dbg(dev, "\tNo fingerprint found\n");
1748        return found_an_ncb_fingerprint;
1749}
1750
1751/* Writes a transcription stamp. */
1752static int mx23_write_transcription_stamp(struct gpmi_nand_data *this)
1753{
1754        struct device *dev = this->dev;
1755        struct boot_rom_geometry *rom_geo = &this->rom_geometry;
1756        struct nand_chip *chip = &this->nand;
1757        struct mtd_info *mtd = nand_to_mtd(chip);
1758        unsigned int block_size_in_pages;
1759        unsigned int search_area_size_in_strides;
1760        unsigned int search_area_size_in_pages;
1761        unsigned int search_area_size_in_blocks;
1762        unsigned int block;
1763        unsigned int stride;
1764        unsigned int page;
1765        uint8_t      *buffer = chip->buffers->databuf;
1766        int saved_chip_number;
1767        int status;
1768
1769        /* Compute the search area geometry. */
1770        block_size_in_pages = mtd->erasesize / mtd->writesize;
1771        search_area_size_in_strides = 1 << rom_geo->search_area_stride_exponent;
1772        search_area_size_in_pages = search_area_size_in_strides *
1773                                        rom_geo->stride_size_in_pages;
1774        search_area_size_in_blocks =
1775                  (search_area_size_in_pages + (block_size_in_pages - 1)) /
1776                                    block_size_in_pages;
1777
1778        dev_dbg(dev, "Search Area Geometry :\n");
1779        dev_dbg(dev, "\tin Blocks : %u\n", search_area_size_in_blocks);
1780        dev_dbg(dev, "\tin Strides: %u\n", search_area_size_in_strides);
1781        dev_dbg(dev, "\tin Pages  : %u\n", search_area_size_in_pages);
1782
1783        /* Select chip 0. */
1784        saved_chip_number = this->current_chip;
1785        chip->select_chip(mtd, 0);
1786
1787        /* Loop over blocks in the first search area, erasing them. */
1788        dev_dbg(dev, "Erasing the search area...\n");
1789
1790        for (block = 0; block < search_area_size_in_blocks; block++) {
1791                /* Compute the page address. */
1792                page = block * block_size_in_pages;
1793
1794                /* Erase this block. */
1795                dev_dbg(dev, "\tErasing block 0x%x\n", block);
1796                chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1797                chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1798
1799                /* Wait for the erase to finish. */
1800                status = chip->waitfunc(mtd, chip);
1801                if (status & NAND_STATUS_FAIL)
1802                        dev_err(dev, "[%s] Erase failed.\n", __func__);
1803        }
1804
1805        /* Write the NCB fingerprint into the page buffer. */
1806        memset(buffer, ~0, mtd->writesize);
1807        memcpy(buffer + 12, fingerprint, strlen(fingerprint));
1808
1809        /* Loop through the first search area, writing NCB fingerprints. */
1810        dev_dbg(dev, "Writing NCB fingerprints...\n");
1811        for (stride = 0; stride < search_area_size_in_strides; stride++) {
1812                /* Compute the page addresses. */
1813                page = stride * rom_geo->stride_size_in_pages;
1814
1815                /* Write the first page of the current stride. */
1816                dev_dbg(dev, "Writing an NCB fingerprint in page 0x%x\n", page);
1817                chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
1818                chip->ecc.write_page_raw(mtd, chip, buffer, 0, page);
1819                chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1820
1821                /* Wait for the write to finish. */
1822                status = chip->waitfunc(mtd, chip);
1823                if (status & NAND_STATUS_FAIL)
1824                        dev_err(dev, "[%s] Write failed.\n", __func__);
1825        }
1826
1827        /* Deselect chip 0. */
1828        chip->select_chip(mtd, saved_chip_number);
1829        return 0;
1830}
1831
1832static int mx23_boot_init(struct gpmi_nand_data  *this)
1833{
1834        struct device *dev = this->dev;
1835        struct nand_chip *chip = &this->nand;
1836        struct mtd_info *mtd = nand_to_mtd(chip);
1837        unsigned int block_count;
1838        unsigned int block;
1839        int     chipnr;
1840        int     page;
1841        loff_t  byte;
1842        uint8_t block_mark;
1843        int     ret = 0;
1844
1845        /*
1846         * If control arrives here, we can't use block mark swapping, which
1847         * means we're forced to use transcription. First, scan for the
1848         * transcription stamp. If we find it, then we don't have to do
1849         * anything -- the block marks are already transcribed.
1850         */
1851        if (mx23_check_transcription_stamp(this))
1852                return 0;
1853
1854        /*
1855         * If control arrives here, we couldn't find a transcription stamp, so
1856         * so we presume the block marks are in the conventional location.
1857         */
1858        dev_dbg(dev, "Transcribing bad block marks...\n");
1859
1860        /* Compute the number of blocks in the entire medium. */
1861        block_count = chip->chipsize >> chip->phys_erase_shift;
1862
1863        /*
1864         * Loop over all the blocks in the medium, transcribing block marks as
1865         * we go.
1866         */
1867        for (block = 0; block < block_count; block++) {
1868                /*
1869                 * Compute the chip, page and byte addresses for this block's
1870                 * conventional mark.
1871                 */
1872                chipnr = block >> (chip->chip_shift - chip->phys_erase_shift);
1873                page = block << (chip->phys_erase_shift - chip->page_shift);
1874                byte = block <<  chip->phys_erase_shift;
1875
1876                /* Send the command to read the conventional block mark. */
1877                chip->select_chip(mtd, chipnr);
1878                chip->cmdfunc(mtd, NAND_CMD_READ0, mtd->writesize, page);
1879                block_mark = chip->read_byte(mtd);
1880                chip->select_chip(mtd, -1);
1881
1882                /*
1883                 * Check if the block is marked bad. If so, we need to mark it
1884                 * again, but this time the result will be a mark in the
1885                 * location where we transcribe block marks.
1886                 */
1887                if (block_mark != 0xff) {
1888                        dev_dbg(dev, "Transcribing mark in block %u\n", block);
1889                        ret = chip->block_markbad(mtd, byte);
1890                        if (ret)
1891                                dev_err(dev,
1892                                        "Failed to mark block bad with ret %d\n",
1893                                        ret);
1894                }
1895        }
1896
1897        /* Write the stamp that indicates we've transcribed the block marks. */
1898        mx23_write_transcription_stamp(this);
1899        return 0;
1900}
1901
1902static int nand_boot_init(struct gpmi_nand_data  *this)
1903{
1904        nand_boot_set_geometry(this);
1905
1906        /* This is ROM arch-specific initilization before the BBT scanning. */
1907        if (GPMI_IS_MX23(this))
1908                return mx23_boot_init(this);
1909        return 0;
1910}
1911
1912static int gpmi_set_geometry(struct gpmi_nand_data *this)
1913{
1914        int ret;
1915
1916        /* Free the temporary DMA memory for reading ID. */
1917        gpmi_free_dma_buffer(this);
1918
1919        /* Set up the NFC geometry which is used by BCH. */
1920        ret = bch_set_geometry(this);
1921        if (ret) {
1922                dev_err(this->dev, "Error setting BCH geometry : %d\n", ret);
1923                return ret;
1924        }
1925
1926        /* Alloc the new DMA buffers according to the pagesize and oobsize */
1927        return gpmi_alloc_dma_buffer(this);
1928}
1929
1930static void gpmi_nand_exit(struct gpmi_nand_data *this)
1931{
1932        nand_release(nand_to_mtd(&this->nand));
1933        gpmi_free_dma_buffer(this);
1934}
1935
1936static int gpmi_init_last(struct gpmi_nand_data *this)
1937{
1938        struct nand_chip *chip = &this->nand;
1939        struct mtd_info *mtd = nand_to_mtd(chip);
1940        struct nand_ecc_ctrl *ecc = &chip->ecc;
1941        struct bch_geometry *bch_geo = &this->bch_geometry;
1942        int ret;
1943
1944        /* Set up the medium geometry */
1945        ret = gpmi_set_geometry(this);
1946        if (ret)
1947                return ret;
1948
1949        /* Init the nand_ecc_ctrl{} */
1950        ecc->read_page  = gpmi_ecc_read_page;
1951        ecc->write_page = gpmi_ecc_write_page;
1952        ecc->read_oob   = gpmi_ecc_read_oob;
1953        ecc->write_oob  = gpmi_ecc_write_oob;
1954        ecc->read_page_raw = gpmi_ecc_read_page_raw;
1955        ecc->write_page_raw = gpmi_ecc_write_page_raw;
1956        ecc->read_oob_raw = gpmi_ecc_read_oob_raw;
1957        ecc->write_oob_raw = gpmi_ecc_write_oob_raw;
1958        ecc->mode       = NAND_ECC_HW;
1959        ecc->size       = bch_geo->ecc_chunk_size;
1960        ecc->strength   = bch_geo->ecc_strength;
1961        mtd_set_ooblayout(mtd, &gpmi_ooblayout_ops);
1962
1963        /*
1964         * We only enable the subpage read when:
1965         *  (1) the chip is imx6, and
1966         *  (2) the size of the ECC parity is byte aligned.
1967         */
1968        if (GPMI_IS_MX6(this) &&
1969                ((bch_geo->gf_len * bch_geo->ecc_strength) % 8) == 0) {
1970                ecc->read_subpage = gpmi_ecc_read_subpage;
1971                chip->options |= NAND_SUBPAGE_READ;
1972        }
1973
1974        /*
1975         * Can we enable the extra features? such as EDO or Sync mode.
1976         *
1977         * We do not check the return value now. That's means if we fail in
1978         * enable the extra features, we still can run in the normal way.
1979         */
1980        gpmi_extra_init(this);
1981
1982        return 0;
1983}
1984
1985static int gpmi_nand_init(struct gpmi_nand_data *this)
1986{
1987        struct nand_chip *chip = &this->nand;
1988        struct mtd_info  *mtd = nand_to_mtd(chip);
1989        int ret;
1990
1991        /* init current chip */
1992        this->current_chip      = -1;
1993
1994        /* init the MTD data structures */
1995        mtd->name               = "gpmi-nand";
1996        mtd->dev.parent         = this->dev;
1997
1998        /* init the nand_chip{}, we don't support a 16-bit NAND Flash bus. */
1999        nand_set_controller_data(chip, this);
2000        nand_set_flash_node(chip, this->pdev->dev.of_node);
2001        chip->select_chip       = gpmi_select_chip;
2002        chip->cmd_ctrl          = gpmi_cmd_ctrl;
2003        chip->dev_ready         = gpmi_dev_ready;
2004        chip->read_byte         = gpmi_read_byte;
2005        chip->read_buf          = gpmi_read_buf;
2006        chip->write_buf         = gpmi_write_buf;
2007        chip->badblock_pattern  = &gpmi_bbt_descr;
2008        chip->block_markbad     = gpmi_block_markbad;
2009        chip->options           |= NAND_NO_SUBPAGE_WRITE;
2010
2011        /* Set up swap_block_mark, must be set before the gpmi_set_geometry() */
2012        this->swap_block_mark = !GPMI_IS_MX23(this);
2013
2014        /*
2015         * Allocate a temporary DMA buffer for reading ID in the
2016         * nand_scan_ident().
2017         */
2018        this->bch_geometry.payload_size = 1024;
2019        this->bch_geometry.auxiliary_size = 128;
2020        ret = gpmi_alloc_dma_buffer(this);
2021        if (ret)
2022                goto err_out;
2023
2024        ret = nand_scan_ident(mtd, GPMI_IS_MX6(this) ? 2 : 1, NULL);
2025        if (ret)
2026                goto err_out;
2027
2028        if (chip->bbt_options & NAND_BBT_USE_FLASH) {
2029                chip->bbt_options |= NAND_BBT_NO_OOB;
2030
2031                if (of_property_read_bool(this->dev->of_node,
2032                                                "fsl,no-blockmark-swap"))
2033                        this->swap_block_mark = false;
2034        }
2035        dev_dbg(this->dev, "Blockmark swapping %sabled\n",
2036                this->swap_block_mark ? "en" : "dis");
2037
2038        ret = gpmi_init_last(this);
2039        if (ret)
2040                goto err_out;
2041
2042        chip->options |= NAND_SKIP_BBTSCAN;
2043        ret = nand_scan_tail(mtd);
2044        if (ret)
2045                goto err_out;
2046
2047        ret = nand_boot_init(this);
2048        if (ret)
2049                goto err_out;
2050        ret = chip->scan_bbt(mtd);
2051        if (ret)
2052                goto err_out;
2053
2054        ret = mtd_device_register(mtd, NULL, 0);
2055        if (ret)
2056                goto err_out;
2057        return 0;
2058
2059err_out:
2060        gpmi_nand_exit(this);
2061        return ret;
2062}
2063
2064static const struct of_device_id gpmi_nand_id_table[] = {
2065        {
2066                .compatible = "fsl,imx23-gpmi-nand",
2067                .data = &gpmi_devdata_imx23,
2068        }, {
2069                .compatible = "fsl,imx28-gpmi-nand",
2070                .data = &gpmi_devdata_imx28,
2071        }, {
2072                .compatible = "fsl,imx6q-gpmi-nand",
2073                .data = &gpmi_devdata_imx6q,
2074        }, {
2075                .compatible = "fsl,imx6sx-gpmi-nand",
2076                .data = &gpmi_devdata_imx6sx,
2077        }, {}
2078};
2079MODULE_DEVICE_TABLE(of, gpmi_nand_id_table);
2080
2081static int gpmi_nand_probe(struct platform_device *pdev)
2082{
2083        struct gpmi_nand_data *this;
2084        const struct of_device_id *of_id;
2085        int ret;
2086
2087        this = devm_kzalloc(&pdev->dev, sizeof(*this), GFP_KERNEL);
2088        if (!this)
2089                return -ENOMEM;
2090
2091        of_id = of_match_device(gpmi_nand_id_table, &pdev->dev);
2092        if (of_id) {
2093                this->devdata = of_id->data;
2094        } else {
2095                dev_err(&pdev->dev, "Failed to find the right device id.\n");
2096                return -ENODEV;
2097        }
2098
2099        platform_set_drvdata(pdev, this);
2100        this->pdev  = pdev;
2101        this->dev   = &pdev->dev;
2102
2103        ret = acquire_resources(this);
2104        if (ret)
2105                goto exit_acquire_resources;
2106
2107        ret = init_hardware(this);
2108        if (ret)
2109                goto exit_nfc_init;
2110
2111        ret = gpmi_nand_init(this);
2112        if (ret)
2113                goto exit_nfc_init;
2114
2115        dev_info(this->dev, "driver registered.\n");
2116
2117        return 0;
2118
2119exit_nfc_init:
2120        release_resources(this);
2121exit_acquire_resources:
2122
2123        return ret;
2124}
2125
2126static int gpmi_nand_remove(struct platform_device *pdev)
2127{
2128        struct gpmi_nand_data *this = platform_get_drvdata(pdev);
2129
2130        gpmi_nand_exit(this);
2131        release_resources(this);
2132        return 0;
2133}
2134
2135#ifdef CONFIG_PM_SLEEP
2136static int gpmi_pm_suspend(struct device *dev)
2137{
2138        struct gpmi_nand_data *this = dev_get_drvdata(dev);
2139
2140        release_dma_channels(this);
2141        return 0;
2142}
2143
2144static int gpmi_pm_resume(struct device *dev)
2145{
2146        struct gpmi_nand_data *this = dev_get_drvdata(dev);
2147        int ret;
2148
2149        ret = acquire_dma_channels(this);
2150        if (ret < 0)
2151                return ret;
2152
2153        /* re-init the GPMI registers */
2154        this->flags &= ~GPMI_TIMING_INIT_OK;
2155        ret = gpmi_init(this);
2156        if (ret) {
2157                dev_err(this->dev, "Error setting GPMI : %d\n", ret);
2158                return ret;
2159        }
2160
2161        /* re-init the BCH registers */
2162        ret = bch_set_geometry(this);
2163        if (ret) {
2164                dev_err(this->dev, "Error setting BCH : %d\n", ret);
2165                return ret;
2166        }
2167
2168        /* re-init others */
2169        gpmi_extra_init(this);
2170
2171        return 0;
2172}
2173#endif /* CONFIG_PM_SLEEP */
2174
2175static const struct dev_pm_ops gpmi_pm_ops = {
2176        SET_SYSTEM_SLEEP_PM_OPS(gpmi_pm_suspend, gpmi_pm_resume)
2177};
2178
2179static struct platform_driver gpmi_nand_driver = {
2180        .driver = {
2181                .name = "gpmi-nand",
2182                .pm = &gpmi_pm_ops,
2183                .of_match_table = gpmi_nand_id_table,
2184        },
2185        .probe   = gpmi_nand_probe,
2186        .remove  = gpmi_nand_remove,
2187};
2188module_platform_driver(gpmi_nand_driver);
2189
2190MODULE_AUTHOR("Freescale Semiconductor, Inc.");
2191MODULE_DESCRIPTION("i.MX GPMI NAND Flash Controller Driver");
2192MODULE_LICENSE("GPL");
2193