1 /*
2  * Copyright (c) 2020 Piotr Mienkowski
3  * Copyright (c) 2020 Linaro Limited
4  * Copyright (c) 2022 Georgij Cernysiov
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #define DT_DRV_COMPAT st_stm32_qspi_nor
10 
11 #include <errno.h>
12 #include <zephyr/kernel.h>
13 #include <zephyr/toolchain.h>
14 #include <zephyr/arch/common/ffs.h>
15 #include <zephyr/sys/util.h>
16 #include <soc.h>
17 #include <zephyr/drivers/pinctrl.h>
18 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
19 #include <zephyr/drivers/clock_control.h>
20 #include <zephyr/drivers/flash.h>
21 #include <zephyr/drivers/dma.h>
22 #include <zephyr/drivers/dma/dma_stm32.h>
23 #include <zephyr/drivers/gpio.h>
24 
25 #if DT_INST_NODE_HAS_PROP(0, spi_bus_width) && \
26 	DT_INST_PROP(0, spi_bus_width) == 4
27 #define STM32_QSPI_USE_QUAD_IO 1
28 #else
29 #define STM32_QSPI_USE_QUAD_IO 0
30 #endif
31 
32 /* Get the base address of the flash from the DTS node */
33 #define STM32_QSPI_BASE_ADDRESS DT_INST_REG_ADDR(0)
34 
35 #define STM32_QSPI_RESET_GPIO DT_INST_NODE_HAS_PROP(0, reset_gpios)
36 #define STM32_QSPI_RESET_CMD DT_INST_NODE_HAS_PROP(0, reset_cmd)
37 
38 #include <stm32_ll_dma.h>
39 
40 #include "spi_nor.h"
41 #include "jesd216.h"
42 
43 #include <zephyr/logging/log.h>
44 #include <zephyr/irq.h>
45 LOG_MODULE_REGISTER(flash_stm32_qspi, CONFIG_FLASH_LOG_LEVEL);
46 
47 #define STM32_QSPI_FIFO_THRESHOLD         8
48 #define STM32_QSPI_CLOCK_PRESCALER_MAX  255
49 
50 #define STM32_QSPI_UNKNOWN_MODE (0xFF)
51 
52 #define STM32_QSPI_USE_DMA DT_NODE_HAS_PROP(DT_INST_PARENT(0), dmas)
53 
54 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_qspi_nor)
55 
56 #if STM32_QSPI_USE_DMA
57 static const uint32_t table_m_size[] = {
58 	LL_DMA_MDATAALIGN_BYTE,
59 	LL_DMA_MDATAALIGN_HALFWORD,
60 	LL_DMA_MDATAALIGN_WORD,
61 };
62 
63 static const uint32_t table_p_size[] = {
64 	LL_DMA_PDATAALIGN_BYTE,
65 	LL_DMA_PDATAALIGN_HALFWORD,
66 	LL_DMA_PDATAALIGN_WORD,
67 };
68 
69 /* Lookup table to set dma priority from the DTS */
70 static const uint32_t table_priority[] = {
71 	DMA_PRIORITY_LOW,
72 	DMA_PRIORITY_MEDIUM,
73 	DMA_PRIORITY_HIGH,
74 	DMA_PRIORITY_VERY_HIGH,
75 };
76 #endif /* STM32_QSPI_USE_DMA */
77 
78 typedef void (*irq_config_func_t)(const struct device *dev);
79 
80 struct stream {
81 	DMA_TypeDef *reg;
82 	const struct device *dev;
83 	uint32_t channel;
84 	struct dma_config cfg;
85 };
86 
87 struct flash_stm32_qspi_config {
88 	QUADSPI_TypeDef *regs;
89 	struct stm32_pclken pclken;
90 	irq_config_func_t irq_config;
91 	size_t flash_size;
92 	uint32_t max_frequency;
93 	const struct pinctrl_dev_config *pcfg;
94 #if STM32_QSPI_RESET_GPIO
95 	const struct gpio_dt_spec reset;
96 #endif
97 #if DT_NODE_HAS_PROP(DT_INST(0, st_stm32_qspi_nor), jedec_id)
98 	uint8_t jedec_id[DT_INST_PROP_LEN(0, jedec_id)];
99 #endif /* jedec_id */
100 };
101 
102 struct flash_stm32_qspi_data {
103 	QSPI_HandleTypeDef hqspi;
104 	struct k_sem sem;
105 	struct k_sem sync;
106 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
107 	struct flash_pages_layout layout;
108 #endif
109 	struct jesd216_erase_type erase_types[JESD216_NUM_ERASE_TYPES];
110 	/* Number of bytes per page */
111 	uint16_t page_size;
112 	enum jesd216_dw15_qer_type qer_type;
113 	enum jesd216_mode_type mode;
114 	int cmd_status;
115 	struct stream dma;
116 	uint8_t qspi_write_cmd;
117 	uint8_t qspi_read_cmd;
118 	uint8_t qspi_read_cmd_latency;
119 	/*
120 	 * If set addressed operations should use 32-bit rather than
121 	 * 24-bit addresses.
122 	 */
123 	bool flag_access_32bit: 1;
124 };
125 
qspi_lock_thread(const struct device * dev)126 static inline void qspi_lock_thread(const struct device *dev)
127 {
128 	struct flash_stm32_qspi_data *dev_data = dev->data;
129 
130 	k_sem_take(&dev_data->sem, K_FOREVER);
131 }
132 
qspi_unlock_thread(const struct device * dev)133 static inline void qspi_unlock_thread(const struct device *dev)
134 {
135 	struct flash_stm32_qspi_data *dev_data = dev->data;
136 
137 	k_sem_give(&dev_data->sem);
138 }
139 
qspi_set_address_size(const struct device * dev,QSPI_CommandTypeDef * cmd)140 static inline void qspi_set_address_size(const struct device *dev,
141 					 QSPI_CommandTypeDef *cmd)
142 {
143 	struct flash_stm32_qspi_data *dev_data = dev->data;
144 
145 	if (dev_data->flag_access_32bit) {
146 		cmd->AddressSize = QSPI_ADDRESS_32_BITS;
147 		return;
148 	}
149 
150 	cmd->AddressSize = QSPI_ADDRESS_24_BITS;
151 }
152 
qspi_prepare_quad_read(const struct device * dev,QSPI_CommandTypeDef * cmd)153 static inline int qspi_prepare_quad_read(const struct device *dev,
154 					  QSPI_CommandTypeDef *cmd)
155 {
156 	struct flash_stm32_qspi_data *dev_data = dev->data;
157 
158 	__ASSERT_NO_MSG(dev_data->mode == JESD216_MODE_114 ||
159 			dev_data->mode == JESD216_MODE_144);
160 
161 	cmd->Instruction = dev_data->qspi_read_cmd;
162 	cmd->AddressMode = ((dev_data->mode == JESD216_MODE_114)
163 				? QSPI_ADDRESS_1_LINE
164 				: QSPI_ADDRESS_4_LINES);
165 	cmd->DataMode = QSPI_DATA_4_LINES;
166 	cmd->DummyCycles = dev_data->qspi_read_cmd_latency;
167 
168 	return 0;
169 }
170 
qspi_prepare_quad_program(const struct device * dev,QSPI_CommandTypeDef * cmd)171 static inline int qspi_prepare_quad_program(const struct device *dev,
172 					     QSPI_CommandTypeDef *cmd)
173 {
174 	struct flash_stm32_qspi_data *dev_data = dev->data;
175 
176 	__ASSERT_NO_MSG(dev_data->qspi_write_cmd == SPI_NOR_CMD_PP_1_1_4 ||
177 			dev_data->qspi_write_cmd == SPI_NOR_CMD_PP_1_4_4);
178 
179 	cmd->Instruction = dev_data->qspi_write_cmd;
180 	cmd->AddressMode = ((cmd->Instruction == SPI_NOR_CMD_PP_1_1_4)
181 				? QSPI_ADDRESS_1_LINE
182 				: QSPI_ADDRESS_4_LINES);
183 	cmd->DataMode = QSPI_DATA_4_LINES;
184 	cmd->DummyCycles = 0;
185 
186 	return 0;
187 }
188 
189 /*
190  * Send a command over QSPI bus.
191  */
qspi_send_cmd(const struct device * dev,QSPI_CommandTypeDef * cmd)192 static int qspi_send_cmd(const struct device *dev, QSPI_CommandTypeDef *cmd)
193 {
194 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
195 	struct flash_stm32_qspi_data *dev_data = dev->data;
196 	HAL_StatusTypeDef hal_ret;
197 
198 	ARG_UNUSED(dev_cfg);
199 
200 	LOG_DBG("Instruction 0x%x", cmd->Instruction);
201 
202 	dev_data->cmd_status = 0;
203 
204 	hal_ret = HAL_QSPI_Command_IT(&dev_data->hqspi, cmd);
205 	if (hal_ret != HAL_OK) {
206 		LOG_ERR("%d: Failed to send QSPI instruction", hal_ret);
207 		return -EIO;
208 	}
209 	LOG_DBG("CCR 0x%x", dev_cfg->regs->CCR);
210 
211 	k_sem_take(&dev_data->sync, K_FOREVER);
212 
213 	return dev_data->cmd_status;
214 }
215 
216 /*
217  * Perform a read access over QSPI bus.
218  */
qspi_read_access(const struct device * dev,QSPI_CommandTypeDef * cmd,uint8_t * data,size_t size)219 static int qspi_read_access(const struct device *dev, QSPI_CommandTypeDef *cmd,
220 			    uint8_t *data, size_t size)
221 {
222 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
223 	struct flash_stm32_qspi_data *dev_data = dev->data;
224 	HAL_StatusTypeDef hal_ret;
225 
226 	ARG_UNUSED(dev_cfg);
227 
228 	cmd->NbData = size;
229 
230 	dev_data->cmd_status = 0;
231 
232 	hal_ret = HAL_QSPI_Command_IT(&dev_data->hqspi, cmd);
233 	if (hal_ret != HAL_OK) {
234 		LOG_ERR("%d: Failed to send QSPI instruction", hal_ret);
235 		return -EIO;
236 	}
237 
238 #if STM32_QSPI_USE_DMA
239 	hal_ret = HAL_QSPI_Receive_DMA(&dev_data->hqspi, data);
240 #else
241 	hal_ret = HAL_QSPI_Receive_IT(&dev_data->hqspi, data);
242 #endif
243 	if (hal_ret != HAL_OK) {
244 		LOG_ERR("%d: Failed to read data", hal_ret);
245 		return -EIO;
246 	}
247 
248 	k_sem_take(&dev_data->sync, K_FOREVER);
249 
250 	return dev_data->cmd_status;
251 }
252 
253 /*
254  * Perform a write access over QSPI bus.
255  */
qspi_write_access(const struct device * dev,QSPI_CommandTypeDef * cmd,const uint8_t * data,size_t size)256 static int qspi_write_access(const struct device *dev, QSPI_CommandTypeDef *cmd,
257 			     const uint8_t *data, size_t size)
258 {
259 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
260 	struct flash_stm32_qspi_data *dev_data = dev->data;
261 	HAL_StatusTypeDef hal_ret;
262 
263 	ARG_UNUSED(dev_cfg);
264 
265 	LOG_DBG("Instruction 0x%x", cmd->Instruction);
266 
267 	cmd->NbData = size;
268 
269 	dev_data->cmd_status = 0;
270 
271 	hal_ret = HAL_QSPI_Command_IT(&dev_data->hqspi, cmd);
272 	if (hal_ret != HAL_OK) {
273 		LOG_ERR("%d: Failed to send QSPI instruction", hal_ret);
274 		return -EIO;
275 	}
276 
277 #if STM32_QSPI_USE_DMA
278 	hal_ret = HAL_QSPI_Transmit_DMA(&dev_data->hqspi, (uint8_t *)data);
279 #else
280 	hal_ret = HAL_QSPI_Transmit_IT(&dev_data->hqspi, (uint8_t *)data);
281 #endif
282 	if (hal_ret != HAL_OK) {
283 		LOG_ERR("%d: Failed to read data", hal_ret);
284 		return -EIO;
285 	}
286 	LOG_DBG("CCR 0x%x", dev_cfg->regs->CCR);
287 
288 	k_sem_take(&dev_data->sync, K_FOREVER);
289 
290 	return dev_data->cmd_status;
291 }
292 
293 #if defined(CONFIG_FLASH_JESD216_API)
294 /*
295  * Read Serial Flash ID :
296  * perform a read access over SPI bus for read Identification (DataMode is already set)
297  * and compare to the jedec-id from the DTYS table exists
298  */
qspi_read_jedec_id(const struct device * dev,uint8_t * id)299 static int qspi_read_jedec_id(const struct device *dev, uint8_t *id)
300 {
301 	struct flash_stm32_qspi_data *dev_data = dev->data;
302 	uint8_t data[JESD216_READ_ID_LEN];
303 
304 	QSPI_CommandTypeDef cmd = {
305 		.Instruction = JESD216_CMD_READ_ID,
306 		.AddressSize = QSPI_ADDRESS_NONE,
307 		.DummyCycles = 8,
308 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
309 		.AddressMode = QSPI_ADDRESS_1_LINE,
310 		.DataMode = QSPI_DATA_1_LINE,
311 		.NbData = JESD216_READ_ID_LEN,
312 	};
313 
314 	HAL_StatusTypeDef hal_ret;
315 
316 	hal_ret = HAL_QSPI_Command_IT(&dev_data->hqspi, &cmd);
317 
318 	if (hal_ret != HAL_OK) {
319 		LOG_ERR("%d: Failed to send OSPI instruction", hal_ret);
320 		return -EIO;
321 	}
322 
323 	hal_ret = HAL_QSPI_Receive(&dev_data->hqspi, data, HAL_QSPI_TIMEOUT_DEFAULT_VALUE);
324 	if (hal_ret != HAL_OK) {
325 		LOG_ERR("%d: Failed to read data", hal_ret);
326 		return -EIO;
327 	}
328 
329 	dev_data->cmd_status = 0;
330 	id = &data[0];
331 
332 	return 0;
333 }
334 #endif /* CONFIG_FLASH_JESD216_API */
335 
336 /*
337  * Read Serial Flash Discovery Parameter
338  */
qspi_read_sfdp(const struct device * dev,off_t addr,void * data,size_t size)339 static int qspi_read_sfdp(const struct device *dev, off_t addr, void *data,
340 			  size_t size)
341 {
342 	struct flash_stm32_qspi_data *dev_data = dev->data;
343 	HAL_StatusTypeDef hal_ret;
344 
345 	__ASSERT(data != NULL, "null destination");
346 
347 	LOG_INF("Reading SFDP");
348 
349 	QSPI_CommandTypeDef cmd = {
350 		.Instruction = JESD216_CMD_READ_SFDP,
351 		.Address = addr,
352 		.AddressSize = QSPI_ADDRESS_24_BITS,
353 		.DummyCycles = 8,
354 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
355 		.AddressMode = QSPI_ADDRESS_1_LINE,
356 		.DataMode = QSPI_DATA_1_LINE,
357 		.NbData = size,
358 	};
359 
360 	hal_ret = HAL_QSPI_Command(&dev_data->hqspi, &cmd,
361 				   HAL_QSPI_TIMEOUT_DEFAULT_VALUE);
362 	if (hal_ret != HAL_OK) {
363 		LOG_ERR("%d: Failed to send SFDP instruction", hal_ret);
364 		return -EIO;
365 	}
366 
367 	hal_ret = HAL_QSPI_Receive(&dev_data->hqspi, (uint8_t *)data,
368 				   HAL_QSPI_TIMEOUT_DEFAULT_VALUE);
369 	if (hal_ret != HAL_OK) {
370 		LOG_ERR("%d: Failed to read SFDP", hal_ret);
371 		return -EIO;
372 	}
373 
374 	dev_data->cmd_status = 0;
375 
376 	return 0;
377 }
378 
qspi_address_is_valid(const struct device * dev,off_t addr,size_t size)379 static bool qspi_address_is_valid(const struct device *dev, off_t addr,
380 				  size_t size)
381 {
382 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
383 	size_t flash_size = dev_cfg->flash_size;
384 
385 	return (addr >= 0) && ((uint64_t)addr + (uint64_t)size <= flash_size);
386 }
387 
flash_stm32_qspi_read(const struct device * dev,off_t addr,void * data,size_t size)388 static int flash_stm32_qspi_read(const struct device *dev, off_t addr,
389 				 void *data, size_t size)
390 {
391 	int ret;
392 
393 	if (!qspi_address_is_valid(dev, addr, size)) {
394 		LOG_DBG("Error: address or size exceeds expected values: "
395 			"addr 0x%lx, size %zu", (long)addr, size);
396 		return -EINVAL;
397 	}
398 
399 	/* read non-zero size */
400 	if (size == 0) {
401 		return 0;
402 	}
403 
404 	QSPI_CommandTypeDef cmd = {
405 		.Instruction = SPI_NOR_CMD_READ,
406 		.Address = addr,
407 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
408 		.AddressMode = QSPI_ADDRESS_1_LINE,
409 		.DataMode = QSPI_DATA_1_LINE,
410 	};
411 
412 	qspi_set_address_size(dev, &cmd);
413 	if (IS_ENABLED(STM32_QSPI_USE_QUAD_IO)) {
414 		ret = qspi_prepare_quad_read(dev, &cmd);
415 		if (ret < 0) {
416 			return ret;
417 		}
418 	}
419 
420 	qspi_lock_thread(dev);
421 
422 	ret = qspi_read_access(dev, &cmd, data, size);
423 
424 	qspi_unlock_thread(dev);
425 
426 	return ret;
427 }
428 
qspi_wait_until_ready(const struct device * dev)429 static int qspi_wait_until_ready(const struct device *dev)
430 {
431 	uint8_t reg;
432 	int ret;
433 
434 	QSPI_CommandTypeDef cmd = {
435 		.Instruction = SPI_NOR_CMD_RDSR,
436 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
437 		.DataMode = QSPI_DATA_1_LINE,
438 	};
439 
440 	do {
441 		ret = qspi_read_access(dev, &cmd, &reg, sizeof(reg));
442 	} while (!ret && (reg & SPI_NOR_WIP_BIT));
443 
444 	return ret;
445 }
446 
flash_stm32_qspi_write(const struct device * dev,off_t addr,const void * data,size_t size)447 static int flash_stm32_qspi_write(const struct device *dev, off_t addr,
448 				  const void *data, size_t size)
449 {
450 	int ret = 0;
451 
452 	if (!qspi_address_is_valid(dev, addr, size)) {
453 		LOG_DBG("Error: address or size exceeds expected values: "
454 			"addr 0x%lx, size %zu", (long)addr, size);
455 		return -EINVAL;
456 	}
457 
458 	/* write non-zero size */
459 	if (size == 0) {
460 		return 0;
461 	}
462 
463 	QSPI_CommandTypeDef cmd_write_en = {
464 		.Instruction = SPI_NOR_CMD_WREN,
465 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
466 	};
467 
468 	QSPI_CommandTypeDef cmd_pp = {
469 		.Instruction = SPI_NOR_CMD_PP,
470 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
471 		.AddressMode = QSPI_ADDRESS_1_LINE,
472 		.DataMode = QSPI_DATA_1_LINE,
473 	};
474 
475 	qspi_set_address_size(dev, &cmd_pp);
476 	if (IS_ENABLED(STM32_QSPI_USE_QUAD_IO)) {
477 		ret = qspi_prepare_quad_program(dev, &cmd_pp);
478 		if (ret < 0) {
479 			return ret;
480 		}
481 	}
482 
483 	qspi_lock_thread(dev);
484 
485 	while (size > 0) {
486 		size_t to_write = size;
487 
488 		/* Don't write more than a page. */
489 		if (to_write >= SPI_NOR_PAGE_SIZE) {
490 			to_write = SPI_NOR_PAGE_SIZE;
491 		}
492 
493 		/* Don't write across a page boundary */
494 		if (((addr + to_write - 1U) / SPI_NOR_PAGE_SIZE)
495 		    != (addr / SPI_NOR_PAGE_SIZE)) {
496 			to_write = SPI_NOR_PAGE_SIZE -
497 						(addr % SPI_NOR_PAGE_SIZE);
498 		}
499 
500 		ret = qspi_send_cmd(dev, &cmd_write_en);
501 		if (ret != 0) {
502 			break;
503 		}
504 
505 		cmd_pp.Address = addr;
506 		ret = qspi_write_access(dev, &cmd_pp, data, to_write);
507 		if (ret != 0) {
508 			break;
509 		}
510 
511 		size -= to_write;
512 		data = (const uint8_t *)data + to_write;
513 		addr += to_write;
514 
515 		ret = qspi_wait_until_ready(dev);
516 		if (ret != 0) {
517 			break;
518 		}
519 	}
520 
521 	qspi_unlock_thread(dev);
522 
523 	return ret;
524 }
525 
flash_stm32_qspi_erase(const struct device * dev,off_t addr,size_t size)526 static int flash_stm32_qspi_erase(const struct device *dev, off_t addr,
527 				  size_t size)
528 {
529 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
530 	struct flash_stm32_qspi_data *dev_data = dev->data;
531 	int ret = 0;
532 
533 	if (!qspi_address_is_valid(dev, addr, size)) {
534 		LOG_DBG("Error: address or size exceeds expected values: "
535 			"addr 0x%lx, size %zu", (long)addr, size);
536 		return -EINVAL;
537 	}
538 
539 	/* erase non-zero size */
540 	if (size == 0) {
541 		return 0;
542 	}
543 
544 	QSPI_CommandTypeDef cmd_write_en = {
545 		.Instruction = SPI_NOR_CMD_WREN,
546 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
547 	};
548 
549 	QSPI_CommandTypeDef cmd_erase = {
550 		.Instruction = 0,
551 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
552 		.AddressMode = QSPI_ADDRESS_1_LINE,
553 	};
554 
555 	qspi_set_address_size(dev, &cmd_erase);
556 	qspi_lock_thread(dev);
557 
558 	while ((size > 0) && (ret == 0)) {
559 		cmd_erase.Address = addr;
560 		qspi_send_cmd(dev, &cmd_write_en);
561 
562 		if (size == dev_cfg->flash_size) {
563 			/* chip erase */
564 			cmd_erase.Instruction = SPI_NOR_CMD_CE;
565 			cmd_erase.AddressMode = QSPI_ADDRESS_NONE;
566 			qspi_send_cmd(dev, &cmd_erase);
567 			size -= dev_cfg->flash_size;
568 		} else {
569 			const struct jesd216_erase_type *erase_types =
570 							dev_data->erase_types;
571 			const struct jesd216_erase_type *bet = NULL;
572 
573 			for (uint8_t ei = 0;
574 				ei < JESD216_NUM_ERASE_TYPES; ++ei) {
575 				const struct jesd216_erase_type *etp =
576 							&erase_types[ei];
577 
578 				if ((etp->exp != 0)
579 				    && SPI_NOR_IS_ALIGNED(addr, etp->exp)
580 				    && SPI_NOR_IS_ALIGNED(size, etp->exp)
581 				    && ((bet == NULL)
582 					|| (etp->exp > bet->exp))) {
583 					bet = etp;
584 					cmd_erase.Instruction = bet->cmd;
585 				}
586 			}
587 			if (bet != NULL) {
588 				qspi_send_cmd(dev, &cmd_erase);
589 				addr += BIT(bet->exp);
590 				size -= BIT(bet->exp);
591 			} else {
592 				LOG_ERR("Can't erase %zu at 0x%lx",
593 					size, (long)addr);
594 				ret = -EINVAL;
595 			}
596 		}
597 		qspi_wait_until_ready(dev);
598 	}
599 
600 	qspi_unlock_thread(dev);
601 
602 	return ret;
603 }
604 
605 static const struct flash_parameters flash_stm32_qspi_parameters = {
606 	.write_block_size = 1,
607 	.erase_value = 0xff
608 };
609 
610 static const struct flash_parameters *
flash_stm32_qspi_get_parameters(const struct device * dev)611 flash_stm32_qspi_get_parameters(const struct device *dev)
612 {
613 	ARG_UNUSED(dev);
614 
615 	return &flash_stm32_qspi_parameters;
616 }
617 
flash_stm32_qspi_isr(const struct device * dev)618 static void flash_stm32_qspi_isr(const struct device *dev)
619 {
620 	struct flash_stm32_qspi_data *dev_data = dev->data;
621 
622 	HAL_QSPI_IRQHandler(&dev_data->hqspi);
623 }
624 
625 /* This function is executed in the interrupt context */
626 #if STM32_QSPI_USE_DMA
qspi_dma_callback(const struct device * dev,void * arg,uint32_t channel,int status)627 static void qspi_dma_callback(const struct device *dev, void *arg,
628 			 uint32_t channel, int status)
629 {
630 	DMA_HandleTypeDef *hdma = arg;
631 
632 	ARG_UNUSED(dev);
633 
634 	if (status < 0) {
635 		LOG_ERR("DMA callback error with channel %d.", channel);
636 
637 	}
638 
639 	HAL_DMA_IRQHandler(hdma);
640 }
641 #endif
642 
HAL_DMA_Abort(DMA_HandleTypeDef * hdma)643 __weak HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma)
644 {
645 	return HAL_OK;
646 }
647 
HAL_DMA_Abort_IT(DMA_HandleTypeDef * hdma)648 __weak HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma)
649 {
650 	return HAL_OK;
651 }
652 
653 /*
654  * Transfer Error callback.
655  */
HAL_QSPI_ErrorCallback(QSPI_HandleTypeDef * hqspi)656 void HAL_QSPI_ErrorCallback(QSPI_HandleTypeDef *hqspi)
657 {
658 	struct flash_stm32_qspi_data *dev_data =
659 		CONTAINER_OF(hqspi, struct flash_stm32_qspi_data, hqspi);
660 
661 	LOG_DBG("Enter");
662 
663 	dev_data->cmd_status = -EIO;
664 
665 	k_sem_give(&dev_data->sync);
666 }
667 
668 /*
669  * Command completed callback.
670  */
HAL_QSPI_CmdCpltCallback(QSPI_HandleTypeDef * hqspi)671 void HAL_QSPI_CmdCpltCallback(QSPI_HandleTypeDef *hqspi)
672 {
673 	struct flash_stm32_qspi_data *dev_data =
674 		CONTAINER_OF(hqspi, struct flash_stm32_qspi_data, hqspi);
675 
676 	k_sem_give(&dev_data->sync);
677 }
678 
679 /*
680  * Rx Transfer completed callback.
681  */
HAL_QSPI_RxCpltCallback(QSPI_HandleTypeDef * hqspi)682 void HAL_QSPI_RxCpltCallback(QSPI_HandleTypeDef *hqspi)
683 {
684 	struct flash_stm32_qspi_data *dev_data =
685 		CONTAINER_OF(hqspi, struct flash_stm32_qspi_data, hqspi);
686 
687 	k_sem_give(&dev_data->sync);
688 }
689 
690 /*
691  * Tx Transfer completed callback.
692  */
HAL_QSPI_TxCpltCallback(QSPI_HandleTypeDef * hqspi)693 void HAL_QSPI_TxCpltCallback(QSPI_HandleTypeDef *hqspi)
694 {
695 	struct flash_stm32_qspi_data *dev_data =
696 		CONTAINER_OF(hqspi, struct flash_stm32_qspi_data, hqspi);
697 
698 	k_sem_give(&dev_data->sync);
699 }
700 
701 /*
702  * Status Match callback.
703  */
HAL_QSPI_StatusMatchCallback(QSPI_HandleTypeDef * hqspi)704 void HAL_QSPI_StatusMatchCallback(QSPI_HandleTypeDef *hqspi)
705 {
706 	struct flash_stm32_qspi_data *dev_data =
707 		CONTAINER_OF(hqspi, struct flash_stm32_qspi_data, hqspi);
708 
709 	k_sem_give(&dev_data->sync);
710 }
711 
712 /*
713  * Timeout callback.
714  */
HAL_QSPI_TimeOutCallback(QSPI_HandleTypeDef * hqspi)715 void HAL_QSPI_TimeOutCallback(QSPI_HandleTypeDef *hqspi)
716 {
717 	struct flash_stm32_qspi_data *dev_data =
718 		CONTAINER_OF(hqspi, struct flash_stm32_qspi_data, hqspi);
719 
720 	LOG_DBG("Enter");
721 
722 	dev_data->cmd_status = -EIO;
723 
724 	k_sem_give(&dev_data->sync);
725 }
726 
727 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
flash_stm32_qspi_pages_layout(const struct device * dev,const struct flash_pages_layout ** layout,size_t * layout_size)728 static void flash_stm32_qspi_pages_layout(const struct device *dev,
729 				const struct flash_pages_layout **layout,
730 				size_t *layout_size)
731 {
732 	struct flash_stm32_qspi_data *dev_data = dev->data;
733 
734 	*layout = &dev_data->layout;
735 	*layout_size = 1;
736 }
737 #endif
738 
739 static const struct flash_driver_api flash_stm32_qspi_driver_api = {
740 	.read = flash_stm32_qspi_read,
741 	.write = flash_stm32_qspi_write,
742 	.erase = flash_stm32_qspi_erase,
743 	.get_parameters = flash_stm32_qspi_get_parameters,
744 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
745 	.page_layout = flash_stm32_qspi_pages_layout,
746 #endif
747 #if defined(CONFIG_FLASH_JESD216_API)
748 	.sfdp_read = qspi_read_sfdp,
749 	.read_jedec_id = qspi_read_jedec_id,
750 #endif /* CONFIG_FLASH_JESD216_API */
751 };
752 
753 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
setup_pages_layout(const struct device * dev)754 static int setup_pages_layout(const struct device *dev)
755 {
756 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
757 	struct flash_stm32_qspi_data *data = dev->data;
758 	const size_t flash_size = dev_cfg->flash_size;
759 	uint32_t layout_page_size = data->page_size;
760 	uint8_t exp = 0;
761 	int rv = 0;
762 
763 	/* Find the smallest erase size. */
764 	for (size_t i = 0; i < ARRAY_SIZE(data->erase_types); ++i) {
765 		const struct jesd216_erase_type *etp = &data->erase_types[i];
766 
767 		if ((etp->cmd != 0)
768 		    && ((exp == 0) || (etp->exp < exp))) {
769 			exp = etp->exp;
770 		}
771 	}
772 
773 	if (exp == 0) {
774 		return -ENOTSUP;
775 	}
776 
777 	uint32_t erase_size = BIT(exp);
778 
779 	/* We need layout page size to be compatible with erase size */
780 	if ((layout_page_size % erase_size) != 0) {
781 		LOG_DBG("layout page %u not compatible with erase size %u",
782 			layout_page_size, erase_size);
783 		LOG_DBG("erase size will be used as layout page size");
784 		layout_page_size = erase_size;
785 	}
786 
787 	/* Warn but accept layout page sizes that leave inaccessible
788 	 * space.
789 	 */
790 	if ((flash_size % layout_page_size) != 0) {
791 		LOG_INF("layout page %u wastes space with device size %zu",
792 			layout_page_size, flash_size);
793 	}
794 
795 	data->layout.pages_size = layout_page_size;
796 	data->layout.pages_count = flash_size / layout_page_size;
797 	LOG_DBG("layout %u x %u By pages", data->layout.pages_count,
798 					   data->layout.pages_size);
799 
800 	return rv;
801 }
802 #endif /* CONFIG_FLASH_PAGE_LAYOUT */
803 
qspi_program_addr_4b(const struct device * dev,bool write_enable)804 static int qspi_program_addr_4b(const struct device *dev, bool write_enable)
805 {
806 	int ret;
807 
808 	/* Send write enable command, if required */
809 	if (write_enable) {
810 		QSPI_CommandTypeDef cmd_write_en = {
811 			.Instruction = SPI_NOR_CMD_WREN,
812 			.InstructionMode = QSPI_INSTRUCTION_1_LINE,
813 		};
814 		ret = qspi_send_cmd(dev, &cmd_write_en);
815 		if (ret != 0) {
816 			return ret;
817 		}
818 	}
819 
820 	/* Program the flash memory to use 4 bytes addressing */
821 	QSPI_CommandTypeDef cmd = {
822 		.Instruction = SPI_NOR_CMD_4BA,
823 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
824 	};
825 
826 	/*
827 	 * No need to Read control register afterwards to verify if 4byte addressing mode
828 	 * is enabled as the effect of the command is immediate
829 	 * and the SPI_NOR_CMD_RDCR is vendor-specific :
830 	 * SPI_NOR_4BYTE_BIT is BIT 5 for Macronix and 0 for Micron or Windbond
831 	 * Moreover bit value meaning is also vendor-specific
832 	 */
833 
834 	return qspi_send_cmd(dev, &cmd);
835 }
836 
qspi_read_status_register(const struct device * dev,uint8_t reg_num,uint8_t * reg)837 static int qspi_read_status_register(const struct device *dev, uint8_t reg_num, uint8_t *reg)
838 {
839 	QSPI_CommandTypeDef cmd = {
840 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
841 		.DataMode = QSPI_DATA_1_LINE,
842 	};
843 
844 	switch (reg_num) {
845 	case 1U:
846 		cmd.Instruction = SPI_NOR_CMD_RDSR;
847 		break;
848 	case 2U:
849 		cmd.Instruction = SPI_NOR_CMD_RDSR2;
850 		break;
851 	case 3U:
852 		cmd.Instruction = SPI_NOR_CMD_RDSR3;
853 		break;
854 	default:
855 		return -EINVAL;
856 	}
857 
858 	return qspi_read_access(dev, &cmd, reg, sizeof(*reg));
859 }
860 
qspi_write_status_register(const struct device * dev,uint8_t reg_num,uint8_t reg)861 static int qspi_write_status_register(const struct device *dev, uint8_t reg_num, uint8_t reg)
862 {
863 	struct flash_stm32_qspi_data *dev_data = dev->data;
864 	size_t size;
865 	uint8_t regs[4] = { 0 };
866 	uint8_t *regs_p;
867 	int ret;
868 
869 	QSPI_CommandTypeDef cmd = {
870 		.Instruction = SPI_NOR_CMD_WRSR,
871 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
872 		.DataMode = QSPI_DATA_1_LINE,
873 	};
874 
875 	if (reg_num == 1) {
876 		size = 1U;
877 		regs[0] = reg;
878 		regs_p = &regs[0];
879 		/* 1 byte write clears SR2, write SR2 as well */
880 		if (dev_data->qer_type == JESD216_DW15_QER_S2B1v1) {
881 			ret = qspi_read_status_register(dev, 2, &regs[1]);
882 			if (ret < 0) {
883 				return ret;
884 			}
885 			size = 2U;
886 		}
887 	} else if (reg_num == 2) {
888 		cmd.Instruction = SPI_NOR_CMD_WRSR2;
889 		size = 1U;
890 		regs[1] = reg;
891 		regs_p = &regs[1];
892 		/* if SR2 write needs SR1 */
893 		if ((dev_data->qer_type == JESD216_DW15_QER_VAL_S2B1v1) ||
894 		    (dev_data->qer_type == JESD216_DW15_QER_VAL_S2B1v4) ||
895 		    (dev_data->qer_type == JESD216_DW15_QER_VAL_S2B1v5)) {
896 			ret = qspi_read_status_register(dev, 1, &regs[0]);
897 			if (ret < 0) {
898 				return ret;
899 			}
900 			cmd.Instruction = SPI_NOR_CMD_WRSR;
901 			size = 2U;
902 			regs_p = &regs[0];
903 		}
904 	} else if (reg_num == 3) {
905 		cmd.Instruction = SPI_NOR_CMD_WRSR3;
906 		size = 1U;
907 		regs[2] = reg;
908 		regs_p = &regs[2];
909 	} else {
910 		return -EINVAL;
911 	}
912 
913 	return qspi_write_access(dev, &cmd, regs_p, size);
914 }
915 
qspi_write_enable(const struct device * dev)916 static int qspi_write_enable(const struct device *dev)
917 {
918 	uint8_t reg;
919 	int ret;
920 
921 	QSPI_CommandTypeDef cmd_write_en = {
922 		.Instruction = SPI_NOR_CMD_WREN,
923 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
924 	};
925 
926 	ret = qspi_send_cmd(dev, &cmd_write_en);
927 	if (ret) {
928 		return ret;
929 	}
930 
931 	do {
932 		ret = qspi_read_status_register(dev, 1U, &reg);
933 	} while (!ret && !(reg & SPI_NOR_WEL_BIT));
934 
935 	return ret;
936 }
937 
qspi_program_quad_io(const struct device * dev)938 static int qspi_program_quad_io(const struct device *dev)
939 {
940 	struct flash_stm32_qspi_data *data = dev->data;
941 	uint8_t qe_reg_num;
942 	uint8_t qe_bit;
943 	uint8_t reg;
944 	int ret;
945 
946 	switch (data->qer_type) {
947 	case JESD216_DW15_QER_NONE:
948 		/* no QE bit, device detects reads based on opcode */
949 		return 0;
950 	case JESD216_DW15_QER_S1B6:
951 		qe_reg_num = 1U;
952 		qe_bit = BIT(6U);
953 		break;
954 	case JESD216_DW15_QER_S2B7:
955 		qe_reg_num = 2U;
956 		qe_bit = BIT(7U);
957 		break;
958 	case JESD216_DW15_QER_S2B1v1:
959 		__fallthrough;
960 	case JESD216_DW15_QER_S2B1v4:
961 		__fallthrough;
962 	case JESD216_DW15_QER_S2B1v5:
963 		__fallthrough;
964 	case JESD216_DW15_QER_S2B1v6:
965 		qe_reg_num = 2U;
966 		qe_bit = BIT(1U);
967 		break;
968 	default:
969 		return -ENOTSUP;
970 	}
971 
972 	ret = qspi_read_status_register(dev, qe_reg_num, &reg);
973 	if (ret < 0) {
974 		return ret;
975 	}
976 
977 	/* exit early if QE bit is already set */
978 	if ((reg & qe_bit) != 0U) {
979 		return 0;
980 	}
981 
982 	reg |= qe_bit;
983 
984 	ret = qspi_write_enable(dev);
985 	if (ret < 0) {
986 		return ret;
987 	}
988 
989 	ret = qspi_write_status_register(dev, qe_reg_num, reg);
990 	if (ret < 0) {
991 		return ret;
992 	}
993 
994 	ret = qspi_wait_until_ready(dev);
995 	if (ret < 0) {
996 		return ret;
997 	}
998 
999 	/* validate that QE bit is set */
1000 	ret = qspi_read_status_register(dev, qe_reg_num, &reg);
1001 	if (ret < 0) {
1002 		return ret;
1003 	}
1004 
1005 	if ((reg & qe_bit) == 0U) {
1006 		LOG_ERR("Status Register %u [0x%02x] not set", qe_reg_num, reg);
1007 		return -EIO;
1008 	}
1009 
1010 	return ret;
1011 }
1012 
spi_nor_process_bfp(const struct device * dev,const struct jesd216_param_header * php,const struct jesd216_bfp * bfp)1013 static int spi_nor_process_bfp(const struct device *dev,
1014 			       const struct jesd216_param_header *php,
1015 			       const struct jesd216_bfp *bfp)
1016 {
1017 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
1018 	struct flash_stm32_qspi_data *data = dev->data;
1019 	struct jesd216_erase_type *etp = data->erase_types;
1020 	const size_t flash_size = jesd216_bfp_density(bfp) / 8U;
1021 	uint8_t addr_mode;
1022 	int rc;
1023 
1024 	if (flash_size != dev_cfg->flash_size) {
1025 		LOG_ERR("Unexpected flash size: %u", flash_size);
1026 	}
1027 
1028 	LOG_INF("%s: %u MiBy flash", dev->name, (uint32_t)(flash_size >> 20));
1029 
1030 	/* Copy over the erase types, preserving their order.  (The
1031 	 * Sector Map Parameter table references them by index.)
1032 	 */
1033 	memset(data->erase_types, 0, sizeof(data->erase_types));
1034 	for (uint8_t ti = 1; ti <= ARRAY_SIZE(data->erase_types); ++ti) {
1035 		if (jesd216_bfp_erase(bfp, ti, etp) == 0) {
1036 			LOG_DBG("Erase %u with %02x",
1037 					(uint32_t)BIT(etp->exp), etp->cmd);
1038 		}
1039 		++etp;
1040 	}
1041 
1042 	data->page_size = jesd216_bfp_page_size(php, bfp);
1043 
1044 	LOG_DBG("Page size %u bytes", data->page_size);
1045 	LOG_DBG("Flash size %u bytes", flash_size);
1046 
1047 	addr_mode = jesd216_bfp_addrbytes(bfp);
1048 	if (addr_mode == JESD216_SFDP_BFP_DW1_ADDRBYTES_VAL_3B4B) {
1049 		struct jesd216_bfp_dw16 dw16;
1050 
1051 		if (jesd216_bfp_decode_dw16(php, bfp, &dw16) == 0) {
1052 			/*
1053 			 * According to JESD216, the bit0 of dw16.enter_4ba
1054 			 * portion of flash description register 16 indicates
1055 			 * if it is enough to use 0xB7 instruction without
1056 			 * write enable to switch to 4 bytes addressing mode.
1057 			 * If bit 1 is set, a write enable is needed.
1058 			 */
1059 			if (dw16.enter_4ba & 0x3) {
1060 				rc = qspi_program_addr_4b(dev, dw16.enter_4ba & 2);
1061 				if (rc == 0) {
1062 					data->flag_access_32bit = true;
1063 					LOG_INF("Flash - address mode: 4B");
1064 				} else {
1065 					LOG_ERR("Unable to enter 4B mode: %d\n", rc);
1066 					return rc;
1067 				}
1068 			}
1069 		}
1070 	}
1071 	if (addr_mode == JESD216_SFDP_BFP_DW1_ADDRBYTES_VAL_4B) {
1072 		data->flag_access_32bit = true;
1073 		LOG_INF("Flash - address mode: 4B");
1074 	}
1075 
1076 	/*
1077 	 * Only check if the 1-4-4 (i.e. 4READ) or 1-1-4 (QREAD)
1078 	 * is supported - other modes are not.
1079 	 */
1080 	if (IS_ENABLED(STM32_QSPI_USE_QUAD_IO)) {
1081 		const enum jesd216_mode_type supported_modes[] = { JESD216_MODE_114,
1082 								   JESD216_MODE_144 };
1083 		struct jesd216_bfp_dw15 dw15;
1084 		struct jesd216_instr res;
1085 
1086 		/* reset active mode */
1087 		data->mode = STM32_QSPI_UNKNOWN_MODE;
1088 
1089 		/* query supported read modes, begin from the slowest */
1090 		for (size_t i = 0; i < ARRAY_SIZE(supported_modes); ++i) {
1091 			rc = jesd216_bfp_read_support(php, bfp, supported_modes[i], &res);
1092 			if (rc >= 0) {
1093 				LOG_INF("Quad read mode %d instr [0x%x] supported",
1094 					supported_modes[i], res.instr);
1095 
1096 				data->mode = supported_modes[i];
1097 				data->qspi_read_cmd = res.instr;
1098 				data->qspi_read_cmd_latency = res.wait_states;
1099 
1100 				if (res.mode_clocks) {
1101 					data->qspi_read_cmd_latency += res.mode_clocks;
1102 				}
1103 			}
1104 		}
1105 
1106 		/* don't continue when there is no supported mode */
1107 		if (data->mode == STM32_QSPI_UNKNOWN_MODE) {
1108 			LOG_ERR("No supported flash read mode found");
1109 			return -ENOTSUP;
1110 		}
1111 
1112 		LOG_INF("Quad read mode %d instr [0x%x] will be used", data->mode, res.instr);
1113 
1114 		/* try to decode QE requirement type */
1115 		rc = jesd216_bfp_decode_dw15(php, bfp, &dw15);
1116 		if (rc < 0) {
1117 			/* will use QER from DTS or default (refer to device data) */
1118 			LOG_WRN("Unable to decode QE requirement [DW15]: %d", rc);
1119 		} else {
1120 			/* bypass DTS QER value */
1121 			data->qer_type = dw15.qer;
1122 		}
1123 
1124 		LOG_INF("QE requirement mode: %x", data->qer_type);
1125 
1126 		/* enable QE */
1127 		rc = qspi_program_quad_io(dev);
1128 		if (rc < 0) {
1129 			LOG_ERR("Failed to enable Quad mode: %d", rc);
1130 			return rc;
1131 		}
1132 
1133 		LOG_INF("Quad mode enabled");
1134 	}
1135 
1136 	return 0;
1137 }
1138 
1139 #if STM32_QSPI_RESET_GPIO
flash_stm32_qspi_gpio_reset(const struct device * dev)1140 static void flash_stm32_qspi_gpio_reset(const struct device *dev)
1141 {
1142 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
1143 
1144 	/* Generate RESETn pulse for the flash memory */
1145 	gpio_pin_configure_dt(&dev_cfg->reset, GPIO_OUTPUT_ACTIVE);
1146 	k_msleep(DT_INST_PROP(0, reset_gpios_duration));
1147 	gpio_pin_set_dt(&dev_cfg->reset, 0);
1148 }
1149 #endif
1150 
1151 #if STM32_QSPI_RESET_CMD
flash_stm32_qspi_send_reset(const struct device * dev)1152 static int flash_stm32_qspi_send_reset(const struct device *dev)
1153 {
1154 	QSPI_CommandTypeDef cmd = {
1155 		.Instruction = SPI_NOR_CMD_RESET_EN,
1156 		.InstructionMode = QSPI_INSTRUCTION_1_LINE,
1157 	};
1158 	int ret;
1159 
1160 	ret = qspi_send_cmd(dev, &cmd);
1161 	if (ret != 0) {
1162 		LOG_ERR("%d: Failed to send RESET_EN", ret);
1163 		return ret;
1164 	}
1165 
1166 	cmd.Instruction = SPI_NOR_CMD_RESET_MEM;
1167 	ret = qspi_send_cmd(dev, &cmd);
1168 	if (ret != 0) {
1169 		LOG_ERR("%d: Failed to send RESET_MEM", ret);
1170 		return ret;
1171 	}
1172 	return 0;
1173 }
1174 #endif
1175 
flash_stm32_qspi_init(const struct device * dev)1176 static int flash_stm32_qspi_init(const struct device *dev)
1177 {
1178 	const struct flash_stm32_qspi_config *dev_cfg = dev->config;
1179 	struct flash_stm32_qspi_data *dev_data = dev->data;
1180 	uint32_t ahb_clock_freq;
1181 	uint32_t prescaler = 0;
1182 	int ret;
1183 
1184 	/* Signals configuration */
1185 	ret = pinctrl_apply_state(dev_cfg->pcfg, PINCTRL_STATE_DEFAULT);
1186 	if (ret < 0) {
1187 		LOG_ERR("QSPI pinctrl setup failed (%d)", ret);
1188 		return ret;
1189 	}
1190 
1191 #if STM32_QSPI_RESET_GPIO
1192 	flash_stm32_qspi_gpio_reset(dev);
1193 #endif
1194 #if STM32_QSPI_USE_DMA
1195 	/*
1196 	 * DMA configuration
1197 	 * Due to use of QSPI HAL API in current driver,
1198 	 * both HAL and Zephyr DMA drivers should be configured.
1199 	 * The required configuration for Zephyr DMA driver should only provide
1200 	 * the minimum information to inform the DMA slot will be in used and
1201 	 * how to route callbacks.
1202 	 */
1203 	struct dma_config dma_cfg = dev_data->dma.cfg;
1204 	static DMA_HandleTypeDef hdma;
1205 
1206 	if (!device_is_ready(dev_data->dma.dev)) {
1207 		LOG_ERR("%s device not ready", dev_data->dma.dev->name);
1208 		return -ENODEV;
1209 	}
1210 
1211 	/* Proceed to the minimum Zephyr DMA driver init */
1212 	dma_cfg.user_data = &hdma;
1213 	/* HACK: This field is used to inform driver that it is overridden */
1214 	dma_cfg.linked_channel = STM32_DMA_HAL_OVERRIDE;
1215 	ret = dma_config(dev_data->dma.dev, dev_data->dma.channel, &dma_cfg);
1216 	if (ret != 0) {
1217 		return ret;
1218 	}
1219 
1220 	/* Proceed to the HAL DMA driver init */
1221 	if (dma_cfg.source_data_size != dma_cfg.dest_data_size) {
1222 		LOG_ERR("Source and destination data sizes not aligned");
1223 		return -EINVAL;
1224 	}
1225 
1226 	int index = find_lsb_set(dma_cfg.source_data_size) - 1;
1227 
1228 	hdma.Init.PeriphDataAlignment = table_p_size[index];
1229 	hdma.Init.MemDataAlignment = table_m_size[index];
1230 	hdma.Init.PeriphInc = DMA_PINC_DISABLE;
1231 	hdma.Init.MemInc = DMA_MINC_ENABLE;
1232 	hdma.Init.Mode = DMA_NORMAL;
1233 	hdma.Init.Priority = table_priority[dma_cfg.channel_priority];
1234 #ifdef CONFIG_DMA_STM32_V1
1235 	/* TODO: Not tested in this configuration */
1236 	hdma.Init.Channel = dma_cfg.dma_slot;
1237 	hdma.Instance = __LL_DMA_GET_STREAM_INSTANCE(dev_data->dma.reg,
1238 						     dev_data->dma.channel);
1239 #else
1240 	hdma.Init.Request = dma_cfg.dma_slot;
1241 #ifdef CONFIG_DMAMUX_STM32
1242 	/* HAL expects a valid DMA channel (not a DMAMUX channel) */
1243 	hdma.Instance = __LL_DMA_GET_CHANNEL_INSTANCE(dev_data->dma.reg,
1244 						      dev_data->dma.channel);
1245 #else
1246 	hdma.Instance = __LL_DMA_GET_CHANNEL_INSTANCE(dev_data->dma.reg,
1247 						      dev_data->dma.channel-1);
1248 #endif
1249 #endif /* CONFIG_DMA_STM32_V1 */
1250 
1251 	/* Initialize DMA HAL */
1252 	__HAL_LINKDMA(&dev_data->hqspi, hdma, hdma);
1253 	HAL_DMA_Init(&hdma);
1254 
1255 #endif /* STM32_QSPI_USE_DMA */
1256 
1257 	/* Clock configuration */
1258 	if (clock_control_on(DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE),
1259 			     (clock_control_subsys_t) &dev_cfg->pclken) != 0) {
1260 		LOG_DBG("Could not enable QSPI clock");
1261 		return -EIO;
1262 	}
1263 
1264 	if (clock_control_get_rate(DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE),
1265 			(clock_control_subsys_t) &dev_cfg->pclken,
1266 			&ahb_clock_freq) < 0) {
1267 		LOG_DBG("Failed to get AHB clock frequency");
1268 		return -EIO;
1269 	}
1270 
1271 	for (; prescaler <= STM32_QSPI_CLOCK_PRESCALER_MAX; prescaler++) {
1272 		uint32_t clk = ahb_clock_freq / (prescaler + 1);
1273 
1274 		if (clk <= dev_cfg->max_frequency) {
1275 			break;
1276 		}
1277 	}
1278 	__ASSERT_NO_MSG(prescaler <= STM32_QSPI_CLOCK_PRESCALER_MAX);
1279 	/* Initialize QSPI HAL */
1280 	dev_data->hqspi.Init.ClockPrescaler = prescaler;
1281 	/* Give a bit position from 0 to 31 to the HAL init minus 1 for the DCR1 reg */
1282 	dev_data->hqspi.Init.FlashSize = find_lsb_set(dev_cfg->flash_size) - 2;
1283 
1284 	HAL_QSPI_Init(&dev_data->hqspi);
1285 
1286 #if DT_NODE_HAS_PROP(DT_NODELABEL(quadspi), flash_id)
1287 	uint8_t qspi_flash_id = DT_PROP(DT_NODELABEL(quadspi), flash_id);
1288 
1289 	HAL_QSPI_SetFlashID(&dev_data->hqspi,
1290 			    (qspi_flash_id - 1) << QUADSPI_CR_FSEL_Pos);
1291 #endif
1292 	/* Initialize semaphores */
1293 	k_sem_init(&dev_data->sem, 1, 1);
1294 	k_sem_init(&dev_data->sync, 0, 1);
1295 
1296 	/* Run IRQ init */
1297 	dev_cfg->irq_config(dev);
1298 
1299 #if STM32_QSPI_RESET_CMD
1300 	flash_stm32_qspi_send_reset(dev);
1301 	k_busy_wait(DT_INST_PROP(0, reset_cmd_wait));
1302 #endif
1303 
1304 	/* Run NOR init */
1305 	const uint8_t decl_nph = 2;
1306 	union {
1307 		/* We only process BFP so use one parameter block */
1308 		uint8_t raw[JESD216_SFDP_SIZE(decl_nph)];
1309 		struct jesd216_sfdp_header sfdp;
1310 	} u;
1311 	const struct jesd216_sfdp_header *hp = &u.sfdp;
1312 
1313 	ret = qspi_read_sfdp(dev, 0, u.raw, sizeof(u.raw));
1314 	if (ret != 0) {
1315 		LOG_ERR("SFDP read failed: %d", ret);
1316 		return ret;
1317 	}
1318 
1319 	uint32_t magic = jesd216_sfdp_magic(hp);
1320 
1321 	if (magic != JESD216_SFDP_MAGIC) {
1322 		LOG_ERR("SFDP magic %08x invalid", magic);
1323 		return -EINVAL;
1324 	}
1325 
1326 	LOG_INF("%s: SFDP v %u.%u AP %x with %u PH", dev->name,
1327 		hp->rev_major, hp->rev_minor, hp->access, 1 + hp->nph);
1328 
1329 	const struct jesd216_param_header *php = hp->phdr;
1330 	const struct jesd216_param_header *phpe = php +
1331 						     MIN(decl_nph, 1 + hp->nph);
1332 
1333 	while (php != phpe) {
1334 		uint16_t id = jesd216_param_id(php);
1335 
1336 		LOG_INF("PH%u: %04x rev %u.%u: %u DW @ %x",
1337 			(php - hp->phdr), id, php->rev_major, php->rev_minor,
1338 			php->len_dw, jesd216_param_addr(php));
1339 
1340 		if (id == JESD216_SFDP_PARAM_ID_BFP) {
1341 			union {
1342 				uint32_t dw[20];
1343 				struct jesd216_bfp bfp;
1344 			} u2;
1345 			const struct jesd216_bfp *bfp = &u2.bfp;
1346 
1347 			ret = qspi_read_sfdp(dev, jesd216_param_addr(php),
1348 					     (uint8_t *)u2.dw,
1349 					     MIN(sizeof(uint32_t) * php->len_dw, sizeof(u2.dw)));
1350 			if (ret == 0) {
1351 				ret = spi_nor_process_bfp(dev, php, bfp);
1352 			}
1353 
1354 			if (ret != 0) {
1355 				LOG_ERR("SFDP BFP failed: %d", ret);
1356 				break;
1357 			}
1358 		}
1359 		++php;
1360 	}
1361 
1362 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
1363 	ret = setup_pages_layout(dev);
1364 	if (ret != 0) {
1365 		LOG_ERR("layout setup failed: %d", ret);
1366 		return -ENODEV;
1367 	}
1368 #endif /* CONFIG_FLASH_PAGE_LAYOUT */
1369 
1370 	LOG_INF("NOR quad-flash at 0x%lx (0x%x bytes)",
1371 		(long)(STM32_QSPI_BASE_ADDRESS),
1372 		dev_cfg->flash_size);
1373 
1374 	return 0;
1375 }
1376 
1377 #define DMA_CHANNEL_CONFIG(node, dir)					\
1378 		DT_DMAS_CELL_BY_NAME(node, dir, channel_config)
1379 
1380 #define QSPI_DMA_CHANNEL_INIT(node, dir)				\
1381 	.dev = DEVICE_DT_GET(DT_DMAS_CTLR(node)),			\
1382 	.channel = DT_DMAS_CELL_BY_NAME(node, dir, channel),		\
1383 	.reg = (DMA_TypeDef *)DT_REG_ADDR(				\
1384 				   DT_PHANDLE_BY_NAME(node, dmas, dir)),\
1385 	.cfg = {							\
1386 		.dma_slot = DT_DMAS_CELL_BY_NAME(node, dir, slot),	\
1387 		.source_data_size = STM32_DMA_CONFIG_PERIPHERAL_DATA_SIZE( \
1388 					DMA_CHANNEL_CONFIG(node, dir)), \
1389 		.dest_data_size = STM32_DMA_CONFIG_MEMORY_DATA_SIZE(    \
1390 					DMA_CHANNEL_CONFIG(node, dir)), \
1391 		.channel_priority = STM32_DMA_CONFIG_PRIORITY(		\
1392 					DMA_CHANNEL_CONFIG(node, dir)), \
1393 		.dma_callback = qspi_dma_callback,			\
1394 	},								\
1395 
1396 #define QSPI_DMA_CHANNEL(node, dir)					\
1397 	.dma = {							\
1398 		COND_CODE_1(DT_DMAS_HAS_NAME(node, dir),		\
1399 			(QSPI_DMA_CHANNEL_INIT(node, dir)),		\
1400 			(NULL))						\
1401 		},
1402 
1403 #define QSPI_FLASH_MODULE(drv_id, flash_id) 				\
1404 		(DT_DRV_INST(drv_id), qspi_nor_flash_##flash_id)
1405 
1406 static void flash_stm32_qspi_irq_config_func(const struct device *dev);
1407 
1408 #define DT_WRITEOC_PROP_OR(inst, default_value)                                              \
1409 	COND_CODE_1(DT_INST_NODE_HAS_PROP(inst, writeoc),                                    \
1410 		    (_CONCAT(SPI_NOR_CMD_, DT_STRING_TOKEN(DT_DRV_INST(inst), writeoc))),    \
1411 		    ((default_value)))
1412 
1413 #define DT_QER_PROP_OR(inst, default_value)                                                  \
1414 	COND_CODE_1(DT_INST_NODE_HAS_PROP(inst, quad_enable_requirements),                   \
1415 		    (_CONCAT(JESD216_DW15_QER_VAL_,                                          \
1416 			     DT_STRING_TOKEN(DT_DRV_INST(inst), quad_enable_requirements))), \
1417 		    ((default_value)))
1418 
1419 #define STM32_QSPI_NODE DT_INST_PARENT(0)
1420 
1421 PINCTRL_DT_DEFINE(STM32_QSPI_NODE);
1422 
1423 static const struct flash_stm32_qspi_config flash_stm32_qspi_cfg = {
1424 	.regs = (QUADSPI_TypeDef *)DT_REG_ADDR(STM32_QSPI_NODE),
1425 	.pclken = {
1426 		.enr = DT_CLOCKS_CELL(STM32_QSPI_NODE, bits),
1427 		.bus = DT_CLOCKS_CELL(STM32_QSPI_NODE, bus)
1428 	},
1429 	.irq_config = flash_stm32_qspi_irq_config_func,
1430 	.flash_size = DT_INST_REG_ADDR_BY_IDX(0, 1),
1431 	.max_frequency = DT_INST_PROP(0, qspi_max_frequency),
1432 	.pcfg = PINCTRL_DT_DEV_CONFIG_GET(STM32_QSPI_NODE),
1433 #if STM32_QSPI_RESET_GPIO
1434 	.reset = GPIO_DT_SPEC_INST_GET(0, reset_gpios),
1435 #endif
1436 #if DT_NODE_HAS_PROP(DT_INST(0, st_stm32_qspi_nor), jedec_id)
1437 	.jedec_id = DT_INST_PROP(0, jedec_id),
1438 #endif /* jedec_id */
1439 };
1440 
1441 static struct flash_stm32_qspi_data flash_stm32_qspi_dev_data = {
1442 	.hqspi = {
1443 		.Instance = (QUADSPI_TypeDef *)DT_REG_ADDR(STM32_QSPI_NODE),
1444 		.Init = {
1445 			.FifoThreshold = STM32_QSPI_FIFO_THRESHOLD,
1446 			.SampleShifting = QSPI_SAMPLE_SHIFTING_NONE,
1447 			.ChipSelectHighTime = QSPI_CS_HIGH_TIME_1_CYCLE,
1448 			.ClockMode = QSPI_CLOCK_MODE_0,
1449 			},
1450 	},
1451 	.qer_type = DT_QER_PROP_OR(0, JESD216_DW15_QER_VAL_S1B6),
1452 	.qspi_write_cmd = DT_WRITEOC_PROP_OR(0, SPI_NOR_CMD_PP_1_4_4),
1453 	QSPI_DMA_CHANNEL(STM32_QSPI_NODE, tx_rx)
1454 };
1455 
1456 DEVICE_DT_INST_DEFINE(0, &flash_stm32_qspi_init, NULL,
1457 		      &flash_stm32_qspi_dev_data, &flash_stm32_qspi_cfg,
1458 		      POST_KERNEL, CONFIG_FLASH_INIT_PRIORITY,
1459 		      &flash_stm32_qspi_driver_api);
1460 
flash_stm32_qspi_irq_config_func(const struct device * dev)1461 static void flash_stm32_qspi_irq_config_func(const struct device *dev)
1462 {
1463 	IRQ_CONNECT(DT_IRQN(STM32_QSPI_NODE), DT_IRQ(STM32_QSPI_NODE, priority),
1464 		    flash_stm32_qspi_isr, DEVICE_DT_INST_GET(0), 0);
1465 	irq_enable(DT_IRQN(STM32_QSPI_NODE));
1466 }
1467 
1468 #endif
1469