1 /**
2 ******************************************************************************
3 * @file stm32c0xx_hal_flash.c
4 * @author MCD Application Team
5 * @brief FLASH HAL module driver.
6 * This file provides firmware functions to manage the following
7 * functionalities of the internal FLASH memory:
8 * + Program operations functions
9 * + Memory Control functions
10 * + Peripheral Errors functions
11 *
12 ******************************************************************************
13 * @attention
14 *
15 * Copyright (c) 2022 STMicroelectronics.
16 * All rights reserved.
17 *
18 * This software is licensed under terms that can be found in the LICENSE file
19 * in the root directory of this software component.
20 * If no LICENSE file comes with this software, it is provided AS-IS.
21 *
22 ******************************************************************************
23 @verbatim
24 ==============================================================================
25 ##### FLASH peripheral features #####
26 ==============================================================================
27
28 [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
29 to the Flash memory. It implements the erase and program Flash memory operations
30 and the read and write protection mechanisms.
31
32 [..] The Flash memory interface accelerates code execution with a system of instruction
33 prefetch and cache lines.
34
35 [..] The FLASH main features are:
36 (+) Flash memory read operations
37 (+) Flash memory program/erase operations
38 (+) Read / write protections
39 (+) Option bytes programming
40 (+) Prefetch on I-Code
41 (+) 32 cache lines of 4*64 bits on I-Code
42
43 ##### How to use this driver #####
44 ==============================================================================
45 [..]
46 This driver provides functions and macros to configure and program the FLASH
47 memory of all STM32C0xx devices.
48
49 (#) Flash Memory IO Programming functions:
50 (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and
51 HAL_FLASH_Lock() functions
52 (++) Program functions: double word and fast program (full row programming)
53 (++) There are two modes of programming:
54 (+++) Polling mode using HAL_FLASH_Program() function
55 (+++) Interrupt mode using HAL_FLASH_Program_IT() function
56
57 (#) Interrupts and flags management functions:
58 (++) Handle FLASH interrupts by calling HAL_FLASH_IRQHandler()
59 (++) Callback functions are called when the flash operations are finished :
60 HAL_FLASH_EndOfOperationCallback() when everything is ok, otherwise
61 HAL_FLASH_OperationErrorCallback()
62 (++) Get error flag status by calling HAL_GetError()
63
64 (#) Option bytes management functions :
65 (++) Lock and Unlock the option bytes using HAL_FLASH_OB_Unlock() and
66 HAL_FLASH_OB_Lock() functions
67 (++) Launch the reload of the option bytes using HAL_FLASH_OB_Launch() function.
68 In this case, a reset is generated
69
70 [..]
71 In addition to these functions, this driver includes a set of macros allowing
72 to handle the following operations:
73 (+) Set the latency
74 (+) Enable/Disable the prefetch buffer
75 (+) Enable/Disable the Instruction cache
76 (+) Reset the Instruction cache
77 (+) Enable/Disable the Flash power-down during low-power modes
78 (+) Enable/Disable the Flash interrupts
79 (+) Monitor the Flash flags status
80
81 @endverbatim
82 ******************************************************************************
83 */
84
85 /* Includes ------------------------------------------------------------------*/
86 #include "stm32c0xx_hal.h"
87
88 /** @addtogroup STM32C0xx_HAL_Driver
89 * @{
90 */
91
92 /** @defgroup FLASH FLASH
93 * @brief FLASH HAL module driver
94 * @{
95 */
96
97 #ifdef HAL_FLASH_MODULE_ENABLED
98
99 /* Private typedef -----------------------------------------------------------*/
100 /* Private defines -----------------------------------------------------------*/
101 /* Private macros ------------------------------------------------------------*/
102 /* Private variables ---------------------------------------------------------*/
103 /** @defgroup FLASH_Private_Variables FLASH Private Variables
104 * @{
105 */
106 /**
107 * @brief Variable used for Program/Erase sectors under interruption
108 */
109 FLASH_ProcessTypeDef pFlash = {.Lock = HAL_UNLOCKED, \
110 .ErrorCode = HAL_FLASH_ERROR_NONE, \
111 .ProcedureOnGoing = FLASH_TYPENONE, \
112 .Address = 0U, \
113 .Page = 0U, \
114 .NbPagesToErase = 0U
115 };
116 /**
117 * @}
118 */
119
120 /* Private function prototypes -----------------------------------------------*/
121 /** @defgroup FLASH_Private_Functions FLASH Private Functions
122 * @{
123 */
124 static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data);
125 static void FLASH_Program_Fast(uint32_t Address, uint32_t DataAddress);
126 /**
127 * @}
128 */
129
130 /* Exported functions --------------------------------------------------------*/
131 /** @defgroup FLASH_Exported_Functions FLASH Exported Functions
132 * @{
133 */
134
135 /** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions
136 * @brief Programming operation functions
137 *
138 @verbatim
139 ===============================================================================
140 ##### Programming operation functions #####
141 ===============================================================================
142 [..]
143 This subsection provides a set of functions allowing to manage the FLASH
144 program operations.
145
146 @endverbatim
147 * @{
148 */
149
150 /**
151 * @brief Program double word or fast program of a row at a specified address.
152 * @param TypeProgram Indicate the way to program at a specified address.
153 * This parameter can be a value of @ref FLASH_Type_Program
154 * @param Address Specifies the address to be programmed.
155 * @param Data Specifies the data to be programmed
156 * This parameter is the data for the double word program and the address where
157 * are stored the data for the row fast program.
158 *
159 * @retval HAL_StatusTypeDef HAL Status
160 */
HAL_FLASH_Program(uint32_t TypeProgram,uint32_t Address,uint64_t Data)161 HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
162 {
163 HAL_StatusTypeDef status;
164
165 /* Check the parameters */
166 assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
167 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
168
169 /* Process Locked */
170 __HAL_LOCK(&pFlash);
171
172 /* Reset error code */
173 pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
174
175 /* Wait for last operation to be completed */
176 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
177
178 if (status == HAL_OK)
179 {
180 if (TypeProgram == FLASH_TYPEPROGRAM_DOUBLEWORD)
181 {
182 /* Check the parameters */
183 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
184
185 /* Program double-word (64-bit) at a specified address */
186 FLASH_Program_DoubleWord(Address, Data);
187 }
188 else
189 {
190 /* Check the parameters */
191 assert_param(IS_FLASH_FAST_PROGRAM_ADDRESS(Address));
192
193 /* Fast program a 32 row double-word (64-bit) at a specified address */
194 FLASH_Program_Fast(Address, (uint32_t)Data);
195 }
196
197 /* Wait for last operation to be completed */
198 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
199
200 /* If the program operation is completed, disable the PG or FSTPG Bit */
201 CLEAR_BIT(FLASH->CR, TypeProgram);
202 }
203
204 /* Process Unlocked */
205 __HAL_UNLOCK(&pFlash);
206
207 /* return status */
208 return status;
209 }
210
211 /**
212 * @brief Program double word or fast program of a row at a specified address with interrupt enabled.
213 * @param TypeProgram Indicate the way to program at a specified address.
214 * This parameter can be a value of @ref FLASH_Type_Program
215 * @param Address Specifies the address to be programmed.
216 * @param Data Specifies the data to be programmed
217 * This parameter is the data for the double word program and the address where
218 * are stored the data for the row fast program.
219 *
220 * @retval HAL Status
221 */
HAL_FLASH_Program_IT(uint32_t TypeProgram,uint32_t Address,uint64_t Data)222 HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
223 {
224 HAL_StatusTypeDef status;
225
226 /* Check the parameters */
227 assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
228 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
229
230 /* Process Locked */
231 __HAL_LOCK(&pFlash);
232
233 /* Reset error code */
234 pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
235
236 /* Wait for last operation to be completed */
237 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
238
239 if (status != HAL_OK)
240 {
241 /* Process Unlocked */
242 __HAL_UNLOCK(&pFlash);
243 }
244 else
245 {
246 /* Set internal variables used by the IRQ handler */
247 pFlash.ProcedureOnGoing = TypeProgram;
248 pFlash.Address = Address;
249
250 /* Enable End of Operation and Error interrupts */
251 __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP | FLASH_IT_OPERR);
252
253 if (TypeProgram == FLASH_TYPEPROGRAM_DOUBLEWORD)
254 {
255 /* Check the parameters */
256 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
257
258 /* Program double-word (64-bit) at a specified address */
259 FLASH_Program_DoubleWord(Address, Data);
260 }
261 else
262 {
263 /* Check the parameters */
264 assert_param(IS_FLASH_FAST_PROGRAM_ADDRESS(Address));
265
266 /* Fast program a 32 row double-word (64-bit) at a specified address */
267 FLASH_Program_Fast(Address, (uint32_t)Data);
268 }
269 }
270
271 /* return status */
272 return status;
273 }
274
275 /**
276 * @brief Handle FLASH interrupt request.
277 * @retval None
278 */
HAL_FLASH_IRQHandler(void)279 void HAL_FLASH_IRQHandler(void)
280 {
281 uint32_t param = 0xFFFFFFFFU;
282 uint32_t error;
283
284 /* Save flash errors */
285 error = (FLASH->SR & FLASH_FLAG_SR_ERROR);
286
287 CLEAR_BIT(FLASH->CR, pFlash.ProcedureOnGoing);
288
289 /* A] Set parameter for user or error callbacks */
290 /* check operation was a program or erase */
291 if ((pFlash.ProcedureOnGoing & (FLASH_TYPEPROGRAM_DOUBLEWORD | FLASH_TYPEPROGRAM_FAST)) != 0x00U)
292 {
293 /* return address being programmed */
294 param = pFlash.Address;
295 }
296 else if ((pFlash.ProcedureOnGoing & (FLASH_TYPEERASE_MASS | FLASH_TYPEERASE_PAGES)) != 0x00U)
297 {
298 /* return page number being erased (0 for mass erase) */
299 param = pFlash.Page;
300 }
301 else
302 {
303 /* Nothing to do */
304 }
305
306 /* B] Check errors */
307 if (error != 0x00U)
308 {
309 /*Save the error code*/
310 pFlash.ErrorCode |= error;
311
312 /* clear error flags */
313 __HAL_FLASH_CLEAR_FLAG(error);
314
315 /*Stop the procedure ongoing*/
316 pFlash.ProcedureOnGoing = FLASH_TYPENONE;
317
318 /* Error callback */
319 HAL_FLASH_OperationErrorCallback(param);
320 }
321
322 /* C] Check FLASH End of Operation flag */
323 if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != 0x00U)
324 {
325 /* Clear FLASH End of Operation pending bit */
326 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
327
328 if (pFlash.ProcedureOnGoing == FLASH_TYPEERASE_PAGES)
329 {
330 /* Nb of pages to erased can be decreased */
331 pFlash.NbPagesToErase--;
332
333 /* Check if there are still pages to erase*/
334 if (pFlash.NbPagesToErase != 0x00U)
335 {
336 /* Increment page number */
337 pFlash.Page++;
338 FLASH_PageErase(pFlash.Page);
339 }
340 else
341 {
342 /* No more pages to erase: stop erase pages procedure */
343 pFlash.ProcedureOnGoing = FLASH_TYPENONE;
344 }
345 }
346 else
347 {
348 /*Stop the ongoing procedure */
349 pFlash.ProcedureOnGoing = FLASH_TYPENONE;
350 }
351
352 /* User callback */
353 HAL_FLASH_EndOfOperationCallback(param);
354 }
355
356 if (pFlash.ProcedureOnGoing == FLASH_TYPENONE)
357 {
358 /* Disable End of Operation and Error interrupts */
359 __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP | FLASH_IT_OPERR);
360
361 /* Process Unlocked */
362 __HAL_UNLOCK(&pFlash);
363 }
364 }
365
366 /**
367 * @brief FLASH end of operation interrupt callback.
368 * @param ReturnValue The value saved in this parameter depends on the ongoing procedure
369 * Mass Erase: 0
370 * Page Erase: Page which has been erased
371 * Program: Address which was selected for data program
372 * @retval None
373 */
HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)374 __weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
375 {
376 /* Prevent unused argument(s) compilation warning */
377 UNUSED(ReturnValue);
378
379 /* NOTE : This function should not be modified, when the callback is needed,
380 the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
381 */
382 }
383
384 /**
385 * @brief FLASH operation error interrupt callback.
386 * @param ReturnValue The value saved in this parameter depends on the ongoing procedure
387 * Mass Erase: 0
388 * Page Erase: Page number which returned an error
389 * Program: Address which was selected for data program
390 * @retval None
391 */
HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)392 __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
393 {
394 /* Prevent unused argument(s) compilation warning */
395 UNUSED(ReturnValue);
396
397 /* NOTE : This function should not be modified, when the callback is needed,
398 the HAL_FLASH_OperationErrorCallback could be implemented in the user file
399 */
400 }
401
402 /**
403 * @}
404 */
405
406 /** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions
407 * @brief Management functions
408 *
409 @verbatim
410 ===============================================================================
411 ##### Peripheral Control functions #####
412 ===============================================================================
413 [..]
414 This subsection provides a set of functions allowing to control the FLASH
415 memory operations.
416
417 @endverbatim
418 * @{
419 */
420
421 /**
422 * @brief Unlock the FLASH control register access.
423 * @retval HAL Status
424 */
HAL_FLASH_Unlock(void)425 HAL_StatusTypeDef HAL_FLASH_Unlock(void)
426 {
427 HAL_StatusTypeDef status = HAL_OK;
428
429 if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00U)
430 {
431 /* Authorize the FLASH Registers access */
432 WRITE_REG(FLASH->KEYR, FLASH_KEY1);
433 WRITE_REG(FLASH->KEYR, FLASH_KEY2);
434
435 /* verify Flash is unlock */
436 if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00U)
437 {
438 status = HAL_ERROR;
439 }
440 }
441
442 return status;
443 }
444
445 /**
446 * @brief Lock the FLASH control register access.
447 * @retval HAL Status
448 */
HAL_FLASH_Lock(void)449 HAL_StatusTypeDef HAL_FLASH_Lock(void)
450 {
451 HAL_StatusTypeDef status = HAL_ERROR;
452
453 /* Set the LOCK Bit to lock the FLASH Registers access */
454 SET_BIT(FLASH->CR, FLASH_CR_LOCK);
455
456 /* verify Flash is locked */
457 if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00u)
458 {
459 status = HAL_OK;
460 }
461
462 return status;
463 }
464
465 /**
466 * @brief Unlock the FLASH Option Bytes Registers access.
467 * @retval HAL Status
468 */
HAL_FLASH_OB_Unlock(void)469 HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void)
470 {
471 HAL_StatusTypeDef status = HAL_ERROR;
472
473 if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) != 0x00U)
474 {
475 /* Authorizes the Option Byte register programming */
476 WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1);
477 WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2);
478
479 /* verify option bytes are unlocked */
480 if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) == 0x00U)
481 {
482 status = HAL_OK;
483 }
484 }
485
486 return status;
487 }
488
489 /**
490 * @brief Lock the FLASH Option Bytes Registers access.
491 * @retval HAL Status
492 */
HAL_FLASH_OB_Lock(void)493 HAL_StatusTypeDef HAL_FLASH_OB_Lock(void)
494 {
495 HAL_StatusTypeDef status = HAL_ERROR;
496
497 /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */
498 SET_BIT(FLASH->CR, FLASH_CR_OPTLOCK);
499
500 /* verify option bytes are locked */
501 if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) != 0x00u)
502 {
503 status = HAL_OK;
504 }
505
506 return status;
507 }
508
509 /**
510 * @brief Launch the option byte loading.
511 * @retval HAL Status
512 */
HAL_FLASH_OB_Launch(void)513 HAL_StatusTypeDef HAL_FLASH_OB_Launch(void)
514 {
515 /* Set the bit to force the option byte reloading */
516 SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH);
517
518 /* We should not reach here : Option byte launch generates Option byte reset
519 so return error */
520 return HAL_ERROR;
521 }
522
523 /**
524 * @}
525 */
526
527 /** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions
528 * @brief Peripheral Errors functions
529 *
530 @verbatim
531 ===============================================================================
532 ##### Peripheral Errors functions #####
533 ===============================================================================
534 [..]
535 This subsection permits to get in run-time Errors of the FLASH peripheral.
536
537 @endverbatim
538 * @{
539 */
540
541 /**
542 * @brief Get the specific FLASH error flag.
543 * @retval FLASH_ErrorCode The returned value can be
544 * @arg @ref HAL_FLASH_ERROR_NONE No error set
545 * @arg @ref HAL_FLASH_ERROR_OP FLASH Operation error
546 * @arg @ref HAL_FLASH_ERROR_PROG FLASH Programming error
547 * @arg @ref HAL_FLASH_ERROR_WRP FLASH Write protection error
548 * @arg @ref HAL_FLASH_ERROR_PGA FLASH Programming alignment error
549 * @arg @ref HAL_FLASH_ERROR_SIZ FLASH Size error
550 * @arg @ref HAL_FLASH_ERROR_PGS FLASH Programming sequence error
551 * @arg @ref HAL_FLASH_ERROR_MIS FLASH Fast programming data miss error
552 * @arg @ref HAL_FLASH_ERROR_FAST FLASH Fast programming error
553 * @arg @ref HAL_FLASH_ERROR_RD FLASH Read Protection error (PCROP)
554 * @arg @ref HAL_FLASH_ERROR_OPTV FLASH Option validity error
555 */
HAL_FLASH_GetError(void)556 uint32_t HAL_FLASH_GetError(void)
557 {
558 return pFlash.ErrorCode;
559 }
560
561 /**
562 * @}
563 */
564
565 /**
566 * @}
567 */
568
569 /* Private functions ---------------------------------------------------------*/
570
571 /** @addtogroup FLASH_Private_Functions
572 * @{
573 */
574
575 /**
576 * @brief Wait for a FLASH operation to complete.
577 * @param Timeout maximum flash operation timeout
578 * @retval HAL_StatusTypeDef HAL Status
579 */
FLASH_WaitForLastOperation(uint32_t Timeout)580 HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
581 {
582 uint32_t error;
583 /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
584 Even if the FLASH operation fails, the BUSY flag will be reset and an error
585 flag will be set */
586 uint32_t timeout = HAL_GetTick() + Timeout;
587
588 /* Wait if any operation is ongoing */
589 while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != 0x00U)
590 {
591 if (HAL_GetTick() >= timeout)
592 {
593 return HAL_TIMEOUT;
594 }
595 }
596
597 /* check flash errors */
598 error = (FLASH->SR & FLASH_FLAG_SR_ERROR);
599
600 /* clear error flags */
601 __HAL_FLASH_CLEAR_FLAG(error);
602
603 if (error != 0x00U)
604 {
605 /*Save the error code*/
606 pFlash.ErrorCode = error;
607
608 return HAL_ERROR;
609 }
610
611 /* Wait for control register to be written */
612 timeout = HAL_GetTick() + Timeout;
613
614 while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_CFGBSY) != 0x00U)
615 {
616 if (HAL_GetTick() >= timeout)
617 {
618 return HAL_TIMEOUT;
619 }
620 }
621
622 return HAL_OK;
623 }
624
625 /**
626 * @brief Program double-word (64-bit) at a specified address.
627 * @param Address Specifies the address to be programmed.
628 * @param Data Specifies the data to be programmed.
629 * @retval None
630 */
FLASH_Program_DoubleWord(uint32_t Address,uint64_t Data)631 static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data)
632 {
633 /* Set PG bit */
634 SET_BIT(FLASH->CR, FLASH_CR_PG);
635
636 /* Program first word */
637 *(uint32_t *)Address = (uint32_t)Data;
638
639 /* Barrier to ensure programming is performed in 2 steps, in right order
640 (independently of compiler optimization behavior) */
641 __ISB();
642
643 /* Program second word */
644 *(uint32_t *)(Address + 4U) = (uint32_t)(Data >> 32U);
645 }
646
647 /**
648 * @brief Fast program a 32 row double-word (64-bit) at a specified address.
649 * @param Address Specifies the address to be programmed.
650 * @param DataAddress Specifies the address where the data are stored.
651 * @retval None
652 */
FLASH_Program_Fast(uint32_t Address,uint32_t DataAddress)653 static __RAM_FUNC void FLASH_Program_Fast(uint32_t Address, uint32_t DataAddress)
654 {
655 uint8_t index = 0;
656 uint32_t dest = Address;
657 uint32_t src = DataAddress;
658 uint32_t primask_bit;
659
660 /* Set FSTPG bit */
661 SET_BIT(FLASH->CR, FLASH_CR_FSTPG);
662
663 /* Enter critical section: row programming should not be longer than 7 ms */
664 primask_bit = __get_PRIMASK();
665 __disable_irq();
666
667 /* Fast Program : 64 words */
668 while (index < 64U)
669 {
670 *(uint32_t *)dest = *(uint32_t *)src;
671 src += 4U;
672 dest += 4U;
673 index++;
674 }
675
676 /* wait for BSY1 in order to be sure that flash operation is ended befoire
677 allowing prefetch in flash. Timeout does not return status, as it will
678 be anyway done later */
679 while ((FLASH->SR & FLASH_SR_BSY1) != 0x00U)
680 {
681 }
682
683 /* Exit critical section: restore previous priority mask */
684 __set_PRIMASK(primask_bit);
685 }
686
687 /**
688 * @}
689 */
690
691 #endif /* HAL_FLASH_MODULE_ENABLED */
692
693 /**
694 * @}
695 */
696
697 /**
698 * @}
699 */
700