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