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