Merge pull request #11189 from klutvott123/move-telemetry-displayport-init
[betaflight.git] / lib / main / STM32F3 / Drivers / STM32F3xx_HAL_Driver / Src / stm32f3xx_hal_flash.c
blob430bf3f8033d1af43878c110f303c1baaf70a46e
1 /**
2 ******************************************************************************
3 * @file stm32f3xx_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 State functions
12 @verbatim
13 ==============================================================================
14 ##### FLASH peripheral features #####
15 ==============================================================================
16 [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
17 to the Flash memory. It implements the erase and program Flash memory operations
18 and the read and write protection mechanisms.
20 [..] The Flash memory interface accelerates code execution with a system of instruction
21 prefetch.
23 [..] The FLASH main features are:
24 (+) Flash memory read operations
25 (+) Flash memory program/erase operations
26 (+) Read / write protections
27 (+) Prefetch on I-Code
28 (+) Option Bytes programming
31 ##### How to use this driver #####
32 ==============================================================================
33 [..]
34 This driver provides functions and macros to configure and program the FLASH
35 memory of all STM32F3xx devices.
37 (#) FLASH Memory I/O Programming functions: this group includes all needed
38 functions to erase and program the main memory:
39 (++) Lock and Unlock the FLASH interface
40 (++) Erase function: Erase page, erase all pages
41 (++) Program functions: half word, word and doubleword
42 (#) FLASH Option Bytes Programming functions: this group includes all needed
43 functions to manage the Option Bytes:
44 (++) Lock and Unlock the Option Bytes
45 (++) Set/Reset the write protection
46 (++) Set the Read protection Level
47 (++) Program the user Option Bytes
48 (++) Launch the Option Bytes loader
49 (++) Erase Option Bytes
50 (++) Program the data Option Bytes
51 (++) Get the Write protection.
52 (++) Get the user option bytes.
54 (#) Interrupts and flags management functions : this group
55 includes all needed functions to:
56 (++) Handle FLASH interrupts
57 (++) Wait for last FLASH operation according to its status
58 (++) Get error flag status
60 [..] In addition to these function, this driver includes a set of macros allowing
61 to handle the following operations:
63 (+) Set/Get the latency
64 (+) Enable/Disable the prefetch buffer
65 (+) Enable/Disable the half cycle access
66 (+) Enable/Disable the FLASH interrupts
67 (+) Monitor the FLASH flags status
69 @endverbatim
70 ******************************************************************************
71 * @attention
73 * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
75 * Redistribution and use in source and binary forms, with or without modification,
76 * are permitted provided that the following conditions are met:
77 * 1. Redistributions of source code must retain the above copyright notice,
78 * this list of conditions and the following disclaimer.
79 * 2. Redistributions in binary form must reproduce the above copyright notice,
80 * this list of conditions and the following disclaimer in the documentation
81 * and/or other materials provided with the distribution.
82 * 3. Neither the name of STMicroelectronics nor the names of its contributors
83 * may be used to endorse or promote products derived from this software
84 * without specific prior written permission.
86 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
87 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
88 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
89 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
90 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
91 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
92 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
93 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
94 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
95 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
97 ******************************************************************************
100 /* Includes ------------------------------------------------------------------*/
101 #include "stm32f3xx_hal.h"
103 /** @addtogroup STM32F3xx_HAL_Driver
104 * @{
107 #ifdef HAL_FLASH_MODULE_ENABLED
109 /** @defgroup FLASH FLASH
110 * @brief FLASH HAL module driver
111 * @{
114 /* Private typedef -----------------------------------------------------------*/
115 /* Private define ------------------------------------------------------------*/
116 /** @defgroup FLASH_Private_Constants FLASH Private Constants
117 * @{
120 * @}
123 /* Private macro ---------------------------- ---------------------------------*/
124 /** @defgroup FLASH_Private_Macros FLASH Private Macros
125 * @{
129 * @}
132 /* Private variables ---------------------------------------------------------*/
133 /** @defgroup FLASH_Private_Variables FLASH Private Variables
134 * @{
136 /* Variables used for Erase pages under interruption*/
137 FLASH_ProcessTypeDef pFlash;
139 * @}
142 /* Private function prototypes -----------------------------------------------*/
143 /** @defgroup FLASH_Private_Functions FLASH Private Functions
144 * @{
146 static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data);
147 static void FLASH_SetErrorCode(void);
148 extern void FLASH_PageErase(uint32_t PageAddress);
150 * @}
153 /* Exported functions ---------------------------------------------------------*/
154 /** @defgroup FLASH_Exported_Functions FLASH Exported Functions
155 * @{
158 /** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions
159 * @brief Programming operation functions
161 @verbatim
162 @endverbatim
163 * @{
167 * @brief Program halfword, word or double word at a specified address
168 * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
169 * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
171 * @note If an erase and a program operations are requested simultaneously,
172 * the erase operation is performed before the program one.
174 * @note FLASH should be previously erased before new programmation (only exception to this
175 * is when 0x0000 is programmed)
177 * @param TypeProgram Indicate the way to program at a specified address.
178 * This parameter can be a value of @ref FLASH_Type_Program
179 * @param Address Specifie the address to be programmed.
180 * @param Data Specifie the data to be programmed
182 * @retval HAL_StatusTypeDef HAL Status
184 HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
186 HAL_StatusTypeDef status = HAL_ERROR;
187 uint8_t index = 0U;
188 uint8_t nbiterations = 0U;
190 /* Process Locked */
191 __HAL_LOCK(&pFlash);
193 /* Check the parameters */
194 assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
195 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
197 /* Wait for last operation to be completed */
198 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
200 if(status == HAL_OK)
202 if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD)
204 /* Program halfword (16-bit) at a specified address. */
205 nbiterations = 1U;
207 else if(TypeProgram == FLASH_TYPEPROGRAM_WORD)
209 /* Program word (32-bit = 2*16-bit) at a specified address. */
210 nbiterations = 2U;
212 else
214 /* Program double word (64-bit = 4*16-bit) at a specified address. */
215 nbiterations = 4U;
218 for (index = 0U; index < nbiterations; index++)
220 FLASH_Program_HalfWord((Address + (2U*index)), (uint16_t)(Data >> (16U*index)));
222 /* Wait for last operation to be completed */
223 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
225 /* If the program operation is completed, disable the PG Bit */
226 CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
227 /* In case of error, stop programation procedure */
228 if (status != HAL_OK)
230 break;
235 /* Process Unlocked */
236 __HAL_UNLOCK(&pFlash);
238 return status;
242 * @brief Program halfword, word or double word at a specified address with interrupt enabled.
243 * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
244 * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
246 * @note If an erase and a program operations are requested simultaneously,
247 * the erase operation is performed before the program one.
249 * @param TypeProgram Indicate the way to program at a specified address.
250 * This parameter can be a value of @ref FLASH_Type_Program
251 * @param Address Specifie the address to be programmed.
252 * @param Data Specifie the data to be programmed
254 * @retval HAL_StatusTypeDef HAL Status
256 HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
258 HAL_StatusTypeDef status = HAL_OK;
260 /* Process Locked */
261 __HAL_LOCK(&pFlash);
263 /* Check the parameters */
264 assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
265 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
267 /* Enable End of FLASH Operation and Error source interrupts */
268 __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP | FLASH_IT_ERR);
270 pFlash.Address = Address;
271 pFlash.Data = Data;
273 if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD)
275 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMHALFWORD;
276 /* Program halfword (16-bit) at a specified address. */
277 pFlash.DataRemaining = 1U;
279 else if(TypeProgram == FLASH_TYPEPROGRAM_WORD)
281 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMWORD;
282 /* Program word (32-bit : 2*16-bit) at a specified address. */
283 pFlash.DataRemaining = 2U;
285 else
287 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMDOUBLEWORD;
288 /* Program double word (64-bit : 4*16-bit) at a specified address. */
289 pFlash.DataRemaining = 4U;
292 /* Program halfword (16-bit) at a specified address. */
293 FLASH_Program_HalfWord(Address, (uint16_t)Data);
295 return status;
299 * @brief This function handles FLASH interrupt request.
300 * @retval None
302 void HAL_FLASH_IRQHandler(void)
304 uint32_t addresstmp = 0U;
306 /* Check FLASH operation error flags */
307 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
309 /* Return the faulty address */
310 addresstmp = pFlash.Address;
311 /* Reset address */
312 pFlash.Address = 0xFFFFFFFFU;
314 /* Save the Error code */
315 FLASH_SetErrorCode();
317 /* FLASH error interrupt user callback */
318 HAL_FLASH_OperationErrorCallback(addresstmp);
320 /* Stop the procedure ongoing */
321 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
324 /* Check FLASH End of Operation flag */
325 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP))
327 /* Clear FLASH End of Operation pending bit */
328 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
330 /* Process can continue only if no error detected */
331 if(pFlash.ProcedureOnGoing != FLASH_PROC_NONE)
333 if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE)
335 /* Nb of pages to erased can be decreased */
336 pFlash.DataRemaining--;
338 /* Check if there are still pages to erase */
339 if(pFlash.DataRemaining != 0U)
341 addresstmp = pFlash.Address;
342 /*Indicate user which sector has been erased */
343 HAL_FLASH_EndOfOperationCallback(addresstmp);
345 /*Increment sector number*/
346 addresstmp = pFlash.Address + FLASH_PAGE_SIZE;
347 pFlash.Address = addresstmp;
349 /* If the erase operation is completed, disable the PER Bit */
350 CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
352 FLASH_PageErase(addresstmp);
354 else
356 /* No more pages to Erase, user callback can be called. */
357 /* Reset Sector and stop Erase pages procedure */
358 pFlash.Address = addresstmp = 0xFFFFFFFFU;
359 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
360 /* FLASH EOP interrupt user callback */
361 HAL_FLASH_EndOfOperationCallback(addresstmp);
364 else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
366 /* Operation is completed, disable the MER Bit */
367 CLEAR_BIT(FLASH->CR, FLASH_CR_MER);
369 /* MassErase ended. Return the selected bank */
370 /* FLASH EOP interrupt user callback */
371 HAL_FLASH_EndOfOperationCallback(0U);
373 /* Stop Mass Erase procedure*/
374 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
376 else
378 /* Nb of 16-bit data to program can be decreased */
379 pFlash.DataRemaining--;
381 /* Check if there are still 16-bit data to program */
382 if(pFlash.DataRemaining != 0U)
384 /* Increment address to 16-bit */
385 pFlash.Address += 2U;
386 addresstmp = pFlash.Address;
388 /* Shift to have next 16-bit data */
389 pFlash.Data = (pFlash.Data >> 16U);
391 /* Operation is completed, disable the PG Bit */
392 CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
394 /*Program halfword (16-bit) at a specified address.*/
395 FLASH_Program_HalfWord(addresstmp, (uint16_t)pFlash.Data);
397 else
399 /* Program ended. Return the selected address */
400 /* FLASH EOP interrupt user callback */
401 if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD)
403 HAL_FLASH_EndOfOperationCallback(pFlash.Address);
405 else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD)
407 HAL_FLASH_EndOfOperationCallback(pFlash.Address - 2U);
409 else
411 HAL_FLASH_EndOfOperationCallback(pFlash.Address - 6U);
414 /* Reset Address and stop Program procedure */
415 pFlash.Address = 0xFFFFFFFFU;
416 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
423 if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE)
425 /* Operation is completed, disable the PG, PER and MER Bits */
426 CLEAR_BIT(FLASH->CR, (FLASH_CR_PG | FLASH_CR_PER | FLASH_CR_MER));
428 /* Disable End of FLASH Operation and Error source interrupts */
429 __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP | FLASH_IT_ERR);
431 /* Process Unlocked */
432 __HAL_UNLOCK(&pFlash);
437 * @brief FLASH end of operation interrupt callback
438 * @param ReturnValue The value saved in this parameter depends on the ongoing procedure
439 * - Mass Erase: No return value expected
440 * - Pages Erase: Address of the page which has been erased
441 * (if 0xFFFFFFFF, it means that all the selected pages have been erased)
442 * - Program: Address which was selected for data program
443 * @retval none
445 __weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
447 /* Prevent unused argument(s) compilation warning */
448 UNUSED(ReturnValue);
450 /* NOTE : This function Should not be modified, when the callback is needed,
451 the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
456 * @brief FLASH operation error interrupt callback
457 * @param ReturnValue The value saved in this parameter depends on the ongoing procedure
458 * - Mass Erase: No return value expected
459 * - Pages Erase: Address of the page which returned an error
460 * - Program: Address which was selected for data program
461 * @retval none
463 __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
465 /* Prevent unused argument(s) compilation warning */
466 UNUSED(ReturnValue);
468 /* NOTE : This function Should not be modified, when the callback is needed,
469 the HAL_FLASH_OperationErrorCallback could be implemented in the user file
474 * @}
477 /** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions
478 * @brief management functions
480 @verbatim
481 ===============================================================================
482 ##### Peripheral Control functions #####
483 ===============================================================================
484 [..]
485 This subsection provides a set of functions allowing to control the FLASH
486 memory operations.
488 @endverbatim
489 * @{
493 * @brief Unlock the FLASH control register access
494 * @retval HAL Status
496 HAL_StatusTypeDef HAL_FLASH_Unlock(void)
498 if (HAL_IS_BIT_SET(FLASH->CR, FLASH_CR_LOCK))
500 /* Authorize the FLASH Registers access */
501 WRITE_REG(FLASH->KEYR, FLASH_KEY1);
502 WRITE_REG(FLASH->KEYR, FLASH_KEY2);
504 else
506 return HAL_ERROR;
509 return HAL_OK;
513 * @brief Locks the FLASH control register access
514 * @retval HAL Status
516 HAL_StatusTypeDef HAL_FLASH_Lock(void)
518 /* Set the LOCK Bit to lock the FLASH Registers access */
519 SET_BIT(FLASH->CR, FLASH_CR_LOCK);
521 return HAL_OK;
525 * @brief Unlock the FLASH Option Control Registers access.
526 * @retval HAL Status
528 HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void)
530 if (HAL_IS_BIT_CLR(FLASH->CR, FLASH_CR_OPTWRE))
532 /* Authorizes the Option Byte register programming */
533 WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1);
534 WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2);
536 else
538 return HAL_ERROR;
541 return HAL_OK;
545 * @brief Lock the FLASH Option Control Registers access.
546 * @retval HAL Status
548 HAL_StatusTypeDef HAL_FLASH_OB_Lock(void)
550 /* Clear the OPTWRE Bit to lock the FLASH Option Byte Registers access */
551 CLEAR_BIT(FLASH->CR, FLASH_CR_OPTWRE);
553 return HAL_OK;
557 * @brief Launch the option byte loading.
558 * @note This function will reset automatically the MCU.
559 * @retval HAL Status
561 HAL_StatusTypeDef HAL_FLASH_OB_Launch(void)
563 /* Set the OBL_Launch bit to launch the option byte loading */
564 SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH);
566 /* Wait for last operation to be completed */
567 return(FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE));
571 * @}
574 /** @defgroup FLASH_Exported_Functions_Group3 Peripheral errors functions
575 * @brief Peripheral errors functions
577 @verbatim
578 ===============================================================================
579 ##### Peripheral Errors functions #####
580 ===============================================================================
581 [..]
582 This subsection permit to get in run-time errors of the FLASH peripheral.
584 @endverbatim
585 * @{
589 * @brief Get the specific FLASH error flag.
590 * @retval FLASH_ErrorCode The returned value can be:
591 * @ref FLASH_Error_Codes
593 uint32_t HAL_FLASH_GetError(void)
595 return pFlash.ErrorCode;
599 * @}
603 * @}
606 /** @addtogroup FLASH_Private_Functions
607 * @{
611 * @brief Program a half-word (16-bit) at a specified address.
612 * @param Address specify the address to be programmed.
613 * @param Data specify the data to be programmed.
614 * @retval None
616 static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data)
618 /* Clean the error context */
619 pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
621 /* Proceed to program the new data */
622 SET_BIT(FLASH->CR, FLASH_CR_PG);
624 /* Write data in the address */
625 *(__IO uint16_t*)Address = Data;
629 * @brief Wait for a FLASH operation to complete.
630 * @param Timeout maximum flash operation timeout
631 * @retval HAL Status
633 HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
635 /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
636 Even if the FLASH operation fails, the BUSY flag will be reset and an error
637 flag will be set */
639 uint32_t tickstart = HAL_GetTick();
641 while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY))
643 if (Timeout != HAL_MAX_DELAY)
645 if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout))
647 return HAL_TIMEOUT;
652 /* Check FLASH End of Operation flag */
653 if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP))
655 /* Clear FLASH End of Operation pending bit */
656 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
659 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||
660 __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
662 /*Save the error code*/
663 FLASH_SetErrorCode();
664 return HAL_ERROR;
667 /* There is no error flag set */
668 return HAL_OK;
673 * @brief Set the specific FLASH error flag.
674 * @retval None
676 static void FLASH_SetErrorCode(void)
678 uint32_t flags = 0U;
680 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR))
682 pFlash.ErrorCode |= HAL_FLASH_ERROR_WRP;
683 flags |= FLASH_FLAG_WRPERR;
685 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
687 pFlash.ErrorCode |= HAL_FLASH_ERROR_PROG;
688 flags |= FLASH_FLAG_PGERR;
690 /* Clear FLASH error pending bits */
691 __HAL_FLASH_CLEAR_FLAG(flags);
694 * @}
698 * @}
701 #endif /* HAL_FLASH_MODULE_ENABLED */
704 * @}
707 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/