uboot/drivers/mtd/spi/spi-nor-core.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Based on m25p80.c, by Mike Lavender (mike@steroidmicros.com), with
   4 * influence from lart.c (Abraham Van Der Merwe) and mtd_dataflash.c
   5 *
   6 * Copyright (C) 2005, Intec Automation Inc.
   7 * Copyright (C) 2014, Freescale Semiconductor, Inc.
   8 *
   9 * Synced from Linux v4.19
  10 */
  11
  12#include <common.h>
  13#include <flash.h>
  14#include <log.h>
  15#include <watchdog.h>
  16#include <dm.h>
  17#include <dm/device_compat.h>
  18#include <dm/devres.h>
  19#include <linux/bitops.h>
  20#include <linux/err.h>
  21#include <linux/errno.h>
  22#include <linux/log2.h>
  23#include <linux/math64.h>
  24#include <linux/sizes.h>
  25#include <linux/bitfield.h>
  26#include <linux/delay.h>
  27
  28#include <linux/mtd/mtd.h>
  29#include <linux/mtd/spi-nor.h>
  30#include <mtd/cfi_flash.h>
  31#include <spi-mem.h>
  32#include <spi.h>
  33
  34#include "sf_internal.h"
  35
  36/* Define max times to check status register before we give up. */
  37
  38/*
  39 * For everything but full-chip erase; probably could be much smaller, but kept
  40 * around for safety for now
  41 */
  42
  43#define HZ                                      CONFIG_SYS_HZ
  44
  45#define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
  46
  47#define ROUND_UP_TO(x, y)       (((x) + (y) - 1) / (y) * (y))
  48
  49struct sfdp_parameter_header {
  50        u8              id_lsb;
  51        u8              minor;
  52        u8              major;
  53        u8              length; /* in double words */
  54        u8              parameter_table_pointer[3]; /* byte address */
  55        u8              id_msb;
  56};
  57
  58#define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
  59#define SFDP_PARAM_HEADER_PTP(p) \
  60        (((p)->parameter_table_pointer[2] << 16) | \
  61         ((p)->parameter_table_pointer[1] <<  8) | \
  62         ((p)->parameter_table_pointer[0] <<  0))
  63
  64#define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
  65#define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
  66#define SFDP_SST_ID             0x01bf  /* Manufacturer specific Table */
  67#define SFDP_PROFILE1_ID        0xff05  /* xSPI Profile 1.0 Table */
  68
  69#define SFDP_SIGNATURE          0x50444653U
  70#define SFDP_JESD216_MAJOR      1
  71#define SFDP_JESD216_MINOR      0
  72#define SFDP_JESD216A_MINOR     5
  73#define SFDP_JESD216B_MINOR     6
  74
  75struct sfdp_header {
  76        u32             signature; /* Ox50444653U <=> "SFDP" */
  77        u8              minor;
  78        u8              major;
  79        u8              nph; /* 0-base number of parameter headers */
  80        u8              unused;
  81
  82        /* Basic Flash Parameter Table. */
  83        struct sfdp_parameter_header    bfpt_header;
  84};
  85
  86/* Basic Flash Parameter Table */
  87
  88/*
  89 * JESD216 rev D defines a Basic Flash Parameter Table of 20 DWORDs.
  90 * They are indexed from 1 but C arrays are indexed from 0.
  91 */
  92#define BFPT_DWORD(i)           ((i) - 1)
  93#define BFPT_DWORD_MAX          20
  94
  95/* The first version of JESB216 defined only 9 DWORDs. */
  96#define BFPT_DWORD_MAX_JESD216                  9
  97#define BFPT_DWORD_MAX_JESD216B                 16
  98
  99/* 1st DWORD. */
 100#define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
 101#define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
 102#define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
 103#define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
 104#define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
 105#define BFPT_DWORD1_DTR                         BIT(19)
 106#define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
 107#define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
 108#define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
 109
 110/* 5th DWORD. */
 111#define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
 112#define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
 113
 114/* 11th DWORD. */
 115#define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
 116#define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
 117
 118/* 15th DWORD. */
 119
 120/*
 121 * (from JESD216 rev B)
 122 * Quad Enable Requirements (QER):
 123 * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
 124 *         reads based on instruction. DQ3/HOLD# functions are hold during
 125 *         instruction phase.
 126 * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
 127 *         two data bytes where bit 1 of the second byte is one.
 128 *         [...]
 129 *         Writing only one byte to the status register has the side-effect of
 130 *         clearing status register 2, including the QE bit. The 100b code is
 131 *         used if writing one byte to the status register does not modify
 132 *         status register 2.
 133 * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
 134 *         one data byte where bit 6 is one.
 135 *         [...]
 136 * - 011b: QE is bit 7 of status register 2. It is set via Write status
 137 *         register 2 instruction 3Eh with one data byte where bit 7 is one.
 138 *         [...]
 139 *         The status register 2 is read using instruction 3Fh.
 140 * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
 141 *         two data bytes where bit 1 of the second byte is one.
 142 *         [...]
 143 *         In contrast to the 001b code, writing one byte to the status
 144 *         register does not modify status register 2.
 145 * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
 146 *         Read Status instruction 05h. Status register2 is read using
 147 *         instruction 35h. QE is set via Writ Status instruction 01h with
 148 *         two data bytes where bit 1 of the second byte is one.
 149 *         [...]
 150 */
 151#define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
 152#define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
 153#define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
 154#define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
 155#define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
 156#define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
 157#define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
 158
 159#define BFPT_DWORD16_SOFT_RST                   BIT(12)
 160
 161#define BFPT_DWORD18_CMD_EXT_MASK               GENMASK(30, 29)
 162#define BFPT_DWORD18_CMD_EXT_REP                (0x0UL << 29) /* Repeat */
 163#define BFPT_DWORD18_CMD_EXT_INV                (0x1UL << 29) /* Invert */
 164#define BFPT_DWORD18_CMD_EXT_RES                (0x2UL << 29) /* Reserved */
 165#define BFPT_DWORD18_CMD_EXT_16B                (0x3UL << 29) /* 16-bit opcode */
 166
 167/* xSPI Profile 1.0 table (from JESD216D.01). */
 168#define PROFILE1_DWORD1_RD_FAST_CMD             GENMASK(15, 8)
 169#define PROFILE1_DWORD1_RDSR_DUMMY              BIT(28)
 170#define PROFILE1_DWORD1_RDSR_ADDR_BYTES         BIT(29)
 171#define PROFILE1_DWORD4_DUMMY_200MHZ            GENMASK(11, 7)
 172#define PROFILE1_DWORD5_DUMMY_166MHZ            GENMASK(31, 27)
 173#define PROFILE1_DWORD5_DUMMY_133MHZ            GENMASK(21, 17)
 174#define PROFILE1_DWORD5_DUMMY_100MHZ            GENMASK(11, 7)
 175#define PROFILE1_DUMMY_DEFAULT                  20
 176
 177struct sfdp_bfpt {
 178        u32     dwords[BFPT_DWORD_MAX];
 179};
 180
 181/**
 182 * struct spi_nor_fixups - SPI NOR fixup hooks
 183 * @default_init: called after default flash parameters init. Used to tweak
 184 *                flash parameters when information provided by the flash_info
 185 *                table is incomplete or wrong.
 186 * @post_bfpt: called after the BFPT table has been parsed
 187 * @post_sfdp: called after SFDP has been parsed (is also called for SPI NORs
 188 *             that do not support RDSFDP). Typically used to tweak various
 189 *             parameters that could not be extracted by other means (i.e.
 190 *             when information provided by the SFDP/flash_info tables are
 191 *             incomplete or wrong).
 192 *
 193 * Those hooks can be used to tweak the SPI NOR configuration when the SFDP
 194 * table is broken or not available.
 195 */
 196struct spi_nor_fixups {
 197        void (*default_init)(struct spi_nor *nor);
 198        int (*post_bfpt)(struct spi_nor *nor,
 199                         const struct sfdp_parameter_header *bfpt_header,
 200                         const struct sfdp_bfpt *bfpt,
 201                         struct spi_nor_flash_parameter *params);
 202        void (*post_sfdp)(struct spi_nor *nor,
 203                          struct spi_nor_flash_parameter *params);
 204};
 205
 206#define SPI_NOR_SRST_SLEEP_LEN                  200
 207
 208/**
 209 * spi_nor_get_cmd_ext() - Get the command opcode extension based on the
 210 *                         extension type.
 211 * @nor:                pointer to a 'struct spi_nor'
 212 * @op:                 pointer to the 'struct spi_mem_op' whose properties
 213 *                      need to be initialized.
 214 *
 215 * Right now, only "repeat" and "invert" are supported.
 216 *
 217 * Return: The opcode extension.
 218 */
 219static u8 spi_nor_get_cmd_ext(const struct spi_nor *nor,
 220                              const struct spi_mem_op *op)
 221{
 222        switch (nor->cmd_ext_type) {
 223        case SPI_NOR_EXT_INVERT:
 224                return ~op->cmd.opcode;
 225
 226        case SPI_NOR_EXT_REPEAT:
 227                return op->cmd.opcode;
 228
 229        default:
 230                dev_dbg(nor->dev, "Unknown command extension type\n");
 231                return 0;
 232        }
 233}
 234
 235/**
 236 * spi_nor_setup_op() - Set up common properties of a spi-mem op.
 237 * @nor:                pointer to a 'struct spi_nor'
 238 * @op:                 pointer to the 'struct spi_mem_op' whose properties
 239 *                      need to be initialized.
 240 * @proto:              the protocol from which the properties need to be set.
 241 */
 242static void spi_nor_setup_op(const struct spi_nor *nor,
 243                             struct spi_mem_op *op,
 244                             const enum spi_nor_protocol proto)
 245{
 246        u8 ext;
 247
 248        op->cmd.buswidth = spi_nor_get_protocol_inst_nbits(proto);
 249
 250        if (op->addr.nbytes)
 251                op->addr.buswidth = spi_nor_get_protocol_addr_nbits(proto);
 252
 253        if (op->dummy.nbytes)
 254                op->dummy.buswidth = spi_nor_get_protocol_addr_nbits(proto);
 255
 256        if (op->data.nbytes)
 257                op->data.buswidth = spi_nor_get_protocol_data_nbits(proto);
 258
 259        if (spi_nor_protocol_is_dtr(proto)) {
 260                /*
 261                 * spi-mem supports mixed DTR modes, but right now we can only
 262                 * have all phases either DTR or STR. IOW, spi-mem can have
 263                 * something like 4S-4D-4D, but spi-nor can't. So, set all 4
 264                 * phases to either DTR or STR.
 265                 */
 266                op->cmd.dtr = op->addr.dtr = op->dummy.dtr =
 267                        op->data.dtr = true;
 268
 269                /* 2 bytes per clock cycle in DTR mode. */
 270                op->dummy.nbytes *= 2;
 271
 272                ext = spi_nor_get_cmd_ext(nor, op);
 273                op->cmd.opcode = (op->cmd.opcode << 8) | ext;
 274                op->cmd.nbytes = 2;
 275        }
 276}
 277
 278static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
 279                *op, void *buf)
 280{
 281        if (op->data.dir == SPI_MEM_DATA_IN)
 282                op->data.buf.in = buf;
 283        else
 284                op->data.buf.out = buf;
 285        return spi_mem_exec_op(nor->spi, op);
 286}
 287
 288static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
 289{
 290        struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 0),
 291                                          SPI_MEM_OP_NO_ADDR,
 292                                          SPI_MEM_OP_NO_DUMMY,
 293                                          SPI_MEM_OP_DATA_IN(len, NULL, 0));
 294        int ret;
 295
 296        spi_nor_setup_op(nor, &op, nor->reg_proto);
 297
 298        ret = spi_nor_read_write_reg(nor, &op, val);
 299        if (ret < 0)
 300                dev_dbg(nor->dev, "error %d reading %x\n", ret, code);
 301
 302        return ret;
 303}
 304
 305static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
 306{
 307        struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 0),
 308                                          SPI_MEM_OP_NO_ADDR,
 309                                          SPI_MEM_OP_NO_DUMMY,
 310                                          SPI_MEM_OP_DATA_OUT(len, NULL, 0));
 311
 312        spi_nor_setup_op(nor, &op, nor->reg_proto);
 313
 314        if (len == 0)
 315                op.data.dir = SPI_MEM_NO_DATA;
 316
 317        return spi_nor_read_write_reg(nor, &op, buf);
 318}
 319
 320#ifdef CONFIG_SPI_FLASH_SPANSION
 321static int spansion_read_any_reg(struct spi_nor *nor, u32 addr, u8 dummy,
 322                                 u8 *val)
 323{
 324        struct spi_mem_op op =
 325                        SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDAR, 1),
 326                                   SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
 327                                   SPI_MEM_OP_DUMMY(dummy / 8, 1),
 328                                   SPI_MEM_OP_DATA_IN(1, NULL, 1));
 329
 330        return spi_nor_read_write_reg(nor, &op, val);
 331}
 332
 333static int spansion_write_any_reg(struct spi_nor *nor, u32 addr, u8 val)
 334{
 335        struct spi_mem_op op =
 336                        SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRAR, 1),
 337                                   SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
 338                                   SPI_MEM_OP_NO_DUMMY,
 339                                   SPI_MEM_OP_DATA_OUT(1, NULL, 1));
 340
 341        return spi_nor_read_write_reg(nor, &op, &val);
 342}
 343#endif
 344
 345static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
 346                                 u_char *buf)
 347{
 348        struct spi_mem_op op =
 349                        SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 0),
 350                                   SPI_MEM_OP_ADDR(nor->addr_width, from, 0),
 351                                   SPI_MEM_OP_DUMMY(nor->read_dummy, 0),
 352                                   SPI_MEM_OP_DATA_IN(len, buf, 0));
 353        size_t remaining = len;
 354        int ret;
 355
 356        spi_nor_setup_op(nor, &op, nor->read_proto);
 357
 358        /* convert the dummy cycles to the number of bytes */
 359        op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
 360        if (spi_nor_protocol_is_dtr(nor->read_proto))
 361                op.dummy.nbytes *= 2;
 362
 363        while (remaining) {
 364                op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
 365                ret = spi_mem_adjust_op_size(nor->spi, &op);
 366                if (ret)
 367                        return ret;
 368
 369                ret = spi_mem_exec_op(nor->spi, &op);
 370                if (ret)
 371                        return ret;
 372
 373                op.addr.val += op.data.nbytes;
 374                remaining -= op.data.nbytes;
 375                op.data.buf.in += op.data.nbytes;
 376        }
 377
 378        return len;
 379}
 380
 381static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
 382                                  const u_char *buf)
 383{
 384        struct spi_mem_op op =
 385                        SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 0),
 386                                   SPI_MEM_OP_ADDR(nor->addr_width, to, 0),
 387                                   SPI_MEM_OP_NO_DUMMY,
 388                                   SPI_MEM_OP_DATA_OUT(len, buf, 0));
 389        int ret;
 390
 391        if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
 392                op.addr.nbytes = 0;
 393
 394        spi_nor_setup_op(nor, &op, nor->write_proto);
 395
 396        ret = spi_mem_adjust_op_size(nor->spi, &op);
 397        if (ret)
 398                return ret;
 399        op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
 400
 401        ret = spi_mem_exec_op(nor->spi, &op);
 402        if (ret)
 403                return ret;
 404
 405        return op.data.nbytes;
 406}
 407
 408/*
 409 * Read the status register, returning its value in the location
 410 * Return the status register value.
 411 * Returns negative if error occurred.
 412 */
 413static int read_sr(struct spi_nor *nor)
 414{
 415        struct spi_mem_op op;
 416        int ret;
 417        u8 val[2];
 418        u8 addr_nbytes, dummy;
 419
 420        if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
 421                addr_nbytes = nor->rdsr_addr_nbytes;
 422                dummy = nor->rdsr_dummy;
 423        } else {
 424                addr_nbytes = 0;
 425                dummy = 0;
 426        }
 427
 428        op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR, 0),
 429                                           SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
 430                                           SPI_MEM_OP_DUMMY(dummy, 0),
 431                                           SPI_MEM_OP_DATA_IN(1, NULL, 0));
 432
 433        spi_nor_setup_op(nor, &op, nor->reg_proto);
 434
 435        /*
 436         * We don't want to read only one byte in DTR mode. So, read 2 and then
 437         * discard the second byte.
 438         */
 439        if (spi_nor_protocol_is_dtr(nor->reg_proto))
 440                op.data.nbytes = 2;
 441
 442        ret = spi_nor_read_write_reg(nor, &op, val);
 443        if (ret < 0) {
 444                pr_debug("error %d reading SR\n", (int)ret);
 445                return ret;
 446        }
 447
 448        return *val;
 449}
 450
 451/*
 452 * Read the flag status register, returning its value in the location
 453 * Return the status register value.
 454 * Returns negative if error occurred.
 455 */
 456static int read_fsr(struct spi_nor *nor)
 457{
 458        struct spi_mem_op op;
 459        int ret;
 460        u8 val[2];
 461        u8 addr_nbytes, dummy;
 462
 463        if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
 464                addr_nbytes = nor->rdsr_addr_nbytes;
 465                dummy = nor->rdsr_dummy;
 466        } else {
 467                addr_nbytes = 0;
 468                dummy = 0;
 469        }
 470
 471        op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDFSR, 0),
 472                                           SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
 473                                           SPI_MEM_OP_DUMMY(dummy, 0),
 474                                           SPI_MEM_OP_DATA_IN(1, NULL, 0));
 475
 476        spi_nor_setup_op(nor, &op, nor->reg_proto);
 477
 478        /*
 479         * We don't want to read only one byte in DTR mode. So, read 2 and then
 480         * discard the second byte.
 481         */
 482        if (spi_nor_protocol_is_dtr(nor->reg_proto))
 483                op.data.nbytes = 2;
 484
 485        ret = spi_nor_read_write_reg(nor, &op, val);
 486        if (ret < 0) {
 487                pr_debug("error %d reading FSR\n", ret);
 488                return ret;
 489        }
 490
 491        return *val;
 492}
 493
 494/*
 495 * Read configuration register, returning its value in the
 496 * location. Return the configuration register value.
 497 * Returns negative if error occurred.
 498 */
 499#if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
 500static int read_cr(struct spi_nor *nor)
 501{
 502        int ret;
 503        u8 val;
 504
 505        ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
 506        if (ret < 0) {
 507                dev_dbg(nor->dev, "error %d reading CR\n", ret);
 508                return ret;
 509        }
 510
 511        return val;
 512}
 513#endif
 514
 515/*
 516 * Write status register 1 byte
 517 * Returns negative if error occurred.
 518 */
 519static int write_sr(struct spi_nor *nor, u8 val)
 520{
 521        nor->cmd_buf[0] = val;
 522        return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
 523}
 524
 525/*
 526 * Set write enable latch with Write Enable command.
 527 * Returns negative if error occurred.
 528 */
 529static int write_enable(struct spi_nor *nor)
 530{
 531        return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
 532}
 533
 534/*
 535 * Send write disable instruction to the chip.
 536 */
 537static int write_disable(struct spi_nor *nor)
 538{
 539        return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
 540}
 541
 542static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
 543{
 544        return mtd->priv;
 545}
 546
 547#ifndef CONFIG_SPI_FLASH_BAR
 548static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
 549{
 550        size_t i;
 551
 552        for (i = 0; i < size; i++)
 553                if (table[i][0] == opcode)
 554                        return table[i][1];
 555
 556        /* No conversion found, keep input op code. */
 557        return opcode;
 558}
 559
 560static u8 spi_nor_convert_3to4_read(u8 opcode)
 561{
 562        static const u8 spi_nor_3to4_read[][2] = {
 563                { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
 564                { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
 565                { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
 566                { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
 567                { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
 568                { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
 569                { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
 570                { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
 571
 572                { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
 573                { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
 574                { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
 575        };
 576
 577        return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
 578                                      ARRAY_SIZE(spi_nor_3to4_read));
 579}
 580
 581static u8 spi_nor_convert_3to4_program(u8 opcode)
 582{
 583        static const u8 spi_nor_3to4_program[][2] = {
 584                { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
 585                { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
 586                { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
 587                { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
 588                { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
 589        };
 590
 591        return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
 592                                      ARRAY_SIZE(spi_nor_3to4_program));
 593}
 594
 595static u8 spi_nor_convert_3to4_erase(u8 opcode)
 596{
 597        static const u8 spi_nor_3to4_erase[][2] = {
 598                { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
 599                { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
 600                { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
 601        };
 602
 603        return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
 604                                      ARRAY_SIZE(spi_nor_3to4_erase));
 605}
 606
 607static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
 608                                      const struct flash_info *info)
 609{
 610        /* Do some manufacturer fixups first */
 611        switch (JEDEC_MFR(info)) {
 612        case SNOR_MFR_SPANSION:
 613                /* No small sector erase for 4-byte command set */
 614                nor->erase_opcode = SPINOR_OP_SE;
 615                nor->mtd.erasesize = info->sector_size;
 616                break;
 617
 618        default:
 619                break;
 620        }
 621
 622        nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
 623        nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
 624        nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
 625}
 626#endif /* !CONFIG_SPI_FLASH_BAR */
 627
 628/* Enable/disable 4-byte addressing mode. */
 629static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
 630                     int enable)
 631{
 632        int status;
 633        bool need_wren = false;
 634        u8 cmd;
 635
 636        switch (JEDEC_MFR(info)) {
 637        case SNOR_MFR_ST:
 638        case SNOR_MFR_MICRON:
 639                /* Some Micron need WREN command; all will accept it */
 640                need_wren = true;
 641        case SNOR_MFR_ISSI:
 642        case SNOR_MFR_MACRONIX:
 643        case SNOR_MFR_WINBOND:
 644                if (need_wren)
 645                        write_enable(nor);
 646
 647                cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
 648                status = nor->write_reg(nor, cmd, NULL, 0);
 649                if (need_wren)
 650                        write_disable(nor);
 651
 652                if (!status && !enable &&
 653                    JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
 654                        /*
 655                         * On Winbond W25Q256FV, leaving 4byte mode causes
 656                         * the Extended Address Register to be set to 1, so all
 657                         * 3-byte-address reads come from the second 16M.
 658                         * We must clear the register to enable normal behavior.
 659                         */
 660                        write_enable(nor);
 661                        nor->cmd_buf[0] = 0;
 662                        nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
 663                        write_disable(nor);
 664                }
 665
 666                return status;
 667        case SNOR_MFR_CYPRESS:
 668                cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B_CYPRESS;
 669                return nor->write_reg(nor, cmd, NULL, 0);
 670        default:
 671                /* Spansion style */
 672                nor->cmd_buf[0] = enable << 7;
 673                return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
 674        }
 675}
 676
 677#ifdef CONFIG_SPI_FLASH_SPANSION
 678/*
 679 * Read status register 1 by using Read Any Register command to support multi
 680 * die package parts.
 681 */
 682static int spansion_sr_ready(struct spi_nor *nor, u32 addr_base, u8 dummy)
 683{
 684        u32 reg_addr = addr_base + SPINOR_REG_ADDR_STR1V;
 685        u8 sr;
 686        int ret;
 687
 688        ret = spansion_read_any_reg(nor, reg_addr, dummy, &sr);
 689        if (ret < 0)
 690                return ret;
 691
 692        if (sr & (SR_E_ERR | SR_P_ERR)) {
 693                if (sr & SR_E_ERR)
 694                        dev_dbg(nor->dev, "Erase Error occurred\n");
 695                else
 696                        dev_dbg(nor->dev, "Programming Error occurred\n");
 697
 698                nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
 699                return -EIO;
 700        }
 701
 702        return !(sr & SR_WIP);
 703}
 704#endif
 705
 706static int spi_nor_sr_ready(struct spi_nor *nor)
 707{
 708        int sr = read_sr(nor);
 709
 710        if (sr < 0)
 711                return sr;
 712
 713        if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
 714                if (sr & SR_E_ERR)
 715                        dev_dbg(nor->dev, "Erase Error occurred\n");
 716                else
 717                        dev_dbg(nor->dev, "Programming Error occurred\n");
 718
 719                nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
 720                return -EIO;
 721        }
 722
 723        return !(sr & SR_WIP);
 724}
 725
 726static int spi_nor_fsr_ready(struct spi_nor *nor)
 727{
 728        int fsr = read_fsr(nor);
 729
 730        if (fsr < 0)
 731                return fsr;
 732
 733        if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
 734                if (fsr & FSR_E_ERR)
 735                        dev_err(nor->dev, "Erase operation failed.\n");
 736                else
 737                        dev_err(nor->dev, "Program operation failed.\n");
 738
 739                if (fsr & FSR_PT_ERR)
 740                        dev_err(nor->dev,
 741                                "Attempted to modify a protected sector.\n");
 742
 743                nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
 744                return -EIO;
 745        }
 746
 747        return fsr & FSR_READY;
 748}
 749
 750static int spi_nor_default_ready(struct spi_nor *nor)
 751{
 752        int sr, fsr;
 753
 754        sr = spi_nor_sr_ready(nor);
 755        if (sr < 0)
 756                return sr;
 757        fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
 758        if (fsr < 0)
 759                return fsr;
 760        return sr && fsr;
 761}
 762
 763static int spi_nor_ready(struct spi_nor *nor)
 764{
 765        if (nor->ready)
 766                return nor->ready(nor);
 767
 768        return spi_nor_default_ready(nor);
 769}
 770
 771/*
 772 * Service routine to read status register until ready, or timeout occurs.
 773 * Returns non-zero if error.
 774 */
 775static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
 776                                                unsigned long timeout)
 777{
 778        unsigned long timebase;
 779        int ret;
 780
 781        timebase = get_timer(0);
 782
 783        while (get_timer(timebase) < timeout) {
 784                ret = spi_nor_ready(nor);
 785                if (ret < 0)
 786                        return ret;
 787                if (ret)
 788                        return 0;
 789        }
 790
 791        dev_err(nor->dev, "flash operation timed out\n");
 792
 793        return -ETIMEDOUT;
 794}
 795
 796static int spi_nor_wait_till_ready(struct spi_nor *nor)
 797{
 798        return spi_nor_wait_till_ready_with_timeout(nor,
 799                                                    DEFAULT_READY_WAIT_JIFFIES);
 800}
 801
 802#ifdef CONFIG_SPI_FLASH_BAR
 803/*
 804 * This "clean_bar" is necessary in a situation when one was accessing
 805 * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
 806 *
 807 * After it the BA24 bit shall be cleared to allow access to correct
 808 * memory region after SW reset (by calling "reset" command).
 809 *
 810 * Otherwise, the BA24 bit may be left set and then after reset, the
 811 * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
 812 */
 813static int clean_bar(struct spi_nor *nor)
 814{
 815        u8 cmd, bank_sel = 0;
 816
 817        if (nor->bank_curr == 0)
 818                return 0;
 819        cmd = nor->bank_write_cmd;
 820        nor->bank_curr = 0;
 821        write_enable(nor);
 822
 823        return nor->write_reg(nor, cmd, &bank_sel, 1);
 824}
 825
 826static int write_bar(struct spi_nor *nor, u32 offset)
 827{
 828        u8 cmd, bank_sel;
 829        int ret;
 830
 831        bank_sel = offset / SZ_16M;
 832        if (bank_sel == nor->bank_curr)
 833                goto bar_end;
 834
 835        cmd = nor->bank_write_cmd;
 836        write_enable(nor);
 837        ret = nor->write_reg(nor, cmd, &bank_sel, 1);
 838        if (ret < 0) {
 839                debug("SF: fail to write bank register\n");
 840                return ret;
 841        }
 842
 843bar_end:
 844        nor->bank_curr = bank_sel;
 845        return nor->bank_curr;
 846}
 847
 848static int read_bar(struct spi_nor *nor, const struct flash_info *info)
 849{
 850        u8 curr_bank = 0;
 851        int ret;
 852
 853        switch (JEDEC_MFR(info)) {
 854        case SNOR_MFR_SPANSION:
 855                nor->bank_read_cmd = SPINOR_OP_BRRD;
 856                nor->bank_write_cmd = SPINOR_OP_BRWR;
 857                break;
 858        default:
 859                nor->bank_read_cmd = SPINOR_OP_RDEAR;
 860                nor->bank_write_cmd = SPINOR_OP_WREAR;
 861        }
 862
 863        ret = nor->read_reg(nor, nor->bank_read_cmd,
 864                                    &curr_bank, 1);
 865        if (ret) {
 866                debug("SF: fail to read bank addr register\n");
 867                return ret;
 868        }
 869        nor->bank_curr = curr_bank;
 870
 871        return 0;
 872}
 873#endif
 874
 875/*
 876 * Initiate the erasure of a single sector. Returns the number of bytes erased
 877 * on success, a negative error code on error.
 878 */
 879static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
 880{
 881        struct spi_mem_op op =
 882                SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
 883                           SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
 884                           SPI_MEM_OP_NO_DUMMY,
 885                           SPI_MEM_OP_NO_DATA);
 886        int ret;
 887
 888        spi_nor_setup_op(nor, &op, nor->write_proto);
 889
 890        if (nor->erase)
 891                return nor->erase(nor, addr);
 892
 893        /*
 894         * Default implementation, if driver doesn't have a specialized HW
 895         * control
 896         */
 897        ret = spi_mem_exec_op(nor->spi, &op);
 898        if (ret)
 899                return ret;
 900
 901        return nor->mtd.erasesize;
 902}
 903
 904/*
 905 * Erase an address range on the nor chip.  The address range may extend
 906 * one or more erase sectors.  Return an error is there is a problem erasing.
 907 */
 908static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
 909{
 910        struct spi_nor *nor = mtd_to_spi_nor(mtd);
 911        bool addr_known = false;
 912        u32 addr, len, rem;
 913        int ret, err;
 914
 915        dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
 916                (long long)instr->len);
 917
 918        div_u64_rem(instr->len, mtd->erasesize, &rem);
 919        if (rem) {
 920                ret = -EINVAL;
 921                goto err;
 922        }
 923
 924        addr = instr->addr;
 925        len = instr->len;
 926
 927        instr->state = MTD_ERASING;
 928        addr_known = true;
 929
 930        while (len) {
 931                WATCHDOG_RESET();
 932                if (ctrlc()) {
 933                        addr_known = false;
 934                        ret = -EINTR;
 935                        goto erase_err;
 936                }
 937#ifdef CONFIG_SPI_FLASH_BAR
 938                ret = write_bar(nor, addr);
 939                if (ret < 0)
 940                        goto erase_err;
 941#endif
 942                ret = write_enable(nor);
 943                if (ret < 0)
 944                        goto erase_err;
 945
 946                ret = spi_nor_erase_sector(nor, addr);
 947                if (ret < 0)
 948                        goto erase_err;
 949
 950                addr += ret;
 951                len -= ret;
 952
 953                ret = spi_nor_wait_till_ready(nor);
 954                if (ret)
 955                        goto erase_err;
 956        }
 957
 958        addr_known = false;
 959erase_err:
 960#ifdef CONFIG_SPI_FLASH_BAR
 961        err = clean_bar(nor);
 962        if (!ret)
 963                ret = err;
 964#endif
 965        err = write_disable(nor);
 966        if (!ret)
 967                ret = err;
 968
 969err:
 970        if (ret) {
 971                instr->fail_addr = addr_known ? addr : MTD_FAIL_ADDR_UNKNOWN;
 972                instr->state = MTD_ERASE_FAILED;
 973        } else {
 974                instr->state = MTD_ERASE_DONE;
 975        }
 976
 977        return ret;
 978}
 979
 980#ifdef CONFIG_SPI_FLASH_SPANSION
 981/**
 982 * spansion_erase_non_uniform() - erase non-uniform sectors for Spansion/Cypress
 983 *                                chips
 984 * @nor:        pointer to a 'struct spi_nor'
 985 * @addr:       address of the sector to erase
 986 * @opcode_4k:  opcode for 4K sector erase
 987 * @ovlsz_top:  size of overlaid portion at the top address
 988 * @ovlsz_btm:  size of overlaid portion at the bottom address
 989 *
 990 * Erase an address range on the nor chip that can contain 4KB sectors overlaid
 991 * on top and/or bottom. The appropriate erase opcode and size are chosen by
 992 * address to erase and size of overlaid portion.
 993 *
 994 * Return: number of bytes erased on success, -errno otherwise.
 995 */
 996static int spansion_erase_non_uniform(struct spi_nor *nor, u32 addr,
 997                                      u8 opcode_4k, u32 ovlsz_top,
 998                                      u32 ovlsz_btm)
 999{
1000        struct spi_mem_op op =
1001                SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
1002                           SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
1003                           SPI_MEM_OP_NO_DUMMY,
1004                           SPI_MEM_OP_NO_DATA);
1005        struct mtd_info *mtd = &nor->mtd;
1006        u32 erasesize;
1007        int ret;
1008
1009        /* 4KB sectors */
1010        if (op.addr.val < ovlsz_btm ||
1011            op.addr.val >= mtd->size - ovlsz_top) {
1012                op.cmd.opcode = opcode_4k;
1013                erasesize = SZ_4K;
1014
1015        /* Non-overlaid portion in the normal sector at the bottom */
1016        } else if (op.addr.val == ovlsz_btm) {
1017                op.cmd.opcode = nor->erase_opcode;
1018                erasesize = mtd->erasesize - ovlsz_btm;
1019
1020        /* Non-overlaid portion in the normal sector at the top */
1021        } else if (op.addr.val == mtd->size - mtd->erasesize) {
1022                op.cmd.opcode = nor->erase_opcode;
1023                erasesize = mtd->erasesize - ovlsz_top;
1024
1025        /* Normal sectors */
1026        } else {
1027                op.cmd.opcode = nor->erase_opcode;
1028                erasesize = mtd->erasesize;
1029        }
1030
1031        spi_nor_setup_op(nor, &op, nor->write_proto);
1032
1033        ret = spi_mem_exec_op(nor->spi, &op);
1034        if (ret)
1035                return ret;
1036
1037        return erasesize;
1038}
1039#endif
1040
1041#if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
1042/* Write status register and ensure bits in mask match written values */
1043static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
1044{
1045        int ret;
1046
1047        write_enable(nor);
1048        ret = write_sr(nor, status_new);
1049        if (ret)
1050                return ret;
1051
1052        ret = spi_nor_wait_till_ready(nor);
1053        if (ret)
1054                return ret;
1055
1056        ret = read_sr(nor);
1057        if (ret < 0)
1058                return ret;
1059
1060        return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
1061}
1062
1063static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
1064                                 uint64_t *len)
1065{
1066        struct mtd_info *mtd = &nor->mtd;
1067        u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1068        int shift = ffs(mask) - 1;
1069        int pow;
1070
1071        if (!(sr & mask)) {
1072                /* No protection */
1073                *ofs = 0;
1074                *len = 0;
1075        } else {
1076                pow = ((sr & mask) ^ mask) >> shift;
1077                *len = mtd->size >> pow;
1078                if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
1079                        *ofs = 0;
1080                else
1081                        *ofs = mtd->size - *len;
1082        }
1083}
1084
1085/*
1086 * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
1087 * @locked is false); 0 otherwise
1088 */
1089static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
1090                                    u8 sr, bool locked)
1091{
1092        loff_t lock_offs;
1093        uint64_t lock_len;
1094
1095        if (!len)
1096                return 1;
1097
1098        stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
1099
1100        if (locked)
1101                /* Requested range is a sub-range of locked range */
1102                return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
1103        else
1104                /* Requested range does not overlap with locked range */
1105                return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
1106}
1107
1108static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1109                            u8 sr)
1110{
1111        return stm_check_lock_status_sr(nor, ofs, len, sr, true);
1112}
1113
1114static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1115                              u8 sr)
1116{
1117        return stm_check_lock_status_sr(nor, ofs, len, sr, false);
1118}
1119
1120/*
1121 * Lock a region of the flash. Compatible with ST Micro and similar flash.
1122 * Supports the block protection bits BP{0,1,2} in the status register
1123 * (SR). Does not support these features found in newer SR bitfields:
1124 *   - SEC: sector/block protect - only handle SEC=0 (block protect)
1125 *   - CMP: complement protect - only support CMP=0 (range is not complemented)
1126 *
1127 * Support for the following is provided conditionally for some flash:
1128 *   - TB: top/bottom protect
1129 *
1130 * Sample table portion for 8MB flash (Winbond w25q64fw):
1131 *
1132 *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
1133 *  --------------------------------------------------------------------------
1134 *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
1135 *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
1136 *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
1137 *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
1138 *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
1139 *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
1140 *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
1141 *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
1142 *  ------|-------|-------|-------|-------|---------------|-------------------
1143 *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
1144 *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
1145 *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
1146 *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
1147 *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
1148 *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
1149 *
1150 * Returns negative on errors, 0 on success.
1151 */
1152static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1153{
1154        struct mtd_info *mtd = &nor->mtd;
1155        int status_old, status_new;
1156        u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1157        u8 shift = ffs(mask) - 1, pow, val;
1158        loff_t lock_len;
1159        bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1160        bool use_top;
1161
1162        status_old = read_sr(nor);
1163        if (status_old < 0)
1164                return status_old;
1165
1166        /* If nothing in our range is unlocked, we don't need to do anything */
1167        if (stm_is_locked_sr(nor, ofs, len, status_old))
1168                return 0;
1169
1170        /* If anything below us is unlocked, we can't use 'bottom' protection */
1171        if (!stm_is_locked_sr(nor, 0, ofs, status_old))
1172                can_be_bottom = false;
1173
1174        /* If anything above us is unlocked, we can't use 'top' protection */
1175        if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
1176                              status_old))
1177                can_be_top = false;
1178
1179        if (!can_be_bottom && !can_be_top)
1180                return -EINVAL;
1181
1182        /* Prefer top, if both are valid */
1183        use_top = can_be_top;
1184
1185        /* lock_len: length of region that should end up locked */
1186        if (use_top)
1187                lock_len = mtd->size - ofs;
1188        else
1189                lock_len = ofs + len;
1190
1191        /*
1192         * Need smallest pow such that:
1193         *
1194         *   1 / (2^pow) <= (len / size)
1195         *
1196         * so (assuming power-of-2 size) we do:
1197         *
1198         *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
1199         */
1200        pow = ilog2(mtd->size) - ilog2(lock_len);
1201        val = mask - (pow << shift);
1202        if (val & ~mask)
1203                return -EINVAL;
1204        /* Don't "lock" with no region! */
1205        if (!(val & mask))
1206                return -EINVAL;
1207
1208        status_new = (status_old & ~mask & ~SR_TB) | val;
1209
1210        /* Disallow further writes if WP pin is asserted */
1211        status_new |= SR_SRWD;
1212
1213        if (!use_top)
1214                status_new |= SR_TB;
1215
1216        /* Don't bother if they're the same */
1217        if (status_new == status_old)
1218                return 0;
1219
1220        /* Only modify protection if it will not unlock other areas */
1221        if ((status_new & mask) < (status_old & mask))
1222                return -EINVAL;
1223
1224        return write_sr_and_check(nor, status_new, mask);
1225}
1226
1227/*
1228 * Unlock a region of the flash. See stm_lock() for more info
1229 *
1230 * Returns negative on errors, 0 on success.
1231 */
1232static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1233{
1234        struct mtd_info *mtd = &nor->mtd;
1235        int status_old, status_new;
1236        u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1237        u8 shift = ffs(mask) - 1, pow, val;
1238        loff_t lock_len;
1239        bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1240        bool use_top;
1241
1242        status_old = read_sr(nor);
1243        if (status_old < 0)
1244                return status_old;
1245
1246        /* If nothing in our range is locked, we don't need to do anything */
1247        if (stm_is_unlocked_sr(nor, ofs, len, status_old))
1248                return 0;
1249
1250        /* If anything below us is locked, we can't use 'top' protection */
1251        if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
1252                can_be_top = false;
1253
1254        /* If anything above us is locked, we can't use 'bottom' protection */
1255        if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1256                                status_old))
1257                can_be_bottom = false;
1258
1259        if (!can_be_bottom && !can_be_top)
1260                return -EINVAL;
1261
1262        /* Prefer top, if both are valid */
1263        use_top = can_be_top;
1264
1265        /* lock_len: length of region that should remain locked */
1266        if (use_top)
1267                lock_len = mtd->size - (ofs + len);
1268        else
1269                lock_len = ofs;
1270
1271        /*
1272         * Need largest pow such that:
1273         *
1274         *   1 / (2^pow) >= (len / size)
1275         *
1276         * so (assuming power-of-2 size) we do:
1277         *
1278         *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
1279         */
1280        pow = ilog2(mtd->size) - order_base_2(lock_len);
1281        if (lock_len == 0) {
1282                val = 0; /* fully unlocked */
1283        } else {
1284                val = mask - (pow << shift);
1285                /* Some power-of-two sizes are not supported */
1286                if (val & ~mask)
1287                        return -EINVAL;
1288        }
1289
1290        status_new = (status_old & ~mask & ~SR_TB) | val;
1291
1292        /* Don't protect status register if we're fully unlocked */
1293        if (lock_len == 0)
1294                status_new &= ~SR_SRWD;
1295
1296        if (!use_top)
1297                status_new |= SR_TB;
1298
1299        /* Don't bother if they're the same */
1300        if (status_new == status_old)
1301                return 0;
1302
1303        /* Only modify protection if it will not lock other areas */
1304        if ((status_new & mask) > (status_old & mask))
1305                return -EINVAL;
1306
1307        return write_sr_and_check(nor, status_new, mask);
1308}
1309
1310/*
1311 * Check if a region of the flash is (completely) locked. See stm_lock() for
1312 * more info.
1313 *
1314 * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
1315 * negative on errors.
1316 */
1317static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1318{
1319        int status;
1320
1321        status = read_sr(nor);
1322        if (status < 0)
1323                return status;
1324
1325        return stm_is_locked_sr(nor, ofs, len, status);
1326}
1327#endif /* CONFIG_SPI_FLASH_STMICRO */
1328
1329static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1330{
1331        int                     tmp;
1332        u8                      id[SPI_NOR_MAX_ID_LEN];
1333        const struct flash_info *info;
1334
1335        tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1336        if (tmp < 0) {
1337                dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1338                return ERR_PTR(tmp);
1339        }
1340
1341        info = spi_nor_ids;
1342        for (; info->name; info++) {
1343                if (info->id_len) {
1344                        if (!memcmp(info->id, id, info->id_len))
1345                                return info;
1346                }
1347        }
1348
1349        dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1350                id[0], id[1], id[2]);
1351        return ERR_PTR(-ENODEV);
1352}
1353
1354static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1355                        size_t *retlen, u_char *buf)
1356{
1357        struct spi_nor *nor = mtd_to_spi_nor(mtd);
1358        int ret;
1359
1360        dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1361
1362        while (len) {
1363                loff_t addr = from;
1364                size_t read_len = len;
1365
1366#ifdef CONFIG_SPI_FLASH_BAR
1367                u32 remain_len;
1368
1369                ret = write_bar(nor, addr);
1370                if (ret < 0)
1371                        return log_ret(ret);
1372                remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
1373
1374                if (len < remain_len)
1375                        read_len = len;
1376                else
1377                        read_len = remain_len;
1378#endif
1379
1380                ret = nor->read(nor, addr, read_len, buf);
1381                if (ret == 0) {
1382                        /* We shouldn't see 0-length reads */
1383                        ret = -EIO;
1384                        goto read_err;
1385                }
1386                if (ret < 0)
1387                        goto read_err;
1388
1389                *retlen += ret;
1390                buf += ret;
1391                from += ret;
1392                len -= ret;
1393        }
1394        ret = 0;
1395
1396read_err:
1397#ifdef CONFIG_SPI_FLASH_BAR
1398        ret = clean_bar(nor);
1399#endif
1400        return ret;
1401}
1402
1403#ifdef CONFIG_SPI_FLASH_SST
1404/*
1405 * sst26 flash series has its own block protection implementation:
1406 * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
1407 * 1x   - 32 KByte blocks - write protection bits
1408 * rest - 64 KByte blocks - write protection bits
1409 * 1x   - 32 KByte blocks - write protection bits
1410 * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
1411 *
1412 * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
1413 * will be treated as single block.
1414 */
1415#define SST26_BPR_8K_NUM                4
1416#define SST26_MAX_BPR_REG_LEN           (18 + 1)
1417#define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
1418
1419enum lock_ctl {
1420        SST26_CTL_LOCK,
1421        SST26_CTL_UNLOCK,
1422        SST26_CTL_CHECK
1423};
1424
1425static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
1426{
1427        switch (ctl) {
1428        case SST26_CTL_LOCK:
1429                cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
1430                break;
1431        case SST26_CTL_UNLOCK:
1432                cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
1433                break;
1434        case SST26_CTL_CHECK:
1435                return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
1436        }
1437
1438        return false;
1439}
1440
1441/*
1442 * Lock, unlock or check lock status of the flash region of the flash (depending
1443 * on the lock_ctl value)
1444 */
1445static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
1446{
1447        struct mtd_info *mtd = &nor->mtd;
1448        u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1449        bool lower_64k = false, upper_64k = false;
1450        u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1451        int ret;
1452
1453        /* Check length and offset for 64k alignment */
1454        if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1455                dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1456                return -EINVAL;
1457        }
1458
1459        if (ofs + len > mtd->size) {
1460                dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1461                        ofs, len, mtd->size);
1462                return -EINVAL;
1463        }
1464
1465        /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1466        if (mtd->size != SZ_2M &&
1467            mtd->size != SZ_4M &&
1468            mtd->size != SZ_8M)
1469                return -EINVAL;
1470
1471        bpr_size = 2 + (mtd->size / SZ_64K / 8);
1472
1473        ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1474        if (ret < 0) {
1475                dev_err(nor->dev, "fail to read block-protection register\n");
1476                return ret;
1477        }
1478
1479        rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1480        lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1481
1482        upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1483        lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1484
1485        /* Lower bits in block-protection register are about 64k region */
1486        bpr_ptr = lptr_64k / SZ_64K - 1;
1487
1488        /* Process 64K blocks region */
1489        while (lptr_64k < rptr_64k) {
1490                if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1491                        return EACCES;
1492
1493                bpr_ptr++;
1494                lptr_64k += SZ_64K;
1495        }
1496
1497        /* 32K and 8K region bits in BPR are after 64k region bits */
1498        bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1499
1500        /* Process lower 32K block region */
1501        if (lower_64k)
1502                if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1503                        return EACCES;
1504
1505        bpr_ptr++;
1506
1507        /* Process upper 32K block region */
1508        if (upper_64k)
1509                if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1510                        return EACCES;
1511
1512        bpr_ptr++;
1513
1514        /* Process lower 8K block regions */
1515        for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1516                if (lower_64k)
1517                        if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1518                                return EACCES;
1519
1520                /* In 8K area BPR has both read and write protection bits */
1521                bpr_ptr += 2;
1522        }
1523
1524        /* Process upper 8K block regions */
1525        for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1526                if (upper_64k)
1527                        if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1528                                return EACCES;
1529
1530                /* In 8K area BPR has both read and write protection bits */
1531                bpr_ptr += 2;
1532        }
1533
1534        /* If we check region status we don't need to write BPR back */
1535        if (ctl == SST26_CTL_CHECK)
1536                return 0;
1537
1538        ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1539        if (ret < 0) {
1540                dev_err(nor->dev, "fail to write block-protection register\n");
1541                return ret;
1542        }
1543
1544        return 0;
1545}
1546
1547static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1548{
1549        return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1550}
1551
1552static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1553{
1554        return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1555}
1556
1557/*
1558 * Returns EACCES (positive value) if region is locked, 0 if region is unlocked,
1559 * and negative on errors.
1560 */
1561static int sst26_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1562{
1563        /*
1564         * is_locked function is used for check before reading or erasing flash
1565         * region, so offset and length might be not 64k allighned, so adjust
1566         * them to be 64k allighned as sst26_lock_ctl works only with 64k
1567         * allighned regions.
1568         */
1569        ofs -= ofs & (SZ_64K - 1);
1570        len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1571
1572        return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1573}
1574
1575static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1576                                 size_t *retlen, const u_char *buf)
1577{
1578        size_t actual;
1579        int ret = 0;
1580
1581        for (actual = 0; actual < len; actual++) {
1582                nor->program_opcode = SPINOR_OP_BP;
1583
1584                write_enable(nor);
1585                /* write one byte. */
1586                ret = nor->write(nor, to, 1, buf + actual);
1587                if (ret < 0)
1588                        goto sst_write_err;
1589                ret = spi_nor_wait_till_ready(nor);
1590                if (ret)
1591                        goto sst_write_err;
1592                to++;
1593        }
1594
1595sst_write_err:
1596        write_disable(nor);
1597        return ret;
1598}
1599
1600static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1601                     size_t *retlen, const u_char *buf)
1602{
1603        struct spi_nor *nor = mtd_to_spi_nor(mtd);
1604        struct spi_slave *spi = nor->spi;
1605        size_t actual;
1606        int ret;
1607
1608        dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1609        if (spi->mode & SPI_TX_BYTE)
1610                return sst_write_byteprogram(nor, to, len, retlen, buf);
1611
1612        write_enable(nor);
1613
1614        nor->sst_write_second = false;
1615
1616        actual = to % 2;
1617        /* Start write from odd address. */
1618        if (actual) {
1619                nor->program_opcode = SPINOR_OP_BP;
1620
1621                /* write one byte. */
1622                ret = nor->write(nor, to, 1, buf);
1623                if (ret < 0)
1624                        goto sst_write_err;
1625                ret = spi_nor_wait_till_ready(nor);
1626                if (ret)
1627                        goto sst_write_err;
1628        }
1629        to += actual;
1630
1631        /* Write out most of the data here. */
1632        for (; actual < len - 1; actual += 2) {
1633                nor->program_opcode = SPINOR_OP_AAI_WP;
1634
1635                /* write two bytes. */
1636                ret = nor->write(nor, to, 2, buf + actual);
1637                if (ret < 0)
1638                        goto sst_write_err;
1639                ret = spi_nor_wait_till_ready(nor);
1640                if (ret)
1641                        goto sst_write_err;
1642                to += 2;
1643                nor->sst_write_second = true;
1644        }
1645        nor->sst_write_second = false;
1646
1647        write_disable(nor);
1648        ret = spi_nor_wait_till_ready(nor);
1649        if (ret)
1650                goto sst_write_err;
1651
1652        /* Write out trailing byte if it exists. */
1653        if (actual != len) {
1654                write_enable(nor);
1655
1656                nor->program_opcode = SPINOR_OP_BP;
1657                ret = nor->write(nor, to, 1, buf + actual);
1658                if (ret < 0)
1659                        goto sst_write_err;
1660                ret = spi_nor_wait_till_ready(nor);
1661                if (ret)
1662                        goto sst_write_err;
1663                write_disable(nor);
1664                actual += 1;
1665        }
1666sst_write_err:
1667        *retlen += actual;
1668        return ret;
1669}
1670#endif
1671/*
1672 * Write an address range to the nor chip.  Data must be written in
1673 * FLASH_PAGESIZE chunks.  The address range may be any size provided
1674 * it is within the physical boundaries.
1675 */
1676static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1677        size_t *retlen, const u_char *buf)
1678{
1679        struct spi_nor *nor = mtd_to_spi_nor(mtd);
1680        size_t page_offset, page_remain, i;
1681        ssize_t ret;
1682
1683#ifdef CONFIG_SPI_FLASH_SST
1684        /* sst nor chips use AAI word program */
1685        if (nor->info->flags & SST_WRITE)
1686                return sst_write(mtd, to, len, retlen, buf);
1687#endif
1688
1689        dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1690
1691        for (i = 0; i < len; ) {
1692                ssize_t written;
1693                loff_t addr = to + i;
1694                WATCHDOG_RESET();
1695
1696                /*
1697                 * If page_size is a power of two, the offset can be quickly
1698                 * calculated with an AND operation. On the other cases we
1699                 * need to do a modulus operation (more expensive).
1700                 */
1701                if (is_power_of_2(nor->page_size)) {
1702                        page_offset = addr & (nor->page_size - 1);
1703                } else {
1704                        u64 aux = addr;
1705
1706                        page_offset = do_div(aux, nor->page_size);
1707                }
1708                /* the size of data remaining on the first page */
1709                page_remain = min_t(size_t,
1710                                    nor->page_size - page_offset, len - i);
1711
1712#ifdef CONFIG_SPI_FLASH_BAR
1713                ret = write_bar(nor, addr);
1714                if (ret < 0)
1715                        return ret;
1716#endif
1717                write_enable(nor);
1718                ret = nor->write(nor, addr, page_remain, buf + i);
1719                if (ret < 0)
1720                        goto write_err;
1721                written = ret;
1722
1723                ret = spi_nor_wait_till_ready(nor);
1724                if (ret)
1725                        goto write_err;
1726                *retlen += written;
1727                i += written;
1728        }
1729
1730write_err:
1731#ifdef CONFIG_SPI_FLASH_BAR
1732        ret = clean_bar(nor);
1733#endif
1734        return ret;
1735}
1736
1737#if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1738/**
1739 * macronix_quad_enable() - set QE bit in Status Register.
1740 * @nor:        pointer to a 'struct spi_nor'
1741 *
1742 * Set the Quad Enable (QE) bit in the Status Register.
1743 *
1744 * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1745 *
1746 * Return: 0 on success, -errno otherwise.
1747 */
1748static int macronix_quad_enable(struct spi_nor *nor)
1749{
1750        int ret, val;
1751
1752        val = read_sr(nor);
1753        if (val < 0)
1754                return val;
1755        if (val & SR_QUAD_EN_MX)
1756                return 0;
1757
1758        write_enable(nor);
1759
1760        write_sr(nor, val | SR_QUAD_EN_MX);
1761
1762        ret = spi_nor_wait_till_ready(nor);
1763        if (ret)
1764                return ret;
1765
1766        ret = read_sr(nor);
1767        if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1768                dev_err(nor->dev, "Macronix Quad bit not set\n");
1769                return -EINVAL;
1770        }
1771
1772        return 0;
1773}
1774#endif
1775
1776#ifdef CONFIG_SPI_FLASH_SPANSION
1777/**
1778 * spansion_quad_enable_volatile() - enable Quad I/O mode in volatile register.
1779 * @nor:        pointer to a 'struct spi_nor'
1780 * @addr_base:  base address of register (can be >0 in multi-die parts)
1781 * @dummy:      number of dummy cycles for register read
1782 *
1783 * It is recommended to update volatile registers in the field application due
1784 * to a risk of the non-volatile registers corruption by power interrupt. This
1785 * function sets Quad Enable bit in CFR1 volatile.
1786 *
1787 * Return: 0 on success, -errno otherwise.
1788 */
1789static int spansion_quad_enable_volatile(struct spi_nor *nor, u32 addr_base,
1790                                         u8 dummy)
1791{
1792        u32 addr = addr_base + SPINOR_REG_ADDR_CFR1V;
1793
1794        u8 cr;
1795        int ret;
1796
1797        /* Check current Quad Enable bit value. */
1798        ret = spansion_read_any_reg(nor, addr, dummy, &cr);
1799        if (ret < 0) {
1800                dev_dbg(nor->dev,
1801                        "error while reading configuration register\n");
1802                return -EINVAL;
1803        }
1804
1805        if (cr & CR_QUAD_EN_SPAN)
1806                return 0;
1807
1808        cr |= CR_QUAD_EN_SPAN;
1809
1810        write_enable(nor);
1811
1812        ret = spansion_write_any_reg(nor, addr, cr);
1813
1814        if (ret < 0) {
1815                dev_dbg(nor->dev,
1816                        "error while writing configuration register\n");
1817                return -EINVAL;
1818        }
1819
1820        /* Read back and check it. */
1821        ret = spansion_read_any_reg(nor, addr, dummy, &cr);
1822        if (ret || !(cr & CR_QUAD_EN_SPAN)) {
1823                dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1824                return -EINVAL;
1825        }
1826
1827        return 0;
1828}
1829#endif
1830
1831#if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1832/*
1833 * Write status Register and configuration register with 2 bytes
1834 * The first byte will be written to the status register, while the
1835 * second byte will be written to the configuration register.
1836 * Return negative if error occurred.
1837 */
1838static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1839{
1840        int ret;
1841
1842        write_enable(nor);
1843
1844        ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1845        if (ret < 0) {
1846                dev_dbg(nor->dev,
1847                        "error while writing configuration register\n");
1848                return -EINVAL;
1849        }
1850
1851        ret = spi_nor_wait_till_ready(nor);
1852        if (ret) {
1853                dev_dbg(nor->dev,
1854                        "timeout while writing configuration register\n");
1855                return ret;
1856        }
1857
1858        return 0;
1859}
1860
1861/**
1862 * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1863 * @nor:        pointer to a 'struct spi_nor'
1864 *
1865 * Set the Quad Enable (QE) bit in the Configuration Register.
1866 * This function should be used with QSPI memories supporting the Read
1867 * Configuration Register (35h) instruction.
1868 *
1869 * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1870 * memories.
1871 *
1872 * Return: 0 on success, -errno otherwise.
1873 */
1874static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1875{
1876        u8 sr_cr[2];
1877        int ret;
1878
1879        /* Check current Quad Enable bit value. */
1880        ret = read_cr(nor);
1881        if (ret < 0) {
1882                dev_dbg(nor->dev,
1883                        "error while reading configuration register\n");
1884                return -EINVAL;
1885        }
1886
1887        if (ret & CR_QUAD_EN_SPAN)
1888                return 0;
1889
1890        sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1891
1892        /* Keep the current value of the Status Register. */
1893        ret = read_sr(nor);
1894        if (ret < 0) {
1895                dev_dbg(nor->dev, "error while reading status register\n");
1896                return -EINVAL;
1897        }
1898        sr_cr[0] = ret;
1899
1900        ret = write_sr_cr(nor, sr_cr);
1901        if (ret)
1902                return ret;
1903
1904        /* Read back and check it. */
1905        ret = read_cr(nor);
1906        if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1907                dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1908                return -EINVAL;
1909        }
1910
1911        return 0;
1912}
1913
1914#if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1915/**
1916 * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1917 * @nor:        pointer to a 'struct spi_nor'
1918 *
1919 * Set the Quad Enable (QE) bit in the Configuration Register.
1920 * This function should be used with QSPI memories not supporting the Read
1921 * Configuration Register (35h) instruction.
1922 *
1923 * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1924 * memories.
1925 *
1926 * Return: 0 on success, -errno otherwise.
1927 */
1928static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1929{
1930        u8 sr_cr[2];
1931        int ret;
1932
1933        /* Keep the current value of the Status Register. */
1934        ret = read_sr(nor);
1935        if (ret < 0) {
1936                dev_dbg(nor->dev, "error while reading status register\n");
1937                return -EINVAL;
1938        }
1939        sr_cr[0] = ret;
1940        sr_cr[1] = CR_QUAD_EN_SPAN;
1941
1942        return write_sr_cr(nor, sr_cr);
1943}
1944
1945#endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1946#endif /* CONFIG_SPI_FLASH_SPANSION */
1947
1948static void
1949spi_nor_set_read_settings(struct spi_nor_read_command *read,
1950                          u8 num_mode_clocks,
1951                          u8 num_wait_states,
1952                          u8 opcode,
1953                          enum spi_nor_protocol proto)
1954{
1955        read->num_mode_clocks = num_mode_clocks;
1956        read->num_wait_states = num_wait_states;
1957        read->opcode = opcode;
1958        read->proto = proto;
1959}
1960
1961static void
1962spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1963                        u8 opcode,
1964                        enum spi_nor_protocol proto)
1965{
1966        pp->opcode = opcode;
1967        pp->proto = proto;
1968}
1969
1970#if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1971/*
1972 * Serial Flash Discoverable Parameters (SFDP) parsing.
1973 */
1974
1975/**
1976 * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1977 * @nor:        pointer to a 'struct spi_nor'
1978 * @addr:       offset in the SFDP area to start reading data from
1979 * @len:        number of bytes to read
1980 * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1981 *
1982 * Whatever the actual numbers of bytes for address and dummy cycles are
1983 * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1984 * followed by a 3-byte address and 8 dummy clock cycles.
1985 *
1986 * Return: 0 on success, -errno otherwise.
1987 */
1988static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1989                             size_t len, void *buf)
1990{
1991        u8 addr_width, read_opcode, read_dummy;
1992        int ret;
1993
1994        read_opcode = nor->read_opcode;
1995        addr_width = nor->addr_width;
1996        read_dummy = nor->read_dummy;
1997
1998        nor->read_opcode = SPINOR_OP_RDSFDP;
1999        nor->addr_width = 3;
2000        nor->read_dummy = 8;
2001
2002        while (len) {
2003                ret = nor->read(nor, addr, len, (u8 *)buf);
2004                if (!ret || ret > len) {
2005                        ret = -EIO;
2006                        goto read_err;
2007                }
2008                if (ret < 0)
2009                        goto read_err;
2010
2011                buf += ret;
2012                addr += ret;
2013                len -= ret;
2014        }
2015        ret = 0;
2016
2017read_err:
2018        nor->read_opcode = read_opcode;
2019        nor->addr_width = addr_width;
2020        nor->read_dummy = read_dummy;
2021
2022        return ret;
2023}
2024
2025/* Fast Read settings. */
2026
2027static void
2028spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
2029                                    u16 half,
2030                                    enum spi_nor_protocol proto)
2031{
2032        read->num_mode_clocks = (half >> 5) & 0x07;
2033        read->num_wait_states = (half >> 0) & 0x1f;
2034        read->opcode = (half >> 8) & 0xff;
2035        read->proto = proto;
2036}
2037
2038struct sfdp_bfpt_read {
2039        /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
2040        u32                     hwcaps;
2041
2042        /*
2043         * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
2044         * whether the Fast Read x-y-z command is supported.
2045         */
2046        u32                     supported_dword;
2047        u32                     supported_bit;
2048
2049        /*
2050         * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
2051         * encodes the op code, the number of mode clocks and the number of wait
2052         * states to be used by Fast Read x-y-z command.
2053         */
2054        u32                     settings_dword;
2055        u32                     settings_shift;
2056
2057        /* The SPI protocol for this Fast Read x-y-z command. */
2058        enum spi_nor_protocol   proto;
2059};
2060
2061static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
2062        /* Fast Read 1-1-2 */
2063        {
2064                SNOR_HWCAPS_READ_1_1_2,
2065                BFPT_DWORD(1), BIT(16), /* Supported bit */
2066                BFPT_DWORD(4), 0,       /* Settings */
2067                SNOR_PROTO_1_1_2,
2068        },
2069
2070        /* Fast Read 1-2-2 */
2071        {
2072                SNOR_HWCAPS_READ_1_2_2,
2073                BFPT_DWORD(1), BIT(20), /* Supported bit */
2074                BFPT_DWORD(4), 16,      /* Settings */
2075                SNOR_PROTO_1_2_2,
2076        },
2077
2078        /* Fast Read 2-2-2 */
2079        {
2080                SNOR_HWCAPS_READ_2_2_2,
2081                BFPT_DWORD(5),  BIT(0), /* Supported bit */
2082                BFPT_DWORD(6), 16,      /* Settings */
2083                SNOR_PROTO_2_2_2,
2084        },
2085
2086        /* Fast Read 1-1-4 */
2087        {
2088                SNOR_HWCAPS_READ_1_1_4,
2089                BFPT_DWORD(1), BIT(22), /* Supported bit */
2090                BFPT_DWORD(3), 16,      /* Settings */
2091                SNOR_PROTO_1_1_4,
2092        },
2093
2094        /* Fast Read 1-4-4 */
2095        {
2096                SNOR_HWCAPS_READ_1_4_4,
2097                BFPT_DWORD(1), BIT(21), /* Supported bit */
2098                BFPT_DWORD(3), 0,       /* Settings */
2099                SNOR_PROTO_1_4_4,
2100        },
2101
2102        /* Fast Read 4-4-4 */
2103        {
2104                SNOR_HWCAPS_READ_4_4_4,
2105                BFPT_DWORD(5), BIT(4),  /* Supported bit */
2106                BFPT_DWORD(7), 16,      /* Settings */
2107                SNOR_PROTO_4_4_4,
2108        },
2109};
2110
2111struct sfdp_bfpt_erase {
2112        /*
2113         * The half-word at offset <shift> in DWORD <dwoard> encodes the
2114         * op code and erase sector size to be used by Sector Erase commands.
2115         */
2116        u32                     dword;
2117        u32                     shift;
2118};
2119
2120static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
2121        /* Erase Type 1 in DWORD8 bits[15:0] */
2122        {BFPT_DWORD(8), 0},
2123
2124        /* Erase Type 2 in DWORD8 bits[31:16] */
2125        {BFPT_DWORD(8), 16},
2126
2127        /* Erase Type 3 in DWORD9 bits[15:0] */
2128        {BFPT_DWORD(9), 0},
2129
2130        /* Erase Type 4 in DWORD9 bits[31:16] */
2131        {BFPT_DWORD(9), 16},
2132};
2133
2134static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
2135
2136static int
2137spi_nor_post_bfpt_fixups(struct spi_nor *nor,
2138                         const struct sfdp_parameter_header *bfpt_header,
2139                         const struct sfdp_bfpt *bfpt,
2140                         struct spi_nor_flash_parameter *params)
2141{
2142        if (nor->fixups && nor->fixups->post_bfpt)
2143                return nor->fixups->post_bfpt(nor, bfpt_header, bfpt, params);
2144
2145        return 0;
2146}
2147
2148/**
2149 * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
2150 * @nor:                pointer to a 'struct spi_nor'
2151 * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
2152 *                      the Basic Flash Parameter Table length and version
2153 * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2154 *                      filled
2155 *
2156 * The Basic Flash Parameter Table is the main and only mandatory table as
2157 * defined by the SFDP (JESD216) specification.
2158 * It provides us with the total size (memory density) of the data array and
2159 * the number of address bytes for Fast Read, Page Program and Sector Erase
2160 * commands.
2161 * For Fast READ commands, it also gives the number of mode clock cycles and
2162 * wait states (regrouped in the number of dummy clock cycles) for each
2163 * supported instruction op code.
2164 * For Page Program, the page size is now available since JESD216 rev A, however
2165 * the supported instruction op codes are still not provided.
2166 * For Sector Erase commands, this table stores the supported instruction op
2167 * codes and the associated sector sizes.
2168 * Finally, the Quad Enable Requirements (QER) are also available since JESD216
2169 * rev A. The QER bits encode the manufacturer dependent procedure to be
2170 * executed to set the Quad Enable (QE) bit in some internal register of the
2171 * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
2172 * sending any Quad SPI command to the memory. Actually, setting the QE bit
2173 * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
2174 * and IO3 hence enabling 4 (Quad) I/O lines.
2175 *
2176 * Return: 0 on success, -errno otherwise.
2177 */
2178static int spi_nor_parse_bfpt(struct spi_nor *nor,
2179                              const struct sfdp_parameter_header *bfpt_header,
2180                              struct spi_nor_flash_parameter *params)
2181{
2182        struct mtd_info *mtd = &nor->mtd;
2183        struct sfdp_bfpt bfpt;
2184        size_t len;
2185        int i, cmd, err;
2186        u32 addr;
2187        u16 half;
2188
2189        /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
2190        if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
2191                return -EINVAL;
2192
2193        /* Read the Basic Flash Parameter Table. */
2194        len = min_t(size_t, sizeof(bfpt),
2195                    bfpt_header->length * sizeof(u32));
2196        addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
2197        memset(&bfpt, 0, sizeof(bfpt));
2198        err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
2199        if (err < 0)
2200                return err;
2201
2202        /* Fix endianness of the BFPT DWORDs. */
2203        for (i = 0; i < BFPT_DWORD_MAX; i++)
2204                bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
2205
2206        /* Number of address bytes. */
2207        switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
2208        case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
2209                nor->addr_width = 3;
2210                break;
2211
2212        case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
2213                nor->addr_width = 4;
2214                break;
2215
2216        default:
2217                break;
2218        }
2219
2220        /* Flash Memory Density (in bits). */
2221        params->size = bfpt.dwords[BFPT_DWORD(2)];
2222        if (params->size & BIT(31)) {
2223                params->size &= ~BIT(31);
2224
2225                /*
2226                 * Prevent overflows on params->size. Anyway, a NOR of 2^64
2227                 * bits is unlikely to exist so this error probably means
2228                 * the BFPT we are reading is corrupted/wrong.
2229                 */
2230                if (params->size > 63)
2231                        return -EINVAL;
2232
2233                params->size = 1ULL << params->size;
2234        } else {
2235                params->size++;
2236        }
2237        params->size >>= 3; /* Convert to bytes. */
2238
2239        /* Fast Read settings. */
2240        for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
2241                const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
2242                struct spi_nor_read_command *read;
2243
2244                if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
2245                        params->hwcaps.mask &= ~rd->hwcaps;
2246                        continue;
2247                }
2248
2249                params->hwcaps.mask |= rd->hwcaps;
2250                cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
2251                read = &params->reads[cmd];
2252                half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
2253                spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
2254        }
2255
2256        /* Sector Erase settings. */
2257        for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
2258                const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
2259                u32 erasesize;
2260                u8 opcode;
2261
2262                half = bfpt.dwords[er->dword] >> er->shift;
2263                erasesize = half & 0xff;
2264
2265                /* erasesize == 0 means this Erase Type is not supported. */
2266                if (!erasesize)
2267                        continue;
2268
2269                erasesize = 1U << erasesize;
2270                opcode = (half >> 8) & 0xff;
2271#ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2272                if (erasesize == SZ_4K) {
2273                        nor->erase_opcode = opcode;
2274                        mtd->erasesize = erasesize;
2275                        break;
2276                }
2277#endif
2278                if (!mtd->erasesize || mtd->erasesize < erasesize) {
2279                        nor->erase_opcode = opcode;
2280                        mtd->erasesize = erasesize;
2281                }
2282        }
2283
2284        /* Stop here if not JESD216 rev A or later. */
2285        if (bfpt_header->length == BFPT_DWORD_MAX_JESD216)
2286                return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2287                                                params);
2288
2289        /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
2290        params->page_size = bfpt.dwords[BFPT_DWORD(11)];
2291        params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
2292        params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
2293        params->page_size = 1U << params->page_size;
2294
2295        /* Quad Enable Requirements. */
2296        switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
2297        case BFPT_DWORD15_QER_NONE:
2298                params->quad_enable = NULL;
2299                break;
2300#if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2301        case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
2302        case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
2303                params->quad_enable = spansion_no_read_cr_quad_enable;
2304                break;
2305#endif
2306#if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2307        case BFPT_DWORD15_QER_SR1_BIT6:
2308                params->quad_enable = macronix_quad_enable;
2309                break;
2310#endif
2311#if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2312        case BFPT_DWORD15_QER_SR2_BIT1:
2313                params->quad_enable = spansion_read_cr_quad_enable;
2314                break;
2315#endif
2316        default:
2317                dev_dbg(nor->dev, "BFPT QER reserved value used\n");
2318                break;
2319        }
2320
2321        /* Soft Reset support. */
2322        if (bfpt.dwords[BFPT_DWORD(16)] & BFPT_DWORD16_SOFT_RST)
2323                nor->flags |= SNOR_F_SOFT_RESET;
2324
2325        /* Stop here if JESD216 rev B. */
2326        if (bfpt_header->length == BFPT_DWORD_MAX_JESD216B)
2327                return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2328                                                params);
2329
2330        /* 8D-8D-8D command extension. */
2331        switch (bfpt.dwords[BFPT_DWORD(18)] & BFPT_DWORD18_CMD_EXT_MASK) {
2332        case BFPT_DWORD18_CMD_EXT_REP:
2333                nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
2334                break;
2335
2336        case BFPT_DWORD18_CMD_EXT_INV:
2337                nor->cmd_ext_type = SPI_NOR_EXT_INVERT;
2338                break;
2339
2340        case BFPT_DWORD18_CMD_EXT_RES:
2341                return -EINVAL;
2342
2343        case BFPT_DWORD18_CMD_EXT_16B:
2344                dev_err(nor->dev, "16-bit opcodes not supported\n");
2345                return -ENOTSUPP;
2346        }
2347
2348        return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
2349}
2350
2351/**
2352 * spi_nor_parse_microchip_sfdp() - parse the Microchip manufacturer specific
2353 * SFDP table.
2354 * @nor:                pointer to a 'struct spi_nor'.
2355 * @param_header:       pointer to the SFDP parameter header.
2356 *
2357 * Return: 0 on success, -errno otherwise.
2358 */
2359static int
2360spi_nor_parse_microchip_sfdp(struct spi_nor *nor,
2361                             const struct sfdp_parameter_header *param_header)
2362{
2363        size_t size;
2364        u32 addr;
2365        int ret;
2366
2367        size = param_header->length * sizeof(u32);
2368        addr = SFDP_PARAM_HEADER_PTP(param_header);
2369
2370        nor->manufacturer_sfdp = devm_kmalloc(nor->dev, size, GFP_KERNEL);
2371        if (!nor->manufacturer_sfdp)
2372                return -ENOMEM;
2373
2374        ret = spi_nor_read_sfdp(nor, addr, size, nor->manufacturer_sfdp);
2375
2376        return ret;
2377}
2378
2379/**
2380 * spi_nor_parse_profile1() - parse the xSPI Profile 1.0 table
2381 * @nor:                pointer to a 'struct spi_nor'
2382 * @profile1_header:    pointer to the 'struct sfdp_parameter_header' describing
2383 *                      the 4-Byte Address Instruction Table length and version.
2384 * @params:             pointer to the 'struct spi_nor_flash_parameter' to be.
2385 *
2386 * Return: 0 on success, -errno otherwise.
2387 */
2388static int spi_nor_parse_profile1(struct spi_nor *nor,
2389                                  const struct sfdp_parameter_header *profile1_header,
2390                                  struct spi_nor_flash_parameter *params)
2391{
2392        u32 *table, opcode, addr;
2393        size_t len;
2394        int ret, i;
2395        u8 dummy;
2396
2397        len = profile1_header->length * sizeof(*table);
2398        table = kmalloc(len, GFP_KERNEL);
2399        if (!table)
2400                return -ENOMEM;
2401
2402        addr = SFDP_PARAM_HEADER_PTP(profile1_header);
2403        ret = spi_nor_read_sfdp(nor, addr, len, table);
2404        if (ret)
2405                goto out;
2406
2407        /* Fix endianness of the table DWORDs. */
2408        for (i = 0; i < profile1_header->length; i++)
2409                table[i] = le32_to_cpu(table[i]);
2410
2411        /* Get 8D-8D-8D fast read opcode and dummy cycles. */
2412        opcode = FIELD_GET(PROFILE1_DWORD1_RD_FAST_CMD, table[0]);
2413
2414        /*
2415         * We don't know what speed the controller is running at. Find the
2416         * dummy cycles for the fastest frequency the flash can run at to be
2417         * sure we are never short of dummy cycles. A value of 0 means the
2418         * frequency is not supported.
2419         *
2420         * Default to PROFILE1_DUMMY_DEFAULT if we don't find anything, and let
2421         * flashes set the correct value if needed in their fixup hooks.
2422         */
2423        dummy = FIELD_GET(PROFILE1_DWORD4_DUMMY_200MHZ, table[3]);
2424        if (!dummy)
2425                dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_166MHZ, table[4]);
2426        if (!dummy)
2427                dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_133MHZ, table[4]);
2428        if (!dummy)
2429                dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_100MHZ, table[4]);
2430        if (!dummy)
2431                dummy = PROFILE1_DUMMY_DEFAULT;
2432
2433        /* Round up to an even value to avoid tripping controllers up. */
2434        dummy = ROUND_UP_TO(dummy, 2);
2435
2436        /* Update the fast read settings. */
2437        spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2438                                  0, dummy, opcode,
2439                                  SNOR_PROTO_8_8_8_DTR);
2440
2441        /*
2442         * Set the Read Status Register dummy cycles and dummy address bytes.
2443         */
2444        if (table[0] & PROFILE1_DWORD1_RDSR_DUMMY)
2445                params->rdsr_dummy = 8;
2446        else
2447                params->rdsr_dummy = 4;
2448
2449        if (table[0] & PROFILE1_DWORD1_RDSR_ADDR_BYTES)
2450                params->rdsr_addr_nbytes = 4;
2451        else
2452                params->rdsr_addr_nbytes = 0;
2453
2454out:
2455        kfree(table);
2456        return ret;
2457}
2458
2459/**
2460 * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
2461 * @nor:                pointer to a 'struct spi_nor'
2462 * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2463 *                      filled
2464 *
2465 * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2466 * specification. This is a standard which tends to supported by almost all
2467 * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2468 * runtime the main parameters needed to perform basic SPI flash operations such
2469 * as Fast Read, Page Program or Sector Erase commands.
2470 *
2471 * Return: 0 on success, -errno otherwise.
2472 */
2473static int spi_nor_parse_sfdp(struct spi_nor *nor,
2474                              struct spi_nor_flash_parameter *params)
2475{
2476        const struct sfdp_parameter_header *param_header, *bfpt_header;
2477        struct sfdp_parameter_header *param_headers = NULL;
2478        struct sfdp_header header;
2479        size_t psize;
2480        int i, err;
2481
2482        /* Get the SFDP header. */
2483        err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2484        if (err < 0)
2485                return err;
2486
2487        /* Check the SFDP header version. */
2488        if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2489            header.major != SFDP_JESD216_MAJOR)
2490                return -EINVAL;
2491
2492        /*
2493         * Verify that the first and only mandatory parameter header is a
2494         * Basic Flash Parameter Table header as specified in JESD216.
2495         */
2496        bfpt_header = &header.bfpt_header;
2497        if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2498            bfpt_header->major != SFDP_JESD216_MAJOR)
2499                return -EINVAL;
2500
2501        /*
2502         * Allocate memory then read all parameter headers with a single
2503         * Read SFDP command. These parameter headers will actually be parsed
2504         * twice: a first time to get the latest revision of the basic flash
2505         * parameter table, then a second time to handle the supported optional
2506         * tables.
2507         * Hence we read the parameter headers once for all to reduce the
2508         * processing time. Also we use kmalloc() instead of devm_kmalloc()
2509         * because we don't need to keep these parameter headers: the allocated
2510         * memory is always released with kfree() before exiting this function.
2511         */
2512        if (header.nph) {
2513                psize = header.nph * sizeof(*param_headers);
2514
2515                param_headers = kmalloc(psize, GFP_KERNEL);
2516                if (!param_headers)
2517                        return -ENOMEM;
2518
2519                err = spi_nor_read_sfdp(nor, sizeof(header),
2520                                        psize, param_headers);
2521                if (err < 0) {
2522                        dev_err(nor->dev,
2523                                "failed to read SFDP parameter headers\n");
2524                        goto exit;
2525                }
2526        }
2527
2528        /*
2529         * Check other parameter headers to get the latest revision of
2530         * the basic flash parameter table.
2531         */
2532        for (i = 0; i < header.nph; i++) {
2533                param_header = &param_headers[i];
2534
2535                if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2536                    param_header->major == SFDP_JESD216_MAJOR &&
2537                    (param_header->minor > bfpt_header->minor ||
2538                     (param_header->minor == bfpt_header->minor &&
2539                      param_header->length > bfpt_header->length)))
2540                        bfpt_header = param_header;
2541        }
2542
2543        err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2544        if (err)
2545                goto exit;
2546
2547        /* Parse other parameter headers. */
2548        for (i = 0; i < header.nph; i++) {
2549                param_header = &param_headers[i];
2550
2551                switch (SFDP_PARAM_HEADER_ID(param_header)) {
2552                case SFDP_SECTOR_MAP_ID:
2553                        dev_info(nor->dev,
2554                                 "non-uniform erase sector maps are not supported yet.\n");
2555                        break;
2556
2557                case SFDP_SST_ID:
2558                        err = spi_nor_parse_microchip_sfdp(nor, param_header);
2559                        break;
2560
2561                case SFDP_PROFILE1_ID:
2562                        err = spi_nor_parse_profile1(nor, param_header, params);
2563                        break;
2564
2565                default:
2566                        break;
2567                }
2568
2569                if (err) {
2570                        dev_warn(nor->dev,
2571                                 "Failed to parse optional parameter table: %04x\n",
2572                                 SFDP_PARAM_HEADER_ID(param_header));
2573                        /*
2574                         * Let's not drop all information we extracted so far
2575                         * if optional table parsers fail. In case of failing,
2576                         * each optional parser is responsible to roll back to
2577                         * the previously known spi_nor data.
2578                         */
2579                        err = 0;
2580                }
2581        }
2582
2583exit:
2584        kfree(param_headers);
2585        return err;
2586}
2587#else
2588static int spi_nor_parse_sfdp(struct spi_nor *nor,
2589                              struct spi_nor_flash_parameter *params)
2590{
2591        return -EINVAL;
2592}
2593#endif /* SPI_FLASH_SFDP_SUPPORT */
2594
2595/**
2596 * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2597 * after SFDP has been parsed (is also called for SPI NORs that do not
2598 * support RDSFDP).
2599 * @nor:        pointer to a 'struct spi_nor'
2600 *
2601 * Typically used to tweak various parameters that could not be extracted by
2602 * other means (i.e. when information provided by the SFDP/flash_info tables
2603 * are incomplete or wrong).
2604 */
2605static void spi_nor_post_sfdp_fixups(struct spi_nor *nor,
2606                                     struct spi_nor_flash_parameter *params)
2607{
2608        if (nor->fixups && nor->fixups->post_sfdp)
2609                nor->fixups->post_sfdp(nor, params);
2610}
2611
2612static void spi_nor_default_init_fixups(struct spi_nor *nor)
2613{
2614        if (nor->fixups && nor->fixups->default_init)
2615                nor->fixups->default_init(nor);
2616}
2617
2618static int spi_nor_init_params(struct spi_nor *nor,
2619                               const struct flash_info *info,
2620                               struct spi_nor_flash_parameter *params)
2621{
2622        /* Set legacy flash parameters as default. */
2623        memset(params, 0, sizeof(*params));
2624
2625        /* Set SPI NOR sizes. */
2626        params->size = info->sector_size * info->n_sectors;
2627        params->page_size = info->page_size;
2628
2629        if (!(info->flags & SPI_NOR_NO_FR)) {
2630                /* Default to Fast Read for DT and non-DT platform devices. */
2631                params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2632
2633                /* Mask out Fast Read if not requested at DT instantiation. */
2634#if CONFIG_IS_ENABLED(DM_SPI)
2635                if (!ofnode_read_bool(dev_ofnode(nor->spi->dev),
2636                                      "m25p,fast-read"))
2637                        params->hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2638#endif
2639        }
2640
2641        /* (Fast) Read settings. */
2642        params->hwcaps.mask |= SNOR_HWCAPS_READ;
2643        spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2644                                  0, 0, SPINOR_OP_READ,
2645                                  SNOR_PROTO_1_1_1);
2646
2647        if (params->hwcaps.mask & SNOR_HWCAPS_READ_FAST)
2648                spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2649                                          0, 8, SPINOR_OP_READ_FAST,
2650                                          SNOR_PROTO_1_1_1);
2651
2652        if (info->flags & SPI_NOR_DUAL_READ) {
2653                params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2654                spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2655                                          0, 8, SPINOR_OP_READ_1_1_2,
2656                                          SNOR_PROTO_1_1_2);
2657        }
2658
2659        if (info->flags & SPI_NOR_QUAD_READ) {
2660                params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2661                spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2662                                          0, 8, SPINOR_OP_READ_1_1_4,
2663                                          SNOR_PROTO_1_1_4);
2664        }
2665
2666        if (info->flags & SPI_NOR_OCTAL_READ) {
2667                params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2668                spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2669                                          0, 8, SPINOR_OP_READ_1_1_8,
2670                                          SNOR_PROTO_1_1_8);
2671        }
2672
2673        if (info->flags & SPI_NOR_OCTAL_DTR_READ) {
2674                params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
2675                spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2676                                          0, 20, SPINOR_OP_READ_FAST,
2677                                          SNOR_PROTO_8_8_8_DTR);
2678        }
2679
2680        /* Page Program settings. */
2681        params->hwcaps.mask |= SNOR_HWCAPS_PP;
2682        spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2683                                SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2684
2685        /*
2686         * Since xSPI Page Program opcode is backward compatible with
2687         * Legacy SPI, use Legacy SPI opcode there as well.
2688         */
2689        spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
2690                                SPINOR_OP_PP, SNOR_PROTO_8_8_8_DTR);
2691
2692        if (info->flags & SPI_NOR_QUAD_READ) {
2693                params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2694                spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2695                                        SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2696        }
2697
2698        /* Select the procedure to set the Quad Enable bit. */
2699        if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2700                                   SNOR_HWCAPS_PP_QUAD)) {
2701                switch (JEDEC_MFR(info)) {
2702#if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2703                case SNOR_MFR_MACRONIX:
2704                case SNOR_MFR_ISSI:
2705                        params->quad_enable = macronix_quad_enable;
2706                        break;
2707#endif
2708                case SNOR_MFR_ST:
2709                case SNOR_MFR_MICRON:
2710                        break;
2711
2712                default:
2713#if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2714                        /* Kept only for backward compatibility purpose. */
2715                        params->quad_enable = spansion_read_cr_quad_enable;
2716#endif
2717                        break;
2718                }
2719        }
2720
2721        spi_nor_default_init_fixups(nor);
2722
2723        /* Override the parameters with data read from SFDP tables. */
2724        nor->addr_width = 0;
2725        nor->mtd.erasesize = 0;
2726        if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2727             SPI_NOR_OCTAL_DTR_READ)) &&
2728            !(info->flags & SPI_NOR_SKIP_SFDP)) {
2729                struct spi_nor_flash_parameter sfdp_params;
2730
2731                memcpy(&sfdp_params, params, sizeof(sfdp_params));
2732                if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2733                        nor->addr_width = 0;
2734                        nor->mtd.erasesize = 0;
2735                } else {
2736                        memcpy(params, &sfdp_params, sizeof(*params));
2737                }
2738        }
2739
2740        spi_nor_post_sfdp_fixups(nor, params);
2741
2742        return 0;
2743}
2744
2745static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2746{
2747        size_t i;
2748
2749        for (i = 0; i < size; i++)
2750                if (table[i][0] == (int)hwcaps)
2751                        return table[i][1];
2752
2753        return -EINVAL;
2754}
2755
2756static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2757{
2758        static const int hwcaps_read2cmd[][2] = {
2759                { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2760                { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2761                { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2762                { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2763                { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2764                { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2765                { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2766                { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2767                { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2768                { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2769                { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2770                { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2771                { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2772                { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2773                { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2774                { SNOR_HWCAPS_READ_8_8_8_DTR,   SNOR_CMD_READ_8_8_8_DTR },
2775        };
2776
2777        return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2778                                  ARRAY_SIZE(hwcaps_read2cmd));
2779}
2780
2781static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2782{
2783        static const int hwcaps_pp2cmd[][2] = {
2784                { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2785                { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2786                { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2787                { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2788                { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2789                { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2790                { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2791                { SNOR_HWCAPS_PP_8_8_8_DTR,     SNOR_CMD_PP_8_8_8_DTR },
2792        };
2793
2794        return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2795                                  ARRAY_SIZE(hwcaps_pp2cmd));
2796}
2797
2798#ifdef CONFIG_SPI_FLASH_SMART_HWCAPS
2799/**
2800 * spi_nor_check_op - check if the operation is supported by controller
2801 * @nor:        pointer to a 'struct spi_nor'
2802 * @op:         pointer to op template to be checked
2803 *
2804 * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2805 */
2806static int spi_nor_check_op(struct spi_nor *nor,
2807                            struct spi_mem_op *op)
2808{
2809        /*
2810         * First test with 4 address bytes. The opcode itself might be a 3B
2811         * addressing opcode but we don't care, because SPI controller
2812         * implementation should not check the opcode, but just the sequence.
2813         */
2814        op->addr.nbytes = 4;
2815        if (!spi_mem_supports_op(nor->spi, op)) {
2816                if (nor->mtd.size > SZ_16M)
2817                        return -ENOTSUPP;
2818
2819                /* If flash size <= 16MB, 3 address bytes are sufficient */
2820                op->addr.nbytes = 3;
2821                if (!spi_mem_supports_op(nor->spi, op))
2822                        return -ENOTSUPP;
2823        }
2824
2825        return 0;
2826}
2827
2828/**
2829 * spi_nor_check_readop - check if the read op is supported by controller
2830 * @nor:         pointer to a 'struct spi_nor'
2831 * @read:        pointer to op template to be checked
2832 *
2833 * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2834 */
2835static int spi_nor_check_readop(struct spi_nor *nor,
2836                                const struct spi_nor_read_command *read)
2837{
2838        struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 0),
2839                                          SPI_MEM_OP_ADDR(3, 0, 0),
2840                                          SPI_MEM_OP_DUMMY(1, 0),
2841                                          SPI_MEM_OP_DATA_IN(2, NULL, 0));
2842
2843        spi_nor_setup_op(nor, &op, read->proto);
2844
2845        op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
2846                          op.dummy.buswidth / 8;
2847        if (spi_nor_protocol_is_dtr(nor->read_proto))
2848                op.dummy.nbytes *= 2;
2849
2850        return spi_nor_check_op(nor, &op);
2851}
2852
2853/**
2854 * spi_nor_check_pp - check if the page program op is supported by controller
2855 * @nor:         pointer to a 'struct spi_nor'
2856 * @pp:          pointer to op template to be checked
2857 *
2858 * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2859 */
2860static int spi_nor_check_pp(struct spi_nor *nor,
2861                            const struct spi_nor_pp_command *pp)
2862{
2863        struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 0),
2864                                          SPI_MEM_OP_ADDR(3, 0, 0),
2865                                          SPI_MEM_OP_NO_DUMMY,
2866                                          SPI_MEM_OP_DATA_OUT(2, NULL, 0));
2867
2868        spi_nor_setup_op(nor, &op, pp->proto);
2869
2870        return spi_nor_check_op(nor, &op);
2871}
2872
2873/**
2874 * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2875 *                         controller capabilities
2876 * @nor:        pointer to a 'struct spi_nor'
2877 * @params:     pointer to the 'struct spi_nor_flash_parameter'
2878 *              representing SPI NOR flash capabilities
2879 * @hwcaps:     pointer to resulting capabilities after adjusting
2880 *              according to controller and flash's capability
2881 *
2882 * Discard caps based on what the SPI controller actually supports (using
2883 * spi_mem_supports_op()).
2884 */
2885static void
2886spi_nor_adjust_hwcaps(struct spi_nor *nor,
2887                      const struct spi_nor_flash_parameter *params,
2888                      u32 *hwcaps)
2889{
2890        unsigned int cap;
2891
2892        /*
2893         * Start by assuming the controller supports every capability.
2894         * We will mask them after checking what's really supported
2895         * using spi_mem_supports_op().
2896         */
2897        *hwcaps = SNOR_HWCAPS_ALL & params->hwcaps.mask;
2898
2899        /* X-X-X modes are not supported yet, mask them all. */
2900        *hwcaps &= ~SNOR_HWCAPS_X_X_X;
2901
2902        /*
2903         * If the reset line is broken, we do not want to enter a stateful
2904         * mode.
2905         */
2906        if (nor->flags & SNOR_F_BROKEN_RESET)
2907                *hwcaps &= ~(SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR);
2908
2909        for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
2910                int rdidx, ppidx;
2911
2912                if (!(*hwcaps & BIT(cap)))
2913                        continue;
2914
2915                rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
2916                if (rdidx >= 0 &&
2917                    spi_nor_check_readop(nor, &params->reads[rdidx]))
2918                        *hwcaps &= ~BIT(cap);
2919
2920                ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
2921                if (ppidx < 0)
2922                        continue;
2923
2924                if (spi_nor_check_pp(nor, &params->page_programs[ppidx]))
2925                        *hwcaps &= ~BIT(cap);
2926        }
2927}
2928#else
2929/**
2930 * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2931 *                         controller capabilities
2932 * @nor:        pointer to a 'struct spi_nor'
2933 * @params:     pointer to the 'struct spi_nor_flash_parameter'
2934 *              representing SPI NOR flash capabilities
2935 * @hwcaps:     pointer to resulting capabilities after adjusting
2936 *              according to controller and flash's capability
2937 *
2938 * Select caps based on what the SPI controller and SPI flash both support.
2939 */
2940static void
2941spi_nor_adjust_hwcaps(struct spi_nor *nor,
2942                      const struct spi_nor_flash_parameter *params,
2943                      u32 *hwcaps)
2944{
2945        struct spi_slave *spi = nor->spi;
2946        u32 ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2947                            SNOR_HWCAPS_READ_4_4_4 |
2948                            SNOR_HWCAPS_READ_8_8_8 |
2949                            SNOR_HWCAPS_PP_4_4_4   |
2950                            SNOR_HWCAPS_PP_8_8_8);
2951        u32 spi_hwcaps = (SNOR_HWCAPS_READ | SNOR_HWCAPS_READ_FAST |
2952                          SNOR_HWCAPS_PP);
2953
2954        /* Get the hardware capabilities the SPI controller supports. */
2955        if (spi->mode & SPI_RX_OCTAL) {
2956                spi_hwcaps |= SNOR_HWCAPS_READ_1_1_8;
2957
2958                if (spi->mode & SPI_TX_OCTAL)
2959                        spi_hwcaps |= (SNOR_HWCAPS_READ_1_8_8 |
2960                                        SNOR_HWCAPS_PP_1_1_8 |
2961                                        SNOR_HWCAPS_PP_1_8_8);
2962        } else if (spi->mode & SPI_RX_QUAD) {
2963                spi_hwcaps |= SNOR_HWCAPS_READ_1_1_4;
2964
2965                if (spi->mode & SPI_TX_QUAD)
2966                        spi_hwcaps |= (SNOR_HWCAPS_READ_1_4_4 |
2967                                        SNOR_HWCAPS_PP_1_1_4 |
2968                                        SNOR_HWCAPS_PP_1_4_4);
2969        } else if (spi->mode & SPI_RX_DUAL) {
2970                spi_hwcaps |= SNOR_HWCAPS_READ_1_1_2;
2971
2972                if (spi->mode & SPI_TX_DUAL)
2973                        spi_hwcaps |= SNOR_HWCAPS_READ_1_2_2;
2974        }
2975
2976        /*
2977         * Keep only the hardware capabilities supported by both the SPI
2978         * controller and the SPI flash memory.
2979         */
2980        *hwcaps = spi_hwcaps & params->hwcaps.mask;
2981        if (*hwcaps & ignored_mask) {
2982                dev_dbg(nor->dev,
2983                        "SPI n-n-n protocols are not supported yet.\n");
2984                *hwcaps &= ~ignored_mask;
2985        }
2986}
2987#endif /* CONFIG_SPI_FLASH_SMART_HWCAPS */
2988
2989static int spi_nor_select_read(struct spi_nor *nor,
2990                               const struct spi_nor_flash_parameter *params,
2991                               u32 shared_hwcaps)
2992{
2993        int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2994        const struct spi_nor_read_command *read;
2995
2996        if (best_match < 0)
2997                return -EINVAL;
2998
2999        cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
3000        if (cmd < 0)
3001                return -EINVAL;
3002
3003        read = &params->reads[cmd];
3004        nor->read_opcode = read->opcode;
3005        nor->read_proto = read->proto;
3006
3007        /*
3008         * In the spi-nor framework, we don't need to make the difference
3009         * between mode clock cycles and wait state clock cycles.
3010         * Indeed, the value of the mode clock cycles is used by a QSPI
3011         * flash memory to know whether it should enter or leave its 0-4-4
3012         * (Continuous Read / XIP) mode.
3013         * eXecution In Place is out of the scope of the mtd sub-system.
3014         * Hence we choose to merge both mode and wait state clock cycles
3015         * into the so called dummy clock cycles.
3016         */
3017        nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
3018        return 0;
3019}
3020
3021static int spi_nor_select_pp(struct spi_nor *nor,
3022                             const struct spi_nor_flash_parameter *params,
3023                             u32 shared_hwcaps)
3024{
3025        int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
3026        const struct spi_nor_pp_command *pp;
3027
3028        if (best_match < 0)
3029                return -EINVAL;
3030
3031        cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
3032        if (cmd < 0)
3033                return -EINVAL;
3034
3035        pp = &params->page_programs[cmd];
3036        nor->program_opcode = pp->opcode;
3037        nor->write_proto = pp->proto;
3038        return 0;
3039}
3040
3041static int spi_nor_select_erase(struct spi_nor *nor,
3042                                const struct flash_info *info)
3043{
3044        struct mtd_info *mtd = &nor->mtd;
3045
3046        /* Do nothing if already configured from SFDP. */
3047        if (mtd->erasesize)
3048                return 0;
3049
3050#ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
3051        /* prefer "small sector" erase if possible */
3052        if (info->flags & SECT_4K) {
3053                nor->erase_opcode = SPINOR_OP_BE_4K;
3054                mtd->erasesize = 4096;
3055        } else if (info->flags & SECT_4K_PMC) {
3056                nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
3057                mtd->erasesize = 4096;
3058        } else
3059#endif
3060        {
3061                nor->erase_opcode = SPINOR_OP_SE;
3062                mtd->erasesize = info->sector_size;
3063        }
3064        return 0;
3065}
3066
3067static int spi_nor_default_setup(struct spi_nor *nor,
3068                                 const struct flash_info *info,
3069                                 const struct spi_nor_flash_parameter *params)
3070{
3071        u32 shared_mask;
3072        bool enable_quad_io;
3073        int err;
3074
3075        spi_nor_adjust_hwcaps(nor, params, &shared_mask);
3076
3077        /* Select the (Fast) Read command. */
3078        err = spi_nor_select_read(nor, params, shared_mask);
3079        if (err) {
3080                dev_dbg(nor->dev,
3081                        "can't select read settings supported by both the SPI controller and memory.\n");
3082                return err;
3083        }
3084
3085        /* Select the Page Program command. */
3086        err = spi_nor_select_pp(nor, params, shared_mask);
3087        if (err) {
3088                dev_dbg(nor->dev,
3089                        "can't select write settings supported by both the SPI controller and memory.\n");
3090                return err;
3091        }
3092
3093        /* Select the Sector Erase command. */
3094        err = spi_nor_select_erase(nor, info);
3095        if (err) {
3096                dev_dbg(nor->dev,
3097                        "can't select erase settings supported by both the SPI controller and memory.\n");
3098                return err;
3099        }
3100
3101        /* Enable Quad I/O if needed. */
3102        enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
3103                          spi_nor_get_protocol_width(nor->write_proto) == 4);
3104        if (enable_quad_io && params->quad_enable)
3105                nor->quad_enable = params->quad_enable;
3106        else
3107                nor->quad_enable = NULL;
3108
3109        return 0;
3110}
3111
3112static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
3113                         const struct spi_nor_flash_parameter *params)
3114{
3115        if (!nor->setup)
3116                return 0;
3117
3118        return nor->setup(nor, info, params);
3119}
3120
3121#ifdef CONFIG_SPI_FLASH_SPANSION
3122static int s25hx_t_mdp_ready(struct spi_nor *nor)
3123{
3124        u32 addr;
3125        int ret;
3126
3127        for (addr = 0; addr < nor->mtd.size; addr += SZ_128M) {
3128                ret = spansion_sr_ready(nor, addr, 0);
3129                if (!ret)
3130                        return ret;
3131        }
3132
3133        return 1;
3134}
3135
3136static int s25hx_t_quad_enable(struct spi_nor *nor)
3137{
3138        u32 addr;
3139        int ret;
3140
3141        for (addr = 0; addr < nor->mtd.size; addr += SZ_128M) {
3142                ret = spansion_quad_enable_volatile(nor, addr, 0);
3143                if (ret)
3144                        return ret;
3145        }
3146
3147        return 0;
3148}
3149
3150static int s25hx_t_erase_non_uniform(struct spi_nor *nor, loff_t addr)
3151{
3152        /* Support 32 x 4KB sectors at bottom */
3153        return spansion_erase_non_uniform(nor, addr, SPINOR_OP_BE_4K_4B, 0,
3154                                          SZ_128K);
3155}
3156
3157static int s25hx_t_setup(struct spi_nor *nor, const struct flash_info *info,
3158                         const struct spi_nor_flash_parameter *params)
3159{
3160        int ret;
3161        u8 cfr3v;
3162
3163#ifdef CONFIG_SPI_FLASH_BAR
3164        return -ENOTSUPP; /* Bank Address Register is not supported */
3165#endif
3166        /*
3167         * Read CFR3V to check if uniform sector is selected. If not, assign an
3168         * erase hook that supports non-uniform erase.
3169         */
3170        ret = spansion_read_any_reg(nor, SPINOR_REG_ADDR_CFR3V, 0, &cfr3v);
3171        if (ret)
3172                return ret;
3173        if (!(cfr3v & CFR3V_UNHYSA))
3174                nor->erase = s25hx_t_erase_non_uniform;
3175
3176        /*
3177         * For the multi-die package parts, the ready() hook is needed to check
3178         * all dies' status via read any register.
3179         */
3180        if (nor->mtd.size > SZ_128M)
3181                nor->ready = s25hx_t_mdp_ready;
3182
3183        return spi_nor_default_setup(nor, info, params);
3184}
3185
3186static void s25hx_t_default_init(struct spi_nor *nor)
3187{
3188        nor->setup = s25hx_t_setup;
3189}
3190
3191static int s25hx_t_post_bfpt_fixup(struct spi_nor *nor,
3192                                   const struct sfdp_parameter_header *header,
3193                                   const struct sfdp_bfpt *bfpt,
3194                                   struct spi_nor_flash_parameter *params)
3195{
3196        int ret;
3197        u32 addr;
3198        u8 cfr3v;
3199
3200        /* erase size in case it is set to 4K from BFPT */
3201        nor->erase_opcode = SPINOR_OP_SE_4B;
3202        nor->mtd.erasesize = nor->info->sector_size;
3203
3204        ret = set_4byte(nor, nor->info, 1);
3205        if (ret)
3206                return ret;
3207        nor->addr_width = 4;
3208
3209        /*
3210         * The page_size is set to 512B from BFPT, but it actually depends on
3211         * the configuration register. Look up the CFR3V and determine the
3212         * page_size. For multi-die package parts, use 512B only when the all
3213         * dies are configured to 512B buffer.
3214         */
3215        for (addr = 0; addr < params->size; addr += SZ_128M) {
3216                ret = spansion_read_any_reg(nor, addr + SPINOR_REG_ADDR_CFR3V,
3217                                            0, &cfr3v);
3218                if (ret)
3219                        return ret;
3220
3221                if (!(cfr3v & CFR3V_PGMBUF)) {
3222                        params->page_size = 256;
3223                        return 0;
3224                }
3225        }
3226        params->page_size = 512;
3227
3228        return 0;
3229}
3230
3231static void s25hx_t_post_sfdp_fixup(struct spi_nor *nor,
3232                                    struct spi_nor_flash_parameter *params)
3233{
3234        /* READ_FAST_4B (0Ch) requires mode cycles*/
3235        params->reads[SNOR_CMD_READ_FAST].num_mode_clocks = 8;
3236        /* PP_1_1_4 is not supported */
3237        params->hwcaps.mask &= ~SNOR_HWCAPS_PP_1_1_4;
3238        /* Use volatile register to enable quad */
3239        params->quad_enable = s25hx_t_quad_enable;
3240}
3241
3242static struct spi_nor_fixups s25hx_t_fixups = {
3243        .default_init = s25hx_t_default_init,
3244        .post_bfpt = s25hx_t_post_bfpt_fixup,
3245        .post_sfdp = s25hx_t_post_sfdp_fixup,
3246};
3247
3248static int s25fl256l_setup(struct spi_nor *nor, const struct flash_info *info,
3249                           const struct spi_nor_flash_parameter *params)
3250{
3251        return -ENOTSUPP; /* Bank Address Register is not supported */
3252}
3253
3254static void s25fl256l_default_init(struct spi_nor *nor)
3255{
3256        nor->setup = s25fl256l_setup;
3257}
3258
3259static struct spi_nor_fixups s25fl256l_fixups = {
3260        .default_init = s25fl256l_default_init,
3261};
3262#endif
3263
3264#ifdef CONFIG_SPI_FLASH_S28HS512T
3265/**
3266 * spi_nor_cypress_octal_dtr_enable() - Enable octal DTR on Cypress flashes.
3267 * @nor:                pointer to a 'struct spi_nor'
3268 *
3269 * This also sets the memory access latency cycles to 24 to allow the flash to
3270 * run at up to 200MHz.
3271 *
3272 * Return: 0 on success, -errno otherwise.
3273 */
3274static int spi_nor_cypress_octal_dtr_enable(struct spi_nor *nor)
3275{
3276        struct spi_mem_op op;
3277        u8 buf;
3278        u8 addr_width = 3;
3279        int ret;
3280
3281        /* Use 24 dummy cycles for memory array reads. */
3282        ret = write_enable(nor);
3283        if (ret)
3284                return ret;
3285
3286        buf = SPINOR_REG_CYPRESS_CFR2V_MEMLAT_11_24;
3287        op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_ANY_REG, 1),
3288                        SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR2V, 1),
3289                        SPI_MEM_OP_NO_DUMMY,
3290                        SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3291        ret = spi_mem_exec_op(nor->spi, &op);
3292        if (ret) {
3293                dev_warn(nor->dev,
3294                         "failed to set default memory latency value: %d\n",
3295                         ret);
3296                return ret;
3297        }
3298        ret = spi_nor_wait_till_ready(nor);
3299        if (ret)
3300                return ret;
3301
3302        nor->read_dummy = 24;
3303
3304        /* Set the octal and DTR enable bits. */
3305        ret = write_enable(nor);
3306        if (ret)
3307                return ret;
3308
3309        buf = SPINOR_REG_CYPRESS_CFR5V_OCT_DTR_EN;
3310        op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_ANY_REG, 1),
3311                        SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR5V, 1),
3312                        SPI_MEM_OP_NO_DUMMY,
3313                        SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3314        ret = spi_mem_exec_op(nor->spi, &op);
3315        if (ret) {
3316                dev_warn(nor->dev, "Failed to enable octal DTR mode\n");
3317                return ret;
3318        }
3319
3320        return 0;
3321}
3322
3323static int s28hs512t_erase_non_uniform(struct spi_nor *nor, loff_t addr)
3324{
3325        /* Factory default configuration: 32 x 4 KiB sectors at bottom. */
3326        return spansion_erase_non_uniform(nor, addr, SPINOR_OP_S28_SE_4K,
3327                                          0, SZ_128K);
3328}
3329
3330static int s28hs512t_setup(struct spi_nor *nor, const struct flash_info *info,
3331                           const struct spi_nor_flash_parameter *params)
3332{
3333        struct spi_mem_op op;
3334        u8 buf;
3335        u8 addr_width = 3;
3336        int ret;
3337
3338        ret = spi_nor_wait_till_ready(nor);
3339        if (ret)
3340                return ret;
3341
3342        /*
3343         * Check CFR3V to check if non-uniform sector mode is selected. If it
3344         * is, set the erase hook to the non-uniform erase procedure.
3345         */
3346        op = (struct spi_mem_op)
3347                SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RD_ANY_REG, 1),
3348                           SPI_MEM_OP_ADDR(addr_width,
3349                                           SPINOR_REG_CYPRESS_CFR3V, 1),
3350                           SPI_MEM_OP_NO_DUMMY,
3351                           SPI_MEM_OP_DATA_IN(1, &buf, 1));
3352
3353        ret = spi_mem_exec_op(nor->spi, &op);
3354        if (ret)
3355                return ret;
3356
3357        if (!(buf & SPINOR_REG_CYPRESS_CFR3V_UNISECT))
3358                nor->erase = s28hs512t_erase_non_uniform;
3359
3360        return spi_nor_default_setup(nor, info, params);
3361}
3362
3363static void s28hs512t_default_init(struct spi_nor *nor)
3364{
3365        nor->octal_dtr_enable = spi_nor_cypress_octal_dtr_enable;
3366        nor->setup = s28hs512t_setup;
3367}
3368
3369static void s28hs512t_post_sfdp_fixup(struct spi_nor *nor,
3370                                      struct spi_nor_flash_parameter *params)
3371{
3372        /*
3373         * On older versions of the flash the xSPI Profile 1.0 table has the
3374         * 8D-8D-8D Fast Read opcode as 0x00. But it actually should be 0xEE.
3375         */
3376        if (params->reads[SNOR_CMD_READ_8_8_8_DTR].opcode == 0)
3377                params->reads[SNOR_CMD_READ_8_8_8_DTR].opcode =
3378                        SPINOR_OP_CYPRESS_RD_FAST;
3379
3380        params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3381
3382        /* This flash is also missing the 4-byte Page Program opcode bit. */
3383        spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
3384                                SPINOR_OP_PP_4B, SNOR_PROTO_1_1_1);
3385        /*
3386         * Since xSPI Page Program opcode is backward compatible with
3387         * Legacy SPI, use Legacy SPI opcode there as well.
3388         */
3389        spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
3390                                SPINOR_OP_PP_4B, SNOR_PROTO_8_8_8_DTR);
3391
3392        /*
3393         * The xSPI Profile 1.0 table advertises the number of additional
3394         * address bytes needed for Read Status Register command as 0 but the
3395         * actual value for that is 4.
3396         */
3397        params->rdsr_addr_nbytes = 4;
3398}
3399
3400static int s28hs512t_post_bfpt_fixup(struct spi_nor *nor,
3401                                     const struct sfdp_parameter_header *bfpt_header,
3402                                     const struct sfdp_bfpt *bfpt,
3403                                     struct spi_nor_flash_parameter *params)
3404{
3405        struct spi_mem_op op;
3406        u8 buf;
3407        u8 addr_width = 3;
3408        int ret;
3409
3410        /*
3411         * The BFPT table advertises a 512B page size but the page size is
3412         * actually configurable (with the default being 256B). Read from
3413         * CFR3V[4] and set the correct size.
3414         */
3415        op = (struct spi_mem_op)
3416                SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RD_ANY_REG, 1),
3417                           SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR3V, 1),
3418                           SPI_MEM_OP_NO_DUMMY,
3419                           SPI_MEM_OP_DATA_IN(1, &buf, 1));
3420        ret = spi_mem_exec_op(nor->spi, &op);
3421        if (ret)
3422                return ret;
3423
3424        if (buf & SPINOR_REG_CYPRESS_CFR3V_PGSZ)
3425                params->page_size = 512;
3426        else
3427                params->page_size = 256;
3428
3429        /*
3430         * The BFPT advertises that it supports 4k erases, and the datasheet
3431         * says the same. But 4k erases did not work when testing. So, use 256k
3432         * erases for now.
3433         */
3434        nor->erase_opcode = SPINOR_OP_SE_4B;
3435        nor->mtd.erasesize = 0x40000;
3436
3437        return 0;
3438}
3439
3440static struct spi_nor_fixups s28hs512t_fixups = {
3441        .default_init = s28hs512t_default_init,
3442        .post_sfdp = s28hs512t_post_sfdp_fixup,
3443        .post_bfpt = s28hs512t_post_bfpt_fixup,
3444};
3445#endif /* CONFIG_SPI_FLASH_S28HS512T */
3446
3447#ifdef CONFIG_SPI_FLASH_MT35XU
3448static int spi_nor_micron_octal_dtr_enable(struct spi_nor *nor)
3449{
3450        struct spi_mem_op op;
3451        u8 buf;
3452        u8 addr_width = 3;
3453        int ret;
3454
3455        /* Set dummy cycles for Fast Read to the default of 20. */
3456        ret = write_enable(nor);
3457        if (ret)
3458                return ret;
3459
3460        buf = 20;
3461        op = (struct spi_mem_op)
3462                SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_MT_WR_ANY_REG, 1),
3463                           SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_MT_CFR1V, 1),
3464                           SPI_MEM_OP_NO_DUMMY,
3465                           SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3466        ret = spi_mem_exec_op(nor->spi, &op);
3467        if (ret)
3468                return ret;
3469
3470        ret = spi_nor_wait_till_ready(nor);
3471        if (ret)
3472                return ret;
3473
3474        nor->read_dummy = 20;
3475
3476        ret = write_enable(nor);
3477        if (ret)
3478                return ret;
3479
3480        buf = SPINOR_MT_OCT_DTR;
3481        op = (struct spi_mem_op)
3482                SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_MT_WR_ANY_REG, 1),
3483                           SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_MT_CFR0V, 1),
3484                           SPI_MEM_OP_NO_DUMMY,
3485                           SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3486        ret = spi_mem_exec_op(nor->spi, &op);
3487        if (ret) {
3488                dev_err(nor->dev, "Failed to enable octal DTR mode\n");
3489                return ret;
3490        }
3491
3492        return 0;
3493}
3494
3495static void mt35xu512aba_default_init(struct spi_nor *nor)
3496{
3497        nor->octal_dtr_enable = spi_nor_micron_octal_dtr_enable;
3498}
3499
3500static void mt35xu512aba_post_sfdp_fixup(struct spi_nor *nor,
3501                                         struct spi_nor_flash_parameter *params)
3502{
3503        /* Set the Fast Read settings. */
3504        params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
3505        spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
3506                                  0, 20, SPINOR_OP_MT_DTR_RD,
3507                                  SNOR_PROTO_8_8_8_DTR);
3508
3509        params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3510
3511        nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3512        params->rdsr_dummy = 8;
3513        params->rdsr_addr_nbytes = 0;
3514
3515        /*
3516         * The BFPT quad enable field is set to a reserved value so the quad
3517         * enable function is ignored by spi_nor_parse_bfpt(). Make sure we
3518         * disable it.
3519         */
3520        params->quad_enable = NULL;
3521}
3522
3523static struct spi_nor_fixups mt35xu512aba_fixups = {
3524        .default_init = mt35xu512aba_default_init,
3525        .post_sfdp = mt35xu512aba_post_sfdp_fixup,
3526};
3527#endif /* CONFIG_SPI_FLASH_MT35XU */
3528
3529/** spi_nor_octal_dtr_enable() - enable Octal DTR I/O if needed
3530 * @nor:                 pointer to a 'struct spi_nor'
3531 *
3532 * Return: 0 on success, -errno otherwise.
3533 */
3534static int spi_nor_octal_dtr_enable(struct spi_nor *nor)
3535{
3536        int ret;
3537
3538        if (!nor->octal_dtr_enable)
3539                return 0;
3540
3541        if (!(nor->read_proto == SNOR_PROTO_8_8_8_DTR &&
3542              nor->write_proto == SNOR_PROTO_8_8_8_DTR))
3543                return 0;
3544
3545        ret = nor->octal_dtr_enable(nor);
3546        if (ret)
3547                return ret;
3548
3549        nor->reg_proto = SNOR_PROTO_8_8_8_DTR;
3550
3551        return 0;
3552}
3553
3554static int spi_nor_init(struct spi_nor *nor)
3555{
3556        int err;
3557
3558        err = spi_nor_octal_dtr_enable(nor);
3559        if (err) {
3560                dev_dbg(nor->dev, "Octal DTR mode not supported\n");
3561                return err;
3562        }
3563
3564        /*
3565         * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
3566         * with the software protection bits set
3567         */
3568        if (IS_ENABLED(CONFIG_SPI_FLASH_UNLOCK_ALL) &&
3569            (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
3570             JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
3571             JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
3572             nor->info->flags & SPI_NOR_HAS_LOCK)) {
3573                write_enable(nor);
3574                write_sr(nor, 0);
3575                spi_nor_wait_till_ready(nor);
3576        }
3577
3578        if (nor->quad_enable) {
3579                err = nor->quad_enable(nor);
3580                if (err) {
3581                        dev_dbg(nor->dev, "quad mode not supported\n");
3582                        return err;
3583                }
3584        }
3585
3586        if (nor->addr_width == 4 &&
3587            !(nor->info->flags & SPI_NOR_OCTAL_DTR_READ) &&
3588            (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
3589            !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
3590                /*
3591                 * If the RESET# pin isn't hooked up properly, or the system
3592                 * otherwise doesn't perform a reset command in the boot
3593                 * sequence, it's impossible to 100% protect against unexpected
3594                 * reboots (e.g., crashes). Warn the user (or hopefully, system
3595                 * designer) that this is bad.
3596                 */
3597                if (nor->flags & SNOR_F_BROKEN_RESET)
3598                        debug("enabling reset hack; may not recover from unexpected reboots\n");
3599                set_4byte(nor, nor->info, 1);
3600        }
3601
3602        return 0;
3603}
3604
3605#ifdef CONFIG_SPI_FLASH_SOFT_RESET
3606/**
3607 * spi_nor_soft_reset() - perform the JEDEC Software Reset sequence
3608 * @nor:        the spi_nor structure
3609 *
3610 * This function can be used to switch from Octal DTR mode to legacy mode on a
3611 * flash that supports it. The soft reset is executed in Octal DTR mode.
3612 *
3613 * Return: 0 for success, -errno for failure.
3614 */
3615static int spi_nor_soft_reset(struct spi_nor *nor)
3616{
3617        struct spi_mem_op op;
3618        int ret;
3619        enum spi_nor_cmd_ext ext;
3620
3621        ext = nor->cmd_ext_type;
3622        nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3623
3624        op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRSTEN, 0),
3625                        SPI_MEM_OP_NO_DUMMY,
3626                        SPI_MEM_OP_NO_ADDR,
3627                        SPI_MEM_OP_NO_DATA);
3628        spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3629        ret = spi_mem_exec_op(nor->spi, &op);
3630        if (ret) {
3631                dev_warn(nor->dev, "Software reset enable failed: %d\n", ret);
3632                goto out;
3633        }
3634
3635        op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRST, 0),
3636                        SPI_MEM_OP_NO_DUMMY,
3637                        SPI_MEM_OP_NO_ADDR,
3638                        SPI_MEM_OP_NO_DATA);
3639        spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3640        ret = spi_mem_exec_op(nor->spi, &op);
3641        if (ret) {
3642                dev_warn(nor->dev, "Software reset failed: %d\n", ret);
3643                goto out;
3644        }
3645
3646        /*
3647         * Software Reset is not instant, and the delay varies from flash to
3648         * flash. Looking at a few flashes, most range somewhere below 100
3649         * microseconds. So, wait for 200ms just to be sure.
3650         */
3651        udelay(SPI_NOR_SRST_SLEEP_LEN);
3652
3653out:
3654        nor->cmd_ext_type = ext;
3655        return ret;
3656}
3657#endif /* CONFIG_SPI_FLASH_SOFT_RESET */
3658
3659int spi_nor_remove(struct spi_nor *nor)
3660{
3661#ifdef CONFIG_SPI_FLASH_SOFT_RESET
3662        if (nor->info->flags & SPI_NOR_OCTAL_DTR_READ &&
3663            nor->flags & SNOR_F_SOFT_RESET)
3664                return spi_nor_soft_reset(nor);
3665#endif
3666
3667        return 0;
3668}
3669
3670void spi_nor_set_fixups(struct spi_nor *nor)
3671{
3672#ifdef CONFIG_SPI_FLASH_SPANSION
3673        if (JEDEC_MFR(nor->info) == SNOR_MFR_CYPRESS) {
3674                switch (nor->info->id[1]) {
3675                case 0x2a: /* S25HL (QSPI, 3.3V) */
3676                case 0x2b: /* S25HS (QSPI, 1.8V) */
3677                        nor->fixups = &s25hx_t_fixups;
3678                        break;
3679
3680                default:
3681                        break;
3682                }
3683        }
3684
3685        if (CONFIG_IS_ENABLED(SPI_FLASH_BAR) &&
3686            !strcmp(nor->info->name, "s25fl256l"))
3687                nor->fixups = &s25fl256l_fixups;
3688#endif
3689
3690#ifdef CONFIG_SPI_FLASH_S28HS512T
3691        if (!strcmp(nor->info->name, "s28hs512t"))
3692                nor->fixups = &s28hs512t_fixups;
3693#endif
3694
3695#ifdef CONFIG_SPI_FLASH_MT35XU
3696        if (!strcmp(nor->info->name, "mt35xu512aba"))
3697                nor->fixups = &mt35xu512aba_fixups;
3698#endif
3699}
3700
3701int spi_nor_scan(struct spi_nor *nor)
3702{
3703        struct spi_nor_flash_parameter params;
3704        const struct flash_info *info = NULL;
3705        struct mtd_info *mtd = &nor->mtd;
3706        struct spi_slave *spi = nor->spi;
3707        int ret;
3708        int cfi_mtd_nb = 0;
3709
3710#ifdef CONFIG_SYS_MAX_FLASH_BANKS
3711        cfi_mtd_nb = CONFIG_SYS_MAX_FLASH_BANKS;
3712#endif
3713
3714        /* Reset SPI protocol for all commands. */
3715        nor->reg_proto = SNOR_PROTO_1_1_1;
3716        nor->read_proto = SNOR_PROTO_1_1_1;
3717        nor->write_proto = SNOR_PROTO_1_1_1;
3718        nor->read = spi_nor_read_data;
3719        nor->write = spi_nor_write_data;
3720        nor->read_reg = spi_nor_read_reg;
3721        nor->write_reg = spi_nor_write_reg;
3722
3723        nor->setup = spi_nor_default_setup;
3724
3725#ifdef CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT
3726        /*
3727         * When the flash is handed to us in a stateful mode like 8D-8D-8D, it
3728         * is difficult to detect the mode the flash is in. One option is to
3729         * read SFDP in all modes and see which one gives the correct "SFDP"
3730         * signature, but not all flashes support SFDP in 8D-8D-8D mode.
3731         *
3732         * Further, even if you detect the mode of the flash via SFDP, you
3733         * still have the problem of actually reading the ID. The Read ID
3734         * command is not standardized across flash vendors. Flashes can have
3735         * different dummy cycles needed for reading the ID. Some flashes even
3736         * expect a 4-byte dummy address with the Read ID command. All this
3737         * information cannot be obtained from the SFDP table.
3738         *
3739         * So, perform a Software Reset sequence before reading the ID and
3740         * initializing the flash. A Soft Reset will bring back the flash in
3741         * its default protocol mode assuming no non-volatile configuration was
3742         * set. This will let us detect the flash even if ROM hands it to us in
3743         * Octal DTR mode.
3744         *
3745         * To accommodate cases where there is more than one flash on a board,
3746         * and only one of them needs a soft reset, failure to reset is not
3747         * made fatal, and we still try to read ID if possible.
3748         */
3749        spi_nor_soft_reset(nor);
3750#endif /* CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT */
3751
3752        info = spi_nor_read_id(nor);
3753        if (IS_ERR_OR_NULL(info))
3754                return -ENOENT;
3755        nor->info = info;
3756
3757        spi_nor_set_fixups(nor);
3758
3759        /* Parse the Serial Flash Discoverable Parameters table. */
3760        ret = spi_nor_init_params(nor, info, &params);
3761        if (ret)
3762                return ret;
3763
3764        if (!mtd->name) {
3765                sprintf(nor->mtd_name, "%s%d",
3766                        MTD_DEV_TYPE(MTD_DEV_TYPE_NOR),
3767                        cfi_mtd_nb + dev_seq(nor->dev));
3768                mtd->name = nor->mtd_name;
3769        }
3770        mtd->dev = nor->dev;
3771        mtd->priv = nor;
3772        mtd->type = MTD_NORFLASH;
3773        mtd->writesize = 1;
3774        mtd->flags = MTD_CAP_NORFLASH;
3775        mtd->size = params.size;
3776        mtd->_erase = spi_nor_erase;
3777        mtd->_read = spi_nor_read;
3778        mtd->_write = spi_nor_write;
3779
3780#if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
3781        /* NOR protection support for STmicro/Micron chips and similar */
3782        if (JEDEC_MFR(info) == SNOR_MFR_ST ||
3783            JEDEC_MFR(info) == SNOR_MFR_MICRON ||
3784            JEDEC_MFR(info) == SNOR_MFR_SST ||
3785                        info->flags & SPI_NOR_HAS_LOCK) {
3786                nor->flash_lock = stm_lock;
3787                nor->flash_unlock = stm_unlock;
3788                nor->flash_is_locked = stm_is_locked;
3789        }
3790#endif
3791
3792#ifdef CONFIG_SPI_FLASH_SST
3793        /*
3794         * sst26 series block protection implementation differs from other
3795         * series.
3796         */
3797        if (info->flags & SPI_NOR_HAS_SST26LOCK) {
3798                nor->flash_lock = sst26_lock;
3799                nor->flash_unlock = sst26_unlock;
3800                nor->flash_is_locked = sst26_is_locked;
3801        }
3802#endif
3803
3804        if (info->flags & USE_FSR)
3805                nor->flags |= SNOR_F_USE_FSR;
3806        if (info->flags & SPI_NOR_HAS_TB)
3807                nor->flags |= SNOR_F_HAS_SR_TB;
3808        if (info->flags & NO_CHIP_ERASE)
3809                nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
3810        if (info->flags & USE_CLSR)
3811                nor->flags |= SNOR_F_USE_CLSR;
3812
3813        if (info->flags & SPI_NOR_NO_ERASE)
3814                mtd->flags |= MTD_NO_ERASE;
3815
3816        nor->page_size = params.page_size;
3817        mtd->writebufsize = nor->page_size;
3818
3819        /* Some devices cannot do fast-read, no matter what DT tells us */
3820        if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
3821                params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
3822
3823        /*
3824         * Configure the SPI memory:
3825         * - select op codes for (Fast) Read, Page Program and Sector Erase.
3826         * - set the number of dummy cycles (mode cycles + wait states).
3827         * - set the SPI protocols for register and memory accesses.
3828         * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
3829         */
3830        ret = spi_nor_setup(nor, info, &params);
3831        if (ret)
3832                return ret;
3833
3834        if (spi_nor_protocol_is_dtr(nor->read_proto)) {
3835                 /* Always use 4-byte addresses in DTR mode. */
3836                nor->addr_width = 4;
3837        } else if (nor->addr_width) {
3838                /* already configured from SFDP */
3839        } else if (info->addr_width) {
3840                nor->addr_width = info->addr_width;
3841        } else {
3842                nor->addr_width = 3;
3843        }
3844
3845        if (nor->addr_width == 3 && mtd->size > SZ_16M) {
3846#ifndef CONFIG_SPI_FLASH_BAR
3847                /* enable 4-byte addressing if the device exceeds 16MiB */
3848                nor->addr_width = 4;
3849                if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
3850                    info->flags & SPI_NOR_4B_OPCODES)
3851                        spi_nor_set_4byte_opcodes(nor, info);
3852#else
3853        /* Configure the BAR - discover bank cmds and read current bank */
3854        nor->addr_width = 3;
3855        ret = read_bar(nor, info);
3856        if (ret < 0)
3857                return ret;
3858#endif
3859        }
3860
3861        if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
3862                dev_dbg(nor->dev, "address width is too large: %u\n",
3863                        nor->addr_width);
3864                return -EINVAL;
3865        }
3866
3867        /* Send all the required SPI flash commands to initialize device */
3868        ret = spi_nor_init(nor);
3869        if (ret)
3870                return ret;
3871
3872        nor->rdsr_dummy = params.rdsr_dummy;
3873        nor->rdsr_addr_nbytes = params.rdsr_addr_nbytes;
3874        nor->name = info->name;
3875        nor->size = mtd->size;
3876        nor->erase_size = mtd->erasesize;
3877        nor->sector_size = mtd->erasesize;
3878
3879#ifndef CONFIG_SPL_BUILD
3880        printf("SF: Detected %s with page size ", nor->name);
3881        print_size(nor->page_size, ", erase size ");
3882        print_size(nor->erase_size, ", total ");
3883        print_size(nor->size, "");
3884        puts("\n");
3885#endif
3886
3887        return 0;
3888}
3889
3890/* U-Boot specific functions, need to extend MTD to support these */
3891int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
3892{
3893        int sr = read_sr(nor);
3894
3895        if (sr < 0)
3896                return sr;
3897
3898        return (sr >> 2) & 7;
3899}
3900