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