Merge tag '6.2-rc-ksmbd-server-fixes' of git://git.samba.org/ksmbd
[linux-2.6-microblaze.git] / drivers / mtd / spi-nor / sfdp.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2005, Intec Automation Inc.
4  * Copyright (C) 2014, Freescale Semiconductor, Inc.
5  */
6
7 #include <linux/bitfield.h>
8 #include <linux/slab.h>
9 #include <linux/sort.h>
10 #include <linux/mtd/spi-nor.h>
11
12 #include "core.h"
13
14 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
15 #define SFDP_PARAM_HEADER_PTP(p) \
16         (((p)->parameter_table_pointer[2] << 16) | \
17          ((p)->parameter_table_pointer[1] <<  8) | \
18          ((p)->parameter_table_pointer[0] <<  0))
19 #define SFDP_PARAM_HEADER_PARAM_LEN(p) ((p)->length * 4)
20
21 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
22 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
23 #define SFDP_4BAIT_ID           0xff84  /* 4-byte Address Instruction Table */
24 #define SFDP_PROFILE1_ID        0xff05  /* xSPI Profile 1.0 table. */
25 #define SFDP_SCCR_MAP_ID        0xff87  /*
26                                          * Status, Control and Configuration
27                                          * Register Map.
28                                          */
29
30 #define SFDP_SIGNATURE          0x50444653U
31
32 struct sfdp_header {
33         u32             signature; /* Ox50444653U <=> "SFDP" */
34         u8              minor;
35         u8              major;
36         u8              nph; /* 0-base number of parameter headers */
37         u8              unused;
38
39         /* Basic Flash Parameter Table. */
40         struct sfdp_parameter_header    bfpt_header;
41 };
42
43 /* Fast Read settings. */
44 struct sfdp_bfpt_read {
45         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
46         u32                     hwcaps;
47
48         /*
49          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
50          * whether the Fast Read x-y-z command is supported.
51          */
52         u32                     supported_dword;
53         u32                     supported_bit;
54
55         /*
56          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
57          * encodes the op code, the number of mode clocks and the number of wait
58          * states to be used by Fast Read x-y-z command.
59          */
60         u32                     settings_dword;
61         u32                     settings_shift;
62
63         /* The SPI protocol for this Fast Read x-y-z command. */
64         enum spi_nor_protocol   proto;
65 };
66
67 struct sfdp_bfpt_erase {
68         /*
69          * The half-word at offset <shift> in DWORD <dword> encodes the
70          * op code and erase sector size to be used by Sector Erase commands.
71          */
72         u32                     dword;
73         u32                     shift;
74 };
75
76 #define SMPT_CMD_ADDRESS_LEN_MASK               GENMASK(23, 22)
77 #define SMPT_CMD_ADDRESS_LEN_0                  (0x0UL << 22)
78 #define SMPT_CMD_ADDRESS_LEN_3                  (0x1UL << 22)
79 #define SMPT_CMD_ADDRESS_LEN_4                  (0x2UL << 22)
80 #define SMPT_CMD_ADDRESS_LEN_USE_CURRENT        (0x3UL << 22)
81
82 #define SMPT_CMD_READ_DUMMY_MASK                GENMASK(19, 16)
83 #define SMPT_CMD_READ_DUMMY_SHIFT               16
84 #define SMPT_CMD_READ_DUMMY(_cmd) \
85         (((_cmd) & SMPT_CMD_READ_DUMMY_MASK) >> SMPT_CMD_READ_DUMMY_SHIFT)
86 #define SMPT_CMD_READ_DUMMY_IS_VARIABLE         0xfUL
87
88 #define SMPT_CMD_READ_DATA_MASK                 GENMASK(31, 24)
89 #define SMPT_CMD_READ_DATA_SHIFT                24
90 #define SMPT_CMD_READ_DATA(_cmd) \
91         (((_cmd) & SMPT_CMD_READ_DATA_MASK) >> SMPT_CMD_READ_DATA_SHIFT)
92
93 #define SMPT_CMD_OPCODE_MASK                    GENMASK(15, 8)
94 #define SMPT_CMD_OPCODE_SHIFT                   8
95 #define SMPT_CMD_OPCODE(_cmd) \
96         (((_cmd) & SMPT_CMD_OPCODE_MASK) >> SMPT_CMD_OPCODE_SHIFT)
97
98 #define SMPT_MAP_REGION_COUNT_MASK              GENMASK(23, 16)
99 #define SMPT_MAP_REGION_COUNT_SHIFT             16
100 #define SMPT_MAP_REGION_COUNT(_header) \
101         ((((_header) & SMPT_MAP_REGION_COUNT_MASK) >> \
102           SMPT_MAP_REGION_COUNT_SHIFT) + 1)
103
104 #define SMPT_MAP_ID_MASK                        GENMASK(15, 8)
105 #define SMPT_MAP_ID_SHIFT                       8
106 #define SMPT_MAP_ID(_header) \
107         (((_header) & SMPT_MAP_ID_MASK) >> SMPT_MAP_ID_SHIFT)
108
109 #define SMPT_MAP_REGION_SIZE_MASK               GENMASK(31, 8)
110 #define SMPT_MAP_REGION_SIZE_SHIFT              8
111 #define SMPT_MAP_REGION_SIZE(_region) \
112         (((((_region) & SMPT_MAP_REGION_SIZE_MASK) >> \
113            SMPT_MAP_REGION_SIZE_SHIFT) + 1) * 256)
114
115 #define SMPT_MAP_REGION_ERASE_TYPE_MASK         GENMASK(3, 0)
116 #define SMPT_MAP_REGION_ERASE_TYPE(_region) \
117         ((_region) & SMPT_MAP_REGION_ERASE_TYPE_MASK)
118
119 #define SMPT_DESC_TYPE_MAP                      BIT(1)
120 #define SMPT_DESC_END                           BIT(0)
121
122 #define SFDP_4BAIT_DWORD_MAX    2
123
124 struct sfdp_4bait {
125         /* The hardware capability. */
126         u32             hwcaps;
127
128         /*
129          * The <supported_bit> bit in DWORD1 of the 4BAIT tells us whether
130          * the associated 4-byte address op code is supported.
131          */
132         u32             supported_bit;
133 };
134
135 /**
136  * spi_nor_read_raw() - raw read of serial flash memory. read_opcode,
137  *                      addr_nbytes and read_dummy members of the struct spi_nor
138  *                      should be previously set.
139  * @nor:        pointer to a 'struct spi_nor'
140  * @addr:       offset in the serial flash memory
141  * @len:        number of bytes to read
142  * @buf:        buffer where the data is copied into (dma-safe memory)
143  *
144  * Return: 0 on success, -errno otherwise.
145  */
146 static int spi_nor_read_raw(struct spi_nor *nor, u32 addr, size_t len, u8 *buf)
147 {
148         ssize_t ret;
149
150         while (len) {
151                 ret = spi_nor_read_data(nor, addr, len, buf);
152                 if (ret < 0)
153                         return ret;
154                 if (!ret || ret > len)
155                         return -EIO;
156
157                 buf += ret;
158                 addr += ret;
159                 len -= ret;
160         }
161         return 0;
162 }
163
164 /**
165  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
166  * @nor:        pointer to a 'struct spi_nor'
167  * @addr:       offset in the SFDP area to start reading data from
168  * @len:        number of bytes to read
169  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
170  *
171  * Whatever the actual numbers of bytes for address and dummy cycles are
172  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
173  * followed by a 3-byte address and 8 dummy clock cycles.
174  *
175  * Return: 0 on success, -errno otherwise.
176  */
177 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
178                              size_t len, void *buf)
179 {
180         u8 addr_nbytes, read_opcode, read_dummy;
181         int ret;
182
183         read_opcode = nor->read_opcode;
184         addr_nbytes = nor->addr_nbytes;
185         read_dummy = nor->read_dummy;
186
187         nor->read_opcode = SPINOR_OP_RDSFDP;
188         nor->addr_nbytes = 3;
189         nor->read_dummy = 8;
190
191         ret = spi_nor_read_raw(nor, addr, len, buf);
192
193         nor->read_opcode = read_opcode;
194         nor->addr_nbytes = addr_nbytes;
195         nor->read_dummy = read_dummy;
196
197         return ret;
198 }
199
200 /**
201  * spi_nor_read_sfdp_dma_unsafe() - read Serial Flash Discoverable Parameters.
202  * @nor:        pointer to a 'struct spi_nor'
203  * @addr:       offset in the SFDP area to start reading data from
204  * @len:        number of bytes to read
205  * @buf:        buffer where the SFDP data are copied into
206  *
207  * Wrap spi_nor_read_sfdp() using a kmalloc'ed bounce buffer as @buf is now not
208  * guaranteed to be dma-safe.
209  *
210  * Return: -ENOMEM if kmalloc() fails, the return code of spi_nor_read_sfdp()
211  *          otherwise.
212  */
213 static int spi_nor_read_sfdp_dma_unsafe(struct spi_nor *nor, u32 addr,
214                                         size_t len, void *buf)
215 {
216         void *dma_safe_buf;
217         int ret;
218
219         dma_safe_buf = kmalloc(len, GFP_KERNEL);
220         if (!dma_safe_buf)
221                 return -ENOMEM;
222
223         ret = spi_nor_read_sfdp(nor, addr, len, dma_safe_buf);
224         memcpy(buf, dma_safe_buf, len);
225         kfree(dma_safe_buf);
226
227         return ret;
228 }
229
230 static void
231 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
232                                     u16 half,
233                                     enum spi_nor_protocol proto)
234 {
235         read->num_mode_clocks = (half >> 5) & 0x07;
236         read->num_wait_states = (half >> 0) & 0x1f;
237         read->opcode = (half >> 8) & 0xff;
238         read->proto = proto;
239 }
240
241 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
242         /* Fast Read 1-1-2 */
243         {
244                 SNOR_HWCAPS_READ_1_1_2,
245                 BFPT_DWORD(1), BIT(16), /* Supported bit */
246                 BFPT_DWORD(4), 0,       /* Settings */
247                 SNOR_PROTO_1_1_2,
248         },
249
250         /* Fast Read 1-2-2 */
251         {
252                 SNOR_HWCAPS_READ_1_2_2,
253                 BFPT_DWORD(1), BIT(20), /* Supported bit */
254                 BFPT_DWORD(4), 16,      /* Settings */
255                 SNOR_PROTO_1_2_2,
256         },
257
258         /* Fast Read 2-2-2 */
259         {
260                 SNOR_HWCAPS_READ_2_2_2,
261                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
262                 BFPT_DWORD(6), 16,      /* Settings */
263                 SNOR_PROTO_2_2_2,
264         },
265
266         /* Fast Read 1-1-4 */
267         {
268                 SNOR_HWCAPS_READ_1_1_4,
269                 BFPT_DWORD(1), BIT(22), /* Supported bit */
270                 BFPT_DWORD(3), 16,      /* Settings */
271                 SNOR_PROTO_1_1_4,
272         },
273
274         /* Fast Read 1-4-4 */
275         {
276                 SNOR_HWCAPS_READ_1_4_4,
277                 BFPT_DWORD(1), BIT(21), /* Supported bit */
278                 BFPT_DWORD(3), 0,       /* Settings */
279                 SNOR_PROTO_1_4_4,
280         },
281
282         /* Fast Read 4-4-4 */
283         {
284                 SNOR_HWCAPS_READ_4_4_4,
285                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
286                 BFPT_DWORD(7), 16,      /* Settings */
287                 SNOR_PROTO_4_4_4,
288         },
289 };
290
291 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
292         /* Erase Type 1 in DWORD8 bits[15:0] */
293         {BFPT_DWORD(8), 0},
294
295         /* Erase Type 2 in DWORD8 bits[31:16] */
296         {BFPT_DWORD(8), 16},
297
298         /* Erase Type 3 in DWORD9 bits[15:0] */
299         {BFPT_DWORD(9), 0},
300
301         /* Erase Type 4 in DWORD9 bits[31:16] */
302         {BFPT_DWORD(9), 16},
303 };
304
305 /**
306  * spi_nor_set_erase_settings_from_bfpt() - set erase type settings from BFPT
307  * @erase:      pointer to a structure that describes a SPI NOR erase type
308  * @size:       the size of the sector/block erased by the erase type
309  * @opcode:     the SPI command op code to erase the sector/block
310  * @i:          erase type index as sorted in the Basic Flash Parameter Table
311  *
312  * The supported Erase Types will be sorted at init in ascending order, with
313  * the smallest Erase Type size being the first member in the erase_type array
314  * of the spi_nor_erase_map structure. Save the Erase Type index as sorted in
315  * the Basic Flash Parameter Table since it will be used later on to
316  * synchronize with the supported Erase Types defined in SFDP optional tables.
317  */
318 static void
319 spi_nor_set_erase_settings_from_bfpt(struct spi_nor_erase_type *erase,
320                                      u32 size, u8 opcode, u8 i)
321 {
322         erase->idx = i;
323         spi_nor_set_erase_type(erase, size, opcode);
324 }
325
326 /**
327  * spi_nor_map_cmp_erase_type() - compare the map's erase types by size
328  * @l:  member in the left half of the map's erase_type array
329  * @r:  member in the right half of the map's erase_type array
330  *
331  * Comparison function used in the sort() call to sort in ascending order the
332  * map's erase types, the smallest erase type size being the first member in the
333  * sorted erase_type array.
334  *
335  * Return: the result of @l->size - @r->size
336  */
337 static int spi_nor_map_cmp_erase_type(const void *l, const void *r)
338 {
339         const struct spi_nor_erase_type *left = l, *right = r;
340
341         return left->size - right->size;
342 }
343
344 /**
345  * spi_nor_sort_erase_mask() - sort erase mask
346  * @map:        the erase map of the SPI NOR
347  * @erase_mask: the erase type mask to be sorted
348  *
349  * Replicate the sort done for the map's erase types in BFPT: sort the erase
350  * mask in ascending order with the smallest erase type size starting from
351  * BIT(0) in the sorted erase mask.
352  *
353  * Return: sorted erase mask.
354  */
355 static u8 spi_nor_sort_erase_mask(struct spi_nor_erase_map *map, u8 erase_mask)
356 {
357         struct spi_nor_erase_type *erase_type = map->erase_type;
358         int i;
359         u8 sorted_erase_mask = 0;
360
361         if (!erase_mask)
362                 return 0;
363
364         /* Replicate the sort done for the map's erase types. */
365         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++)
366                 if (erase_type[i].size && erase_mask & BIT(erase_type[i].idx))
367                         sorted_erase_mask |= BIT(i);
368
369         return sorted_erase_mask;
370 }
371
372 /**
373  * spi_nor_regions_sort_erase_types() - sort erase types in each region
374  * @map:        the erase map of the SPI NOR
375  *
376  * Function assumes that the erase types defined in the erase map are already
377  * sorted in ascending order, with the smallest erase type size being the first
378  * member in the erase_type array. It replicates the sort done for the map's
379  * erase types. Each region's erase bitmask will indicate which erase types are
380  * supported from the sorted erase types defined in the erase map.
381  * Sort the all region's erase type at init in order to speed up the process of
382  * finding the best erase command at runtime.
383  */
384 static void spi_nor_regions_sort_erase_types(struct spi_nor_erase_map *map)
385 {
386         struct spi_nor_erase_region *region = map->regions;
387         u8 region_erase_mask, sorted_erase_mask;
388
389         while (region) {
390                 region_erase_mask = region->offset & SNOR_ERASE_TYPE_MASK;
391
392                 sorted_erase_mask = spi_nor_sort_erase_mask(map,
393                                                             region_erase_mask);
394
395                 /* Overwrite erase mask. */
396                 region->offset = (region->offset & ~SNOR_ERASE_TYPE_MASK) |
397                                  sorted_erase_mask;
398
399                 region = spi_nor_region_next(region);
400         }
401 }
402
403 /**
404  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
405  * @nor:                pointer to a 'struct spi_nor'
406  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
407  *                      the Basic Flash Parameter Table length and version
408  *
409  * The Basic Flash Parameter Table is the main and only mandatory table as
410  * defined by the SFDP (JESD216) specification.
411  * It provides us with the total size (memory density) of the data array and
412  * the number of address bytes for Fast Read, Page Program and Sector Erase
413  * commands.
414  * For Fast READ commands, it also gives the number of mode clock cycles and
415  * wait states (regrouped in the number of dummy clock cycles) for each
416  * supported instruction op code.
417  * For Page Program, the page size is now available since JESD216 rev A, however
418  * the supported instruction op codes are still not provided.
419  * For Sector Erase commands, this table stores the supported instruction op
420  * codes and the associated sector sizes.
421  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
422  * rev A. The QER bits encode the manufacturer dependent procedure to be
423  * executed to set the Quad Enable (QE) bit in some internal register of the
424  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
425  * sending any Quad SPI command to the memory. Actually, setting the QE bit
426  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
427  * and IO3 hence enabling 4 (Quad) I/O lines.
428  *
429  * Return: 0 on success, -errno otherwise.
430  */
431 static int spi_nor_parse_bfpt(struct spi_nor *nor,
432                               const struct sfdp_parameter_header *bfpt_header)
433 {
434         struct spi_nor_flash_parameter *params = nor->params;
435         struct spi_nor_erase_map *map = &params->erase_map;
436         struct spi_nor_erase_type *erase_type = map->erase_type;
437         struct sfdp_bfpt bfpt;
438         size_t len;
439         int i, cmd, err;
440         u32 addr, val;
441         u16 half;
442         u8 erase_mask;
443
444         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
445         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
446                 return -EINVAL;
447
448         /* Read the Basic Flash Parameter Table. */
449         len = min_t(size_t, sizeof(bfpt),
450                     bfpt_header->length * sizeof(u32));
451         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
452         memset(&bfpt, 0, sizeof(bfpt));
453         err = spi_nor_read_sfdp_dma_unsafe(nor,  addr, len, &bfpt);
454         if (err < 0)
455                 return err;
456
457         /* Fix endianness of the BFPT DWORDs. */
458         le32_to_cpu_array(bfpt.dwords, BFPT_DWORD_MAX);
459
460         /* Number of address bytes. */
461         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
462         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
463         case BFPT_DWORD1_ADDRESS_BYTES_3_OR_4:
464                 params->addr_nbytes = 3;
465                 params->addr_mode_nbytes = 3;
466                 break;
467
468         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
469                 params->addr_nbytes = 4;
470                 params->addr_mode_nbytes = 4;
471                 break;
472
473         default:
474                 break;
475         }
476
477         /* Flash Memory Density (in bits). */
478         val = bfpt.dwords[BFPT_DWORD(2)];
479         if (val & BIT(31)) {
480                 val &= ~BIT(31);
481
482                 /*
483                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
484                  * bits is unlikely to exist so this error probably means
485                  * the BFPT we are reading is corrupted/wrong.
486                  */
487                 if (val > 63)
488                         return -EINVAL;
489
490                 params->size = 1ULL << val;
491         } else {
492                 params->size = val + 1;
493         }
494         params->size >>= 3; /* Convert to bytes. */
495
496         /* Fast Read settings. */
497         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
498                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
499                 struct spi_nor_read_command *read;
500
501                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
502                         params->hwcaps.mask &= ~rd->hwcaps;
503                         continue;
504                 }
505
506                 params->hwcaps.mask |= rd->hwcaps;
507                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
508                 read = &params->reads[cmd];
509                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
510                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
511         }
512
513         /*
514          * Sector Erase settings. Reinitialize the uniform erase map using the
515          * Erase Types defined in the bfpt table.
516          */
517         erase_mask = 0;
518         memset(&params->erase_map, 0, sizeof(params->erase_map));
519         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
520                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
521                 u32 erasesize;
522                 u8 opcode;
523
524                 half = bfpt.dwords[er->dword] >> er->shift;
525                 erasesize = half & 0xff;
526
527                 /* erasesize == 0 means this Erase Type is not supported. */
528                 if (!erasesize)
529                         continue;
530
531                 erasesize = 1U << erasesize;
532                 opcode = (half >> 8) & 0xff;
533                 erase_mask |= BIT(i);
534                 spi_nor_set_erase_settings_from_bfpt(&erase_type[i], erasesize,
535                                                      opcode, i);
536         }
537         spi_nor_init_uniform_erase_map(map, erase_mask, params->size);
538         /*
539          * Sort all the map's Erase Types in ascending order with the smallest
540          * erase size being the first member in the erase_type array.
541          */
542         sort(erase_type, SNOR_ERASE_TYPE_MAX, sizeof(erase_type[0]),
543              spi_nor_map_cmp_erase_type, NULL);
544         /*
545          * Sort the erase types in the uniform region in order to update the
546          * uniform_erase_type bitmask. The bitmask will be used later on when
547          * selecting the uniform erase.
548          */
549         spi_nor_regions_sort_erase_types(map);
550         map->uniform_erase_type = map->uniform_region.offset &
551                                   SNOR_ERASE_TYPE_MASK;
552
553         /* Stop here if not JESD216 rev A or later. */
554         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216)
555                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt);
556
557         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
558         val = bfpt.dwords[BFPT_DWORD(11)];
559         val &= BFPT_DWORD11_PAGE_SIZE_MASK;
560         val >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
561         params->page_size = 1U << val;
562
563         /* Quad Enable Requirements. */
564         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
565         case BFPT_DWORD15_QER_NONE:
566                 params->quad_enable = NULL;
567                 break;
568
569         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
570                 /*
571                  * Writing only one byte to the Status Register has the
572                  * side-effect of clearing Status Register 2.
573                  */
574         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
575                 /*
576                  * Read Configuration Register (35h) instruction is not
577                  * supported.
578                  */
579                 nor->flags |= SNOR_F_HAS_16BIT_SR | SNOR_F_NO_READ_CR;
580                 params->quad_enable = spi_nor_sr2_bit1_quad_enable;
581                 break;
582
583         case BFPT_DWORD15_QER_SR1_BIT6:
584                 nor->flags &= ~SNOR_F_HAS_16BIT_SR;
585                 params->quad_enable = spi_nor_sr1_bit6_quad_enable;
586                 break;
587
588         case BFPT_DWORD15_QER_SR2_BIT7:
589                 nor->flags &= ~SNOR_F_HAS_16BIT_SR;
590                 params->quad_enable = spi_nor_sr2_bit7_quad_enable;
591                 break;
592
593         case BFPT_DWORD15_QER_SR2_BIT1:
594                 /*
595                  * JESD216 rev B or later does not specify if writing only one
596                  * byte to the Status Register clears or not the Status
597                  * Register 2, so let's be cautious and keep the default
598                  * assumption of a 16-bit Write Status (01h) command.
599                  */
600                 nor->flags |= SNOR_F_HAS_16BIT_SR;
601
602                 params->quad_enable = spi_nor_sr2_bit1_quad_enable;
603                 break;
604
605         default:
606                 dev_dbg(nor->dev, "BFPT QER reserved value used\n");
607                 break;
608         }
609
610         /* Soft Reset support. */
611         if (bfpt.dwords[BFPT_DWORD(16)] & BFPT_DWORD16_SWRST_EN_RST)
612                 nor->flags |= SNOR_F_SOFT_RESET;
613
614         /* Stop here if not JESD216 rev C or later. */
615         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216B)
616                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt);
617
618         /* 8D-8D-8D command extension. */
619         switch (bfpt.dwords[BFPT_DWORD(18)] & BFPT_DWORD18_CMD_EXT_MASK) {
620         case BFPT_DWORD18_CMD_EXT_REP:
621                 nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
622                 break;
623
624         case BFPT_DWORD18_CMD_EXT_INV:
625                 nor->cmd_ext_type = SPI_NOR_EXT_INVERT;
626                 break;
627
628         case BFPT_DWORD18_CMD_EXT_RES:
629                 dev_dbg(nor->dev, "Reserved command extension used\n");
630                 break;
631
632         case BFPT_DWORD18_CMD_EXT_16B:
633                 dev_dbg(nor->dev, "16-bit opcodes not supported\n");
634                 return -EOPNOTSUPP;
635         }
636
637         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt);
638 }
639
640 /**
641  * spi_nor_smpt_addr_nbytes() - return the number of address bytes used in the
642  *                             configuration detection command.
643  * @nor:        pointer to a 'struct spi_nor'
644  * @settings:   configuration detection command descriptor, dword1
645  */
646 static u8 spi_nor_smpt_addr_nbytes(const struct spi_nor *nor, const u32 settings)
647 {
648         switch (settings & SMPT_CMD_ADDRESS_LEN_MASK) {
649         case SMPT_CMD_ADDRESS_LEN_0:
650                 return 0;
651         case SMPT_CMD_ADDRESS_LEN_3:
652                 return 3;
653         case SMPT_CMD_ADDRESS_LEN_4:
654                 return 4;
655         case SMPT_CMD_ADDRESS_LEN_USE_CURRENT:
656         default:
657                 return nor->params->addr_mode_nbytes;
658         }
659 }
660
661 /**
662  * spi_nor_smpt_read_dummy() - return the configuration detection command read
663  *                             latency, in clock cycles.
664  * @nor:        pointer to a 'struct spi_nor'
665  * @settings:   configuration detection command descriptor, dword1
666  *
667  * Return: the number of dummy cycles for an SMPT read
668  */
669 static u8 spi_nor_smpt_read_dummy(const struct spi_nor *nor, const u32 settings)
670 {
671         u8 read_dummy = SMPT_CMD_READ_DUMMY(settings);
672
673         if (read_dummy == SMPT_CMD_READ_DUMMY_IS_VARIABLE)
674                 return nor->read_dummy;
675         return read_dummy;
676 }
677
678 /**
679  * spi_nor_get_map_in_use() - get the configuration map in use
680  * @nor:        pointer to a 'struct spi_nor'
681  * @smpt:       pointer to the sector map parameter table
682  * @smpt_len:   sector map parameter table length
683  *
684  * Return: pointer to the map in use, ERR_PTR(-errno) otherwise.
685  */
686 static const u32 *spi_nor_get_map_in_use(struct spi_nor *nor, const u32 *smpt,
687                                          u8 smpt_len)
688 {
689         const u32 *ret;
690         u8 *buf;
691         u32 addr;
692         int err;
693         u8 i;
694         u8 addr_nbytes, read_opcode, read_dummy;
695         u8 read_data_mask, map_id;
696
697         /* Use a kmalloc'ed bounce buffer to guarantee it is DMA-able. */
698         buf = kmalloc(sizeof(*buf), GFP_KERNEL);
699         if (!buf)
700                 return ERR_PTR(-ENOMEM);
701
702         addr_nbytes = nor->addr_nbytes;
703         read_dummy = nor->read_dummy;
704         read_opcode = nor->read_opcode;
705
706         map_id = 0;
707         /* Determine if there are any optional Detection Command Descriptors */
708         for (i = 0; i < smpt_len; i += 2) {
709                 if (smpt[i] & SMPT_DESC_TYPE_MAP)
710                         break;
711
712                 read_data_mask = SMPT_CMD_READ_DATA(smpt[i]);
713                 nor->addr_nbytes = spi_nor_smpt_addr_nbytes(nor, smpt[i]);
714                 nor->read_dummy = spi_nor_smpt_read_dummy(nor, smpt[i]);
715                 nor->read_opcode = SMPT_CMD_OPCODE(smpt[i]);
716                 addr = smpt[i + 1];
717
718                 err = spi_nor_read_raw(nor, addr, 1, buf);
719                 if (err) {
720                         ret = ERR_PTR(err);
721                         goto out;
722                 }
723
724                 /*
725                  * Build an index value that is used to select the Sector Map
726                  * Configuration that is currently in use.
727                  */
728                 map_id = map_id << 1 | !!(*buf & read_data_mask);
729         }
730
731         /*
732          * If command descriptors are provided, they always precede map
733          * descriptors in the table. There is no need to start the iteration
734          * over smpt array all over again.
735          *
736          * Find the matching configuration map.
737          */
738         ret = ERR_PTR(-EINVAL);
739         while (i < smpt_len) {
740                 if (SMPT_MAP_ID(smpt[i]) == map_id) {
741                         ret = smpt + i;
742                         break;
743                 }
744
745                 /*
746                  * If there are no more configuration map descriptors and no
747                  * configuration ID matched the configuration identifier, the
748                  * sector address map is unknown.
749                  */
750                 if (smpt[i] & SMPT_DESC_END)
751                         break;
752
753                 /* increment the table index to the next map */
754                 i += SMPT_MAP_REGION_COUNT(smpt[i]) + 1;
755         }
756
757         /* fall through */
758 out:
759         kfree(buf);
760         nor->addr_nbytes = addr_nbytes;
761         nor->read_dummy = read_dummy;
762         nor->read_opcode = read_opcode;
763         return ret;
764 }
765
766 static void spi_nor_region_mark_end(struct spi_nor_erase_region *region)
767 {
768         region->offset |= SNOR_LAST_REGION;
769 }
770
771 static void spi_nor_region_mark_overlay(struct spi_nor_erase_region *region)
772 {
773         region->offset |= SNOR_OVERLAID_REGION;
774 }
775
776 /**
777  * spi_nor_region_check_overlay() - set overlay bit when the region is overlaid
778  * @region:     pointer to a structure that describes a SPI NOR erase region
779  * @erase:      pointer to a structure that describes a SPI NOR erase type
780  * @erase_type: erase type bitmask
781  */
782 static void
783 spi_nor_region_check_overlay(struct spi_nor_erase_region *region,
784                              const struct spi_nor_erase_type *erase,
785                              const u8 erase_type)
786 {
787         int i;
788
789         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
790                 if (!(erase[i].size && erase_type & BIT(erase[i].idx)))
791                         continue;
792                 if (region->size & erase[i].size_mask) {
793                         spi_nor_region_mark_overlay(region);
794                         return;
795                 }
796         }
797 }
798
799 /**
800  * spi_nor_init_non_uniform_erase_map() - initialize the non-uniform erase map
801  * @nor:        pointer to a 'struct spi_nor'
802  * @smpt:       pointer to the sector map parameter table
803  *
804  * Return: 0 on success, -errno otherwise.
805  */
806 static int spi_nor_init_non_uniform_erase_map(struct spi_nor *nor,
807                                               const u32 *smpt)
808 {
809         struct spi_nor_erase_map *map = &nor->params->erase_map;
810         struct spi_nor_erase_type *erase = map->erase_type;
811         struct spi_nor_erase_region *region;
812         u64 offset;
813         u32 region_count;
814         int i, j;
815         u8 uniform_erase_type, save_uniform_erase_type;
816         u8 erase_type, regions_erase_type;
817
818         region_count = SMPT_MAP_REGION_COUNT(*smpt);
819         /*
820          * The regions will be freed when the driver detaches from the
821          * device.
822          */
823         region = devm_kcalloc(nor->dev, region_count, sizeof(*region),
824                               GFP_KERNEL);
825         if (!region)
826                 return -ENOMEM;
827         map->regions = region;
828
829         uniform_erase_type = 0xff;
830         regions_erase_type = 0;
831         offset = 0;
832         /* Populate regions. */
833         for (i = 0; i < region_count; i++) {
834                 j = i + 1; /* index for the region dword */
835                 region[i].size = SMPT_MAP_REGION_SIZE(smpt[j]);
836                 erase_type = SMPT_MAP_REGION_ERASE_TYPE(smpt[j]);
837                 region[i].offset = offset | erase_type;
838
839                 spi_nor_region_check_overlay(&region[i], erase, erase_type);
840
841                 /*
842                  * Save the erase types that are supported in all regions and
843                  * can erase the entire flash memory.
844                  */
845                 uniform_erase_type &= erase_type;
846
847                 /*
848                  * regions_erase_type mask will indicate all the erase types
849                  * supported in this configuration map.
850                  */
851                 regions_erase_type |= erase_type;
852
853                 offset = (region[i].offset & ~SNOR_ERASE_FLAGS_MASK) +
854                          region[i].size;
855         }
856         spi_nor_region_mark_end(&region[i - 1]);
857
858         save_uniform_erase_type = map->uniform_erase_type;
859         map->uniform_erase_type = spi_nor_sort_erase_mask(map,
860                                                           uniform_erase_type);
861
862         if (!regions_erase_type) {
863                 /*
864                  * Roll back to the previous uniform_erase_type mask, SMPT is
865                  * broken.
866                  */
867                 map->uniform_erase_type = save_uniform_erase_type;
868                 return -EINVAL;
869         }
870
871         /*
872          * BFPT advertises all the erase types supported by all the possible
873          * map configurations. Mask out the erase types that are not supported
874          * by the current map configuration.
875          */
876         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++)
877                 if (!(regions_erase_type & BIT(erase[i].idx)))
878                         spi_nor_set_erase_type(&erase[i], 0, 0xFF);
879
880         return 0;
881 }
882
883 /**
884  * spi_nor_parse_smpt() - parse Sector Map Parameter Table
885  * @nor:                pointer to a 'struct spi_nor'
886  * @smpt_header:        sector map parameter table header
887  *
888  * This table is optional, but when available, we parse it to identify the
889  * location and size of sectors within the main data array of the flash memory
890  * device and to identify which Erase Types are supported by each sector.
891  *
892  * Return: 0 on success, -errno otherwise.
893  */
894 static int spi_nor_parse_smpt(struct spi_nor *nor,
895                               const struct sfdp_parameter_header *smpt_header)
896 {
897         const u32 *sector_map;
898         u32 *smpt;
899         size_t len;
900         u32 addr;
901         int ret;
902
903         /* Read the Sector Map Parameter Table. */
904         len = smpt_header->length * sizeof(*smpt);
905         smpt = kmalloc(len, GFP_KERNEL);
906         if (!smpt)
907                 return -ENOMEM;
908
909         addr = SFDP_PARAM_HEADER_PTP(smpt_header);
910         ret = spi_nor_read_sfdp(nor, addr, len, smpt);
911         if (ret)
912                 goto out;
913
914         /* Fix endianness of the SMPT DWORDs. */
915         le32_to_cpu_array(smpt, smpt_header->length);
916
917         sector_map = spi_nor_get_map_in_use(nor, smpt, smpt_header->length);
918         if (IS_ERR(sector_map)) {
919                 ret = PTR_ERR(sector_map);
920                 goto out;
921         }
922
923         ret = spi_nor_init_non_uniform_erase_map(nor, sector_map);
924         if (ret)
925                 goto out;
926
927         spi_nor_regions_sort_erase_types(&nor->params->erase_map);
928         /* fall through */
929 out:
930         kfree(smpt);
931         return ret;
932 }
933
934 /**
935  * spi_nor_parse_4bait() - parse the 4-Byte Address Instruction Table
936  * @nor:                pointer to a 'struct spi_nor'.
937  * @param_header:       pointer to the 'struct sfdp_parameter_header' describing
938  *                      the 4-Byte Address Instruction Table length and version.
939  *
940  * Return: 0 on success, -errno otherwise.
941  */
942 static int spi_nor_parse_4bait(struct spi_nor *nor,
943                                const struct sfdp_parameter_header *param_header)
944 {
945         static const struct sfdp_4bait reads[] = {
946                 { SNOR_HWCAPS_READ,             BIT(0) },
947                 { SNOR_HWCAPS_READ_FAST,        BIT(1) },
948                 { SNOR_HWCAPS_READ_1_1_2,       BIT(2) },
949                 { SNOR_HWCAPS_READ_1_2_2,       BIT(3) },
950                 { SNOR_HWCAPS_READ_1_1_4,       BIT(4) },
951                 { SNOR_HWCAPS_READ_1_4_4,       BIT(5) },
952                 { SNOR_HWCAPS_READ_1_1_1_DTR,   BIT(13) },
953                 { SNOR_HWCAPS_READ_1_2_2_DTR,   BIT(14) },
954                 { SNOR_HWCAPS_READ_1_4_4_DTR,   BIT(15) },
955         };
956         static const struct sfdp_4bait programs[] = {
957                 { SNOR_HWCAPS_PP,               BIT(6) },
958                 { SNOR_HWCAPS_PP_1_1_4,         BIT(7) },
959                 { SNOR_HWCAPS_PP_1_4_4,         BIT(8) },
960         };
961         static const struct sfdp_4bait erases[SNOR_ERASE_TYPE_MAX] = {
962                 { 0u /* not used */,            BIT(9) },
963                 { 0u /* not used */,            BIT(10) },
964                 { 0u /* not used */,            BIT(11) },
965                 { 0u /* not used */,            BIT(12) },
966         };
967         struct spi_nor_flash_parameter *params = nor->params;
968         struct spi_nor_pp_command *params_pp = params->page_programs;
969         struct spi_nor_erase_map *map = &params->erase_map;
970         struct spi_nor_erase_type *erase_type = map->erase_type;
971         u32 *dwords;
972         size_t len;
973         u32 addr, discard_hwcaps, read_hwcaps, pp_hwcaps, erase_mask;
974         int i, ret;
975
976         if (param_header->major != SFDP_JESD216_MAJOR ||
977             param_header->length < SFDP_4BAIT_DWORD_MAX)
978                 return -EINVAL;
979
980         /* Read the 4-byte Address Instruction Table. */
981         len = sizeof(*dwords) * SFDP_4BAIT_DWORD_MAX;
982
983         /* Use a kmalloc'ed bounce buffer to guarantee it is DMA-able. */
984         dwords = kmalloc(len, GFP_KERNEL);
985         if (!dwords)
986                 return -ENOMEM;
987
988         addr = SFDP_PARAM_HEADER_PTP(param_header);
989         ret = spi_nor_read_sfdp(nor, addr, len, dwords);
990         if (ret)
991                 goto out;
992
993         /* Fix endianness of the 4BAIT DWORDs. */
994         le32_to_cpu_array(dwords, SFDP_4BAIT_DWORD_MAX);
995
996         /*
997          * Compute the subset of (Fast) Read commands for which the 4-byte
998          * version is supported.
999          */
1000         discard_hwcaps = 0;
1001         read_hwcaps = 0;
1002         for (i = 0; i < ARRAY_SIZE(reads); i++) {
1003                 const struct sfdp_4bait *read = &reads[i];
1004
1005                 discard_hwcaps |= read->hwcaps;
1006                 if ((params->hwcaps.mask & read->hwcaps) &&
1007                     (dwords[0] & read->supported_bit))
1008                         read_hwcaps |= read->hwcaps;
1009         }
1010
1011         /*
1012          * Compute the subset of Page Program commands for which the 4-byte
1013          * version is supported.
1014          */
1015         pp_hwcaps = 0;
1016         for (i = 0; i < ARRAY_SIZE(programs); i++) {
1017                 const struct sfdp_4bait *program = &programs[i];
1018
1019                 /*
1020                  * The 4 Byte Address Instruction (Optional) Table is the only
1021                  * SFDP table that indicates support for Page Program Commands.
1022                  * Bypass the params->hwcaps.mask and consider 4BAIT the biggest
1023                  * authority for specifying Page Program support.
1024                  */
1025                 discard_hwcaps |= program->hwcaps;
1026                 if (dwords[0] & program->supported_bit)
1027                         pp_hwcaps |= program->hwcaps;
1028         }
1029
1030         /*
1031          * Compute the subset of Sector Erase commands for which the 4-byte
1032          * version is supported.
1033          */
1034         erase_mask = 0;
1035         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
1036                 const struct sfdp_4bait *erase = &erases[i];
1037
1038                 if (dwords[0] & erase->supported_bit)
1039                         erase_mask |= BIT(i);
1040         }
1041
1042         /* Replicate the sort done for the map's erase types in BFPT. */
1043         erase_mask = spi_nor_sort_erase_mask(map, erase_mask);
1044
1045         /*
1046          * We need at least one 4-byte op code per read, program and erase
1047          * operation; the .read(), .write() and .erase() hooks share the
1048          * nor->addr_nbytes value.
1049          */
1050         if (!read_hwcaps || !pp_hwcaps || !erase_mask)
1051                 goto out;
1052
1053         /*
1054          * Discard all operations from the 4-byte instruction set which are
1055          * not supported by this memory.
1056          */
1057         params->hwcaps.mask &= ~discard_hwcaps;
1058         params->hwcaps.mask |= (read_hwcaps | pp_hwcaps);
1059
1060         /* Use the 4-byte address instruction set. */
1061         for (i = 0; i < SNOR_CMD_READ_MAX; i++) {
1062                 struct spi_nor_read_command *read_cmd = &params->reads[i];
1063
1064                 read_cmd->opcode = spi_nor_convert_3to4_read(read_cmd->opcode);
1065         }
1066
1067         /* 4BAIT is the only SFDP table that indicates page program support. */
1068         if (pp_hwcaps & SNOR_HWCAPS_PP) {
1069                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP],
1070                                         SPINOR_OP_PP_4B, SNOR_PROTO_1_1_1);
1071                 /*
1072                  * Since xSPI Page Program opcode is backward compatible with
1073                  * Legacy SPI, use Legacy SPI opcode there as well.
1074                  */
1075                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP_8_8_8_DTR],
1076                                         SPINOR_OP_PP_4B, SNOR_PROTO_8_8_8_DTR);
1077         }
1078         if (pp_hwcaps & SNOR_HWCAPS_PP_1_1_4)
1079                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP_1_1_4],
1080                                         SPINOR_OP_PP_1_1_4_4B,
1081                                         SNOR_PROTO_1_1_4);
1082         if (pp_hwcaps & SNOR_HWCAPS_PP_1_4_4)
1083                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP_1_4_4],
1084                                         SPINOR_OP_PP_1_4_4_4B,
1085                                         SNOR_PROTO_1_4_4);
1086
1087         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
1088                 if (erase_mask & BIT(i))
1089                         erase_type[i].opcode = (dwords[1] >>
1090                                                 erase_type[i].idx * 8) & 0xFF;
1091                 else
1092                         spi_nor_set_erase_type(&erase_type[i], 0u, 0xFF);
1093         }
1094
1095         /*
1096          * We set SNOR_F_HAS_4BAIT in order to skip spi_nor_set_4byte_opcodes()
1097          * later because we already did the conversion to 4byte opcodes. Also,
1098          * this latest function implements a legacy quirk for the erase size of
1099          * Spansion memory. However this quirk is no longer needed with new
1100          * SFDP compliant memories.
1101          */
1102         params->addr_nbytes = 4;
1103         nor->flags |= SNOR_F_4B_OPCODES | SNOR_F_HAS_4BAIT;
1104
1105         /* fall through */
1106 out:
1107         kfree(dwords);
1108         return ret;
1109 }
1110
1111 #define PROFILE1_DWORD1_RDSR_ADDR_BYTES         BIT(29)
1112 #define PROFILE1_DWORD1_RDSR_DUMMY              BIT(28)
1113 #define PROFILE1_DWORD1_RD_FAST_CMD             GENMASK(15, 8)
1114 #define PROFILE1_DWORD4_DUMMY_200MHZ            GENMASK(11, 7)
1115 #define PROFILE1_DWORD5_DUMMY_166MHZ            GENMASK(31, 27)
1116 #define PROFILE1_DWORD5_DUMMY_133MHZ            GENMASK(21, 17)
1117 #define PROFILE1_DWORD5_DUMMY_100MHZ            GENMASK(11, 7)
1118
1119 /**
1120  * spi_nor_parse_profile1() - parse the xSPI Profile 1.0 table
1121  * @nor:                pointer to a 'struct spi_nor'
1122  * @profile1_header:    pointer to the 'struct sfdp_parameter_header' describing
1123  *                      the Profile 1.0 Table length and version.
1124  *
1125  * Return: 0 on success, -errno otherwise.
1126  */
1127 static int spi_nor_parse_profile1(struct spi_nor *nor,
1128                                   const struct sfdp_parameter_header *profile1_header)
1129 {
1130         u32 *dwords, addr;
1131         size_t len;
1132         int ret;
1133         u8 dummy, opcode;
1134
1135         len = profile1_header->length * sizeof(*dwords);
1136         dwords = kmalloc(len, GFP_KERNEL);
1137         if (!dwords)
1138                 return -ENOMEM;
1139
1140         addr = SFDP_PARAM_HEADER_PTP(profile1_header);
1141         ret = spi_nor_read_sfdp(nor, addr, len, dwords);
1142         if (ret)
1143                 goto out;
1144
1145         le32_to_cpu_array(dwords, profile1_header->length);
1146
1147         /* Get 8D-8D-8D fast read opcode and dummy cycles. */
1148         opcode = FIELD_GET(PROFILE1_DWORD1_RD_FAST_CMD, dwords[0]);
1149
1150          /* Set the Read Status Register dummy cycles and dummy address bytes. */
1151         if (dwords[0] & PROFILE1_DWORD1_RDSR_DUMMY)
1152                 nor->params->rdsr_dummy = 8;
1153         else
1154                 nor->params->rdsr_dummy = 4;
1155
1156         if (dwords[0] & PROFILE1_DWORD1_RDSR_ADDR_BYTES)
1157                 nor->params->rdsr_addr_nbytes = 4;
1158         else
1159                 nor->params->rdsr_addr_nbytes = 0;
1160
1161         /*
1162          * We don't know what speed the controller is running at. Find the
1163          * dummy cycles for the fastest frequency the flash can run at to be
1164          * sure we are never short of dummy cycles. A value of 0 means the
1165          * frequency is not supported.
1166          *
1167          * Default to PROFILE1_DUMMY_DEFAULT if we don't find anything, and let
1168          * flashes set the correct value if needed in their fixup hooks.
1169          */
1170         dummy = FIELD_GET(PROFILE1_DWORD4_DUMMY_200MHZ, dwords[3]);
1171         if (!dummy)
1172                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_166MHZ, dwords[4]);
1173         if (!dummy)
1174                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_133MHZ, dwords[4]);
1175         if (!dummy)
1176                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_100MHZ, dwords[4]);
1177         if (!dummy)
1178                 dev_dbg(nor->dev,
1179                         "Can't find dummy cycles from Profile 1.0 table\n");
1180
1181         /* Round up to an even value to avoid tripping controllers up. */
1182         dummy = round_up(dummy, 2);
1183
1184         /* Update the fast read settings. */
1185         nor->params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
1186         spi_nor_set_read_settings(&nor->params->reads[SNOR_CMD_READ_8_8_8_DTR],
1187                                   0, dummy, opcode,
1188                                   SNOR_PROTO_8_8_8_DTR);
1189
1190         /*
1191          * Page Program is "Required Command" in the xSPI Profile 1.0. Update
1192          * the params->hwcaps.mask here.
1193          */
1194         nor->params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
1195
1196 out:
1197         kfree(dwords);
1198         return ret;
1199 }
1200
1201 #define SCCR_DWORD22_OCTAL_DTR_EN_VOLATILE              BIT(31)
1202
1203 /**
1204  * spi_nor_parse_sccr() - Parse the Status, Control and Configuration Register
1205  *                        Map.
1206  * @nor:                pointer to a 'struct spi_nor'
1207  * @sccr_header:        pointer to the 'struct sfdp_parameter_header' describing
1208  *                      the SCCR Map table length and version.
1209  *
1210  * Return: 0 on success, -errno otherwise.
1211  */
1212 static int spi_nor_parse_sccr(struct spi_nor *nor,
1213                               const struct sfdp_parameter_header *sccr_header)
1214 {
1215         u32 *dwords, addr;
1216         size_t len;
1217         int ret;
1218
1219         len = sccr_header->length * sizeof(*dwords);
1220         dwords = kmalloc(len, GFP_KERNEL);
1221         if (!dwords)
1222                 return -ENOMEM;
1223
1224         addr = SFDP_PARAM_HEADER_PTP(sccr_header);
1225         ret = spi_nor_read_sfdp(nor, addr, len, dwords);
1226         if (ret)
1227                 goto out;
1228
1229         le32_to_cpu_array(dwords, sccr_header->length);
1230
1231         if (FIELD_GET(SCCR_DWORD22_OCTAL_DTR_EN_VOLATILE, dwords[22]))
1232                 nor->flags |= SNOR_F_IO_MODE_EN_VOLATILE;
1233
1234 out:
1235         kfree(dwords);
1236         return ret;
1237 }
1238
1239 /**
1240  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
1241  * after SFDP has been parsed. Called only for flashes that define JESD216 SFDP
1242  * tables.
1243  * @nor:        pointer to a 'struct spi_nor'
1244  *
1245  * Used to tweak various flash parameters when information provided by the SFDP
1246  * tables are wrong.
1247  */
1248 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor)
1249 {
1250         if (nor->manufacturer && nor->manufacturer->fixups &&
1251             nor->manufacturer->fixups->post_sfdp)
1252                 nor->manufacturer->fixups->post_sfdp(nor);
1253
1254         if (nor->info->fixups && nor->info->fixups->post_sfdp)
1255                 nor->info->fixups->post_sfdp(nor);
1256 }
1257
1258 /**
1259  * spi_nor_check_sfdp_signature() - check for a valid SFDP signature
1260  * @nor:        pointer to a 'struct spi_nor'
1261  *
1262  * Used to detect if the flash supports the RDSFDP command as well as the
1263  * presence of a valid SFDP table.
1264  *
1265  * Return: 0 on success, -errno otherwise.
1266  */
1267 int spi_nor_check_sfdp_signature(struct spi_nor *nor)
1268 {
1269         u32 signature;
1270         int err;
1271
1272         /* Get the SFDP header. */
1273         err = spi_nor_read_sfdp_dma_unsafe(nor, 0, sizeof(signature),
1274                                            &signature);
1275         if (err < 0)
1276                 return err;
1277
1278         /* Check the SFDP signature. */
1279         if (le32_to_cpu(signature) != SFDP_SIGNATURE)
1280                 return -EINVAL;
1281
1282         return 0;
1283 }
1284
1285 /**
1286  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
1287  * @nor:                pointer to a 'struct spi_nor'
1288  *
1289  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
1290  * specification. This is a standard which tends to supported by almost all
1291  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
1292  * runtime the main parameters needed to perform basic SPI flash operations such
1293  * as Fast Read, Page Program or Sector Erase commands.
1294  *
1295  * Return: 0 on success, -errno otherwise.
1296  */
1297 int spi_nor_parse_sfdp(struct spi_nor *nor)
1298 {
1299         const struct sfdp_parameter_header *param_header, *bfpt_header;
1300         struct sfdp_parameter_header *param_headers = NULL;
1301         struct sfdp_header header;
1302         struct device *dev = nor->dev;
1303         struct sfdp *sfdp;
1304         size_t sfdp_size;
1305         size_t psize;
1306         int i, err;
1307
1308         /* Get the SFDP header. */
1309         err = spi_nor_read_sfdp_dma_unsafe(nor, 0, sizeof(header), &header);
1310         if (err < 0)
1311                 return err;
1312
1313         /* Check the SFDP header version. */
1314         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
1315             header.major != SFDP_JESD216_MAJOR)
1316                 return -EINVAL;
1317
1318         /*
1319          * Verify that the first and only mandatory parameter header is a
1320          * Basic Flash Parameter Table header as specified in JESD216.
1321          */
1322         bfpt_header = &header.bfpt_header;
1323         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
1324             bfpt_header->major != SFDP_JESD216_MAJOR)
1325                 return -EINVAL;
1326
1327         sfdp_size = SFDP_PARAM_HEADER_PTP(bfpt_header) +
1328                     SFDP_PARAM_HEADER_PARAM_LEN(bfpt_header);
1329
1330         /*
1331          * Allocate memory then read all parameter headers with a single
1332          * Read SFDP command. These parameter headers will actually be parsed
1333          * twice: a first time to get the latest revision of the basic flash
1334          * parameter table, then a second time to handle the supported optional
1335          * tables.
1336          * Hence we read the parameter headers once for all to reduce the
1337          * processing time. Also we use kmalloc() instead of devm_kmalloc()
1338          * because we don't need to keep these parameter headers: the allocated
1339          * memory is always released with kfree() before exiting this function.
1340          */
1341         if (header.nph) {
1342                 psize = header.nph * sizeof(*param_headers);
1343
1344                 param_headers = kmalloc(psize, GFP_KERNEL);
1345                 if (!param_headers)
1346                         return -ENOMEM;
1347
1348                 err = spi_nor_read_sfdp(nor, sizeof(header),
1349                                         psize, param_headers);
1350                 if (err < 0) {
1351                         dev_dbg(dev, "failed to read SFDP parameter headers\n");
1352                         goto exit;
1353                 }
1354         }
1355
1356         /*
1357          * Cache the complete SFDP data. It is not (easily) possible to fetch
1358          * SFDP after probe time and we need it for the sysfs access.
1359          */
1360         for (i = 0; i < header.nph; i++) {
1361                 param_header = &param_headers[i];
1362                 sfdp_size = max_t(size_t, sfdp_size,
1363                                   SFDP_PARAM_HEADER_PTP(param_header) +
1364                                   SFDP_PARAM_HEADER_PARAM_LEN(param_header));
1365         }
1366
1367         /*
1368          * Limit the total size to a reasonable value to avoid allocating too
1369          * much memory just of because the flash returned some insane values.
1370          */
1371         if (sfdp_size > PAGE_SIZE) {
1372                 dev_dbg(dev, "SFDP data (%zu) too big, truncating\n",
1373                         sfdp_size);
1374                 sfdp_size = PAGE_SIZE;
1375         }
1376
1377         sfdp = devm_kzalloc(dev, sizeof(*sfdp), GFP_KERNEL);
1378         if (!sfdp) {
1379                 err = -ENOMEM;
1380                 goto exit;
1381         }
1382
1383         /*
1384          * The SFDP is organized in chunks of DWORDs. Thus, in theory, the
1385          * sfdp_size should be a multiple of DWORDs. But in case a flash
1386          * is not spec compliant, make sure that we have enough space to store
1387          * the complete SFDP data.
1388          */
1389         sfdp->num_dwords = DIV_ROUND_UP(sfdp_size, sizeof(*sfdp->dwords));
1390         sfdp->dwords = devm_kcalloc(dev, sfdp->num_dwords,
1391                                     sizeof(*sfdp->dwords), GFP_KERNEL);
1392         if (!sfdp->dwords) {
1393                 err = -ENOMEM;
1394                 devm_kfree(dev, sfdp);
1395                 goto exit;
1396         }
1397
1398         err = spi_nor_read_sfdp(nor, 0, sfdp_size, sfdp->dwords);
1399         if (err < 0) {
1400                 dev_dbg(dev, "failed to read SFDP data\n");
1401                 devm_kfree(dev, sfdp->dwords);
1402                 devm_kfree(dev, sfdp);
1403                 goto exit;
1404         }
1405
1406         nor->sfdp = sfdp;
1407
1408         /*
1409          * Check other parameter headers to get the latest revision of
1410          * the basic flash parameter table.
1411          */
1412         for (i = 0; i < header.nph; i++) {
1413                 param_header = &param_headers[i];
1414
1415                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
1416                     param_header->major == SFDP_JESD216_MAJOR &&
1417                     (param_header->minor > bfpt_header->minor ||
1418                      (param_header->minor == bfpt_header->minor &&
1419                       param_header->length > bfpt_header->length)))
1420                         bfpt_header = param_header;
1421         }
1422
1423         err = spi_nor_parse_bfpt(nor, bfpt_header);
1424         if (err)
1425                 goto exit;
1426
1427         /* Parse optional parameter tables. */
1428         for (i = 0; i < header.nph; i++) {
1429                 param_header = &param_headers[i];
1430
1431                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
1432                 case SFDP_SECTOR_MAP_ID:
1433                         err = spi_nor_parse_smpt(nor, param_header);
1434                         break;
1435
1436                 case SFDP_4BAIT_ID:
1437                         err = spi_nor_parse_4bait(nor, param_header);
1438                         break;
1439
1440                 case SFDP_PROFILE1_ID:
1441                         err = spi_nor_parse_profile1(nor, param_header);
1442                         break;
1443
1444                 case SFDP_SCCR_MAP_ID:
1445                         err = spi_nor_parse_sccr(nor, param_header);
1446                         break;
1447
1448                 default:
1449                         break;
1450                 }
1451
1452                 if (err) {
1453                         dev_warn(dev, "Failed to parse optional parameter table: %04x\n",
1454                                  SFDP_PARAM_HEADER_ID(param_header));
1455                         /*
1456                          * Let's not drop all information we extracted so far
1457                          * if optional table parsers fail. In case of failing,
1458                          * each optional parser is responsible to roll back to
1459                          * the previously known spi_nor data.
1460                          */
1461                         err = 0;
1462                 }
1463         }
1464
1465         spi_nor_post_sfdp_fixups(nor);
1466 exit:
1467         kfree(param_headers);
1468         return err;
1469 }