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