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
11 *
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.
19
20 [..] The Flash memory interface accelerates code execution with a system of instruction
21 prefetch.
22
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
29
30
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.
36
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.
53
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
59
60 [..] In addition to these function, this driver includes a set of macros allowing
61 to handle the following operations:
62
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
68
69 @endverbatim
70 ******************************************************************************
71 * @attention
72 *
73 * Copyright (c) 2016 STMicroelectronics.
74 * All rights reserved.
75 *
76 * This software is licensed under terms that can be found in the LICENSE file in
77 * the root directory of this software component.
78 * If no LICENSE file comes with this software, it is provided AS-IS.
79 ******************************************************************************
80 */
81
82 /* Includes ------------------------------------------------------------------*/
83 #include "stm32f3xx_hal.h"
84
85 /** @addtogroup STM32F3xx_HAL_Driver
86 * @{
87 */
88
89 #ifdef HAL_FLASH_MODULE_ENABLED
90
91 /** @defgroup FLASH FLASH
92 * @brief FLASH HAL module driver
93 * @{
94 */
95
96 /* Private typedef -----------------------------------------------------------*/
97 /* Private define ------------------------------------------------------------*/
98 /** @defgroup FLASH_Private_Constants FLASH Private Constants
99 * @{
100 */
101 /**
102 * @}
103 */
104
105 /* Private macro ---------------------------- ---------------------------------*/
106 /** @defgroup FLASH_Private_Macros FLASH Private Macros
107 * @{
108 */
109
110 /**
111 * @}
112 */
113
114 /* Private variables ---------------------------------------------------------*/
115 /** @defgroup FLASH_Private_Variables FLASH Private Variables
116 * @{
117 */
118 /* Variables used for Erase pages under interruption*/
119 FLASH_ProcessTypeDef pFlash;
120 /**
121 * @}
122 */
123
124 /* Private function prototypes -----------------------------------------------*/
125 /** @defgroup FLASH_Private_Functions FLASH Private Functions
126 * @{
127 */
128 static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data);
129 static void FLASH_SetErrorCode(void);
130 extern void FLASH_PageErase(uint32_t PageAddress);
131 /**
132 * @}
133 */
134
135 /* Exported functions ---------------------------------------------------------*/
136 /** @defgroup FLASH_Exported_Functions FLASH Exported Functions
137 * @{
138 */
139
140 /** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions
141 * @brief Programming operation functions
142 *
143 @verbatim
144 @endverbatim
145 * @{
146 */
147
148 /**
149 * @brief Program halfword, word or double word at a specified address
150 * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
151 * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
152 *
153 * @note If an erase and a program operations are requested simultaneously,
154 * the erase operation is performed before the program one.
155 *
156 * @note FLASH should be previously erased before new programming (only exception to this
157 * is when 0x0000 is programmed)
158 *
159 * @param TypeProgram Indicate the way to program at a specified address.
160 * This parameter can be a value of @ref FLASH_Type_Program
161 * @param Address Specifie the address to be programmed.
162 * @param Data Specifie the data to be programmed
163 *
164 * @retval HAL_StatusTypeDef HAL Status
165 */
HAL_FLASH_Program(uint32_t TypeProgram,uint32_t Address,uint64_t Data)166 HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
167 {
168 HAL_StatusTypeDef status = HAL_ERROR;
169 uint8_t index = 0U;
170 uint8_t nbiterations = 0U;
171
172 /* Process Locked */
173 __HAL_LOCK(&pFlash);
174
175 /* Check the parameters */
176 assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
177 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
178
179 /* Wait for last operation to be completed */
180 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
181
182 if(status == HAL_OK)
183 {
184 if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD)
185 {
186 /* Program halfword (16-bit) at a specified address. */
187 nbiterations = 1U;
188 }
189 else if(TypeProgram == FLASH_TYPEPROGRAM_WORD)
190 {
191 /* Program word (32-bit = 2*16-bit) at a specified address. */
192 nbiterations = 2U;
193 }
194 else
195 {
196 /* Program double word (64-bit = 4*16-bit) at a specified address. */
197 nbiterations = 4U;
198 }
199
200 for (index = 0U; index < nbiterations; index++)
201 {
202 FLASH_Program_HalfWord((Address + (2U*index)), (uint16_t)(Data >> (16U*index)));
203
204 /* Wait for last operation to be completed */
205 status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
206
207 /* If the program operation is completed, disable the PG Bit */
208 CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
209 /* In case of error, stop programming procedure */
210 if (status != HAL_OK)
211 {
212 break;
213 }
214 }
215 }
216
217 /* Process Unlocked */
218 __HAL_UNLOCK(&pFlash);
219
220 return status;
221 }
222
223 /**
224 * @brief Program halfword, word or double word at a specified address with interrupt enabled.
225 * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
226 * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
227 *
228 * @note If an erase and a program operations are requested simultaneously,
229 * the erase operation is performed before the program one.
230 *
231 * @param TypeProgram Indicate the way to program at a specified address.
232 * This parameter can be a value of @ref FLASH_Type_Program
233 * @param Address Specifie the address to be programmed.
234 * @param Data Specifie the data to be programmed
235 *
236 * @retval HAL_StatusTypeDef HAL Status
237 */
HAL_FLASH_Program_IT(uint32_t TypeProgram,uint32_t Address,uint64_t Data)238 HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
239 {
240 HAL_StatusTypeDef status = HAL_OK;
241
242 /* Process Locked */
243 __HAL_LOCK(&pFlash);
244
245 /* Check the parameters */
246 assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
247 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
248
249 /* Enable End of FLASH Operation and Error source interrupts */
250 __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP | FLASH_IT_ERR);
251
252 pFlash.Address = Address;
253 pFlash.Data = Data;
254
255 if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD)
256 {
257 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMHALFWORD;
258 /* Program halfword (16-bit) at a specified address. */
259 pFlash.DataRemaining = 1U;
260 }
261 else if(TypeProgram == FLASH_TYPEPROGRAM_WORD)
262 {
263 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMWORD;
264 /* Program word (32-bit : 2*16-bit) at a specified address. */
265 pFlash.DataRemaining = 2U;
266 }
267 else
268 {
269 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMDOUBLEWORD;
270 /* Program double word (64-bit : 4*16-bit) at a specified address. */
271 pFlash.DataRemaining = 4U;
272 }
273
274 /* Program halfword (16-bit) at a specified address. */
275 FLASH_Program_HalfWord(Address, (uint16_t)Data);
276
277 return status;
278 }
279
280 /**
281 * @brief This function handles FLASH interrupt request.
282 * @retval None
283 */
HAL_FLASH_IRQHandler(void)284 void HAL_FLASH_IRQHandler(void)
285 {
286 uint32_t addresstmp = 0U;
287
288 /* Check FLASH operation error flags */
289 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
290 {
291 /* Return the faulty address */
292 addresstmp = pFlash.Address;
293 /* Reset address */
294 pFlash.Address = 0xFFFFFFFFU;
295
296 /* Save the Error code */
297 FLASH_SetErrorCode();
298
299 /* FLASH error interrupt user callback */
300 HAL_FLASH_OperationErrorCallback(addresstmp);
301
302 /* Stop the procedure ongoing */
303 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
304 }
305
306 /* Check FLASH End of Operation flag */
307 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP))
308 {
309 /* Clear FLASH End of Operation pending bit */
310 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
311
312 /* Process can continue only if no error detected */
313 if(pFlash.ProcedureOnGoing != FLASH_PROC_NONE)
314 {
315 if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE)
316 {
317 /* Nb of pages to erased can be decreased */
318 pFlash.DataRemaining--;
319
320 /* Check if there are still pages to erase */
321 if(pFlash.DataRemaining != 0U)
322 {
323 addresstmp = pFlash.Address;
324 /*Indicate user which sector has been erased */
325 HAL_FLASH_EndOfOperationCallback(addresstmp);
326
327 /*Increment sector number*/
328 addresstmp = pFlash.Address + FLASH_PAGE_SIZE;
329 pFlash.Address = addresstmp;
330
331 /* If the erase operation is completed, disable the PER Bit */
332 CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
333
334 FLASH_PageErase(addresstmp);
335 }
336 else
337 {
338 /* No more pages to Erase, user callback can be called. */
339 /* Reset Sector and stop Erase pages procedure */
340 pFlash.Address = addresstmp = 0xFFFFFFFFU;
341 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
342 /* FLASH EOP interrupt user callback */
343 HAL_FLASH_EndOfOperationCallback(addresstmp);
344 }
345 }
346 else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
347 {
348 /* Operation is completed, disable the MER Bit */
349 CLEAR_BIT(FLASH->CR, FLASH_CR_MER);
350
351 /* MassErase ended. Return the selected bank */
352 /* FLASH EOP interrupt user callback */
353 HAL_FLASH_EndOfOperationCallback(0U);
354
355 /* Stop Mass Erase procedure*/
356 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
357 }
358 else
359 {
360 /* Nb of 16-bit data to program can be decreased */
361 pFlash.DataRemaining--;
362
363 /* Check if there are still 16-bit data to program */
364 if(pFlash.DataRemaining != 0U)
365 {
366 /* Increment address to 16-bit */
367 pFlash.Address += 2U;
368 addresstmp = pFlash.Address;
369
370 /* Shift to have next 16-bit data */
371 pFlash.Data = (pFlash.Data >> 16U);
372
373 /* Operation is completed, disable the PG Bit */
374 CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
375
376 /*Program halfword (16-bit) at a specified address.*/
377 FLASH_Program_HalfWord(addresstmp, (uint16_t)pFlash.Data);
378 }
379 else
380 {
381 /* Program ended. Return the selected address */
382 /* FLASH EOP interrupt user callback */
383 if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD)
384 {
385 HAL_FLASH_EndOfOperationCallback(pFlash.Address);
386 }
387 else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD)
388 {
389 HAL_FLASH_EndOfOperationCallback(pFlash.Address - 2U);
390 }
391 else
392 {
393 HAL_FLASH_EndOfOperationCallback(pFlash.Address - 6U);
394 }
395
396 /* Reset Address and stop Program procedure */
397 pFlash.Address = 0xFFFFFFFFU;
398 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
399 }
400 }
401 }
402 }
403
404
405 if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE)
406 {
407 /* Operation is completed, disable the PG, PER and MER Bits */
408 CLEAR_BIT(FLASH->CR, (FLASH_CR_PG | FLASH_CR_PER | FLASH_CR_MER));
409
410 /* Disable End of FLASH Operation and Error source interrupts */
411 __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP | FLASH_IT_ERR);
412
413 /* Process Unlocked */
414 __HAL_UNLOCK(&pFlash);
415 }
416 }
417
418 /**
419 * @brief FLASH end of operation interrupt callback
420 * @param ReturnValue The value saved in this parameter depends on the ongoing procedure
421 * - Mass Erase: No return value expected
422 * - Pages Erase: Address of the page which has been erased
423 * (if 0xFFFFFFFF, it means that all the selected pages have been erased)
424 * - Program: Address which was selected for data program
425 * @retval none
426 */
HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)427 __weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
428 {
429 /* Prevent unused argument(s) compilation warning */
430 UNUSED(ReturnValue);
431
432 /* NOTE : This function Should not be modified, when the callback is needed,
433 the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
434 */
435 }
436
437 /**
438 * @brief FLASH operation error interrupt callback
439 * @param ReturnValue The value saved in this parameter depends on the ongoing procedure
440 * - Mass Erase: No return value expected
441 * - Pages Erase: Address of the page which returned an error
442 * - Program: Address which was selected for data program
443 * @retval none
444 */
HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)445 __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
446 {
447 /* Prevent unused argument(s) compilation warning */
448 UNUSED(ReturnValue);
449
450 /* NOTE : This function Should not be modified, when the callback is needed,
451 the HAL_FLASH_OperationErrorCallback could be implemented in the user file
452 */
453 }
454
455 /**
456 * @}
457 */
458
459 /** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions
460 * @brief management functions
461 *
462 @verbatim
463 ===============================================================================
464 ##### Peripheral Control functions #####
465 ===============================================================================
466 [..]
467 This subsection provides a set of functions allowing to control the FLASH
468 memory operations.
469
470 @endverbatim
471 * @{
472 */
473
474 /**
475 * @brief Unlock the FLASH control register access
476 * @retval HAL Status
477 */
HAL_FLASH_Unlock(void)478 HAL_StatusTypeDef HAL_FLASH_Unlock(void)
479 {
480 HAL_StatusTypeDef status = HAL_OK;
481
482 if(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET)
483 {
484 /* Authorize the FLASH Registers access */
485 WRITE_REG(FLASH->KEYR, FLASH_KEY1);
486 WRITE_REG(FLASH->KEYR, FLASH_KEY2);
487
488 /* Verify Flash is unlocked */
489 if(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET)
490 {
491 status = HAL_ERROR;
492 }
493 }
494
495 return status;
496 }
497
498 /**
499 * @brief Locks the FLASH control register access
500 * @retval HAL Status
501 */
HAL_FLASH_Lock(void)502 HAL_StatusTypeDef HAL_FLASH_Lock(void)
503 {
504 /* Set the LOCK Bit to lock the FLASH Registers access */
505 SET_BIT(FLASH->CR, FLASH_CR_LOCK);
506
507 return HAL_OK;
508 }
509
510 /**
511 * @brief Unlock the FLASH Option Control Registers access.
512 * @retval HAL Status
513 */
HAL_FLASH_OB_Unlock(void)514 HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void)
515 {
516 if (HAL_IS_BIT_CLR(FLASH->CR, FLASH_CR_OPTWRE))
517 {
518 /* Authorizes the Option Byte register programming */
519 WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1);
520 WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2);
521 }
522 else
523 {
524 return HAL_ERROR;
525 }
526
527 return HAL_OK;
528 }
529
530 /**
531 * @brief Lock the FLASH Option Control Registers access.
532 * @retval HAL Status
533 */
HAL_FLASH_OB_Lock(void)534 HAL_StatusTypeDef HAL_FLASH_OB_Lock(void)
535 {
536 /* Clear the OPTWRE Bit to lock the FLASH Option Byte Registers access */
537 CLEAR_BIT(FLASH->CR, FLASH_CR_OPTWRE);
538
539 return HAL_OK;
540 }
541
542 /**
543 * @brief Launch the option byte loading.
544 * @note This function will reset automatically the MCU.
545 * @retval HAL Status
546 */
HAL_FLASH_OB_Launch(void)547 HAL_StatusTypeDef HAL_FLASH_OB_Launch(void)
548 {
549 /* Set the OBL_Launch bit to launch the option byte loading */
550 SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH);
551
552 /* Wait for last operation to be completed */
553 return(FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE));
554 }
555
556 /**
557 * @}
558 */
559
560 /** @defgroup FLASH_Exported_Functions_Group3 Peripheral errors functions
561 * @brief Peripheral errors functions
562 *
563 @verbatim
564 ===============================================================================
565 ##### Peripheral Errors functions #####
566 ===============================================================================
567 [..]
568 This subsection permit to get in run-time errors of the FLASH peripheral.
569
570 @endverbatim
571 * @{
572 */
573
574 /**
575 * @brief Get the specific FLASH error flag.
576 * @retval FLASH_ErrorCode The returned value can be:
577 * @ref FLASH_Error_Codes
578 */
HAL_FLASH_GetError(void)579 uint32_t HAL_FLASH_GetError(void)
580 {
581 return pFlash.ErrorCode;
582 }
583
584 /**
585 * @}
586 */
587
588 /**
589 * @}
590 */
591
592 /** @addtogroup FLASH_Private_Functions
593 * @{
594 */
595
596 /**
597 * @brief Program a half-word (16-bit) at a specified address.
598 * @param Address specify the address to be programmed.
599 * @param Data specify the data to be programmed.
600 * @retval None
601 */
FLASH_Program_HalfWord(uint32_t Address,uint16_t Data)602 static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data)
603 {
604 /* Clean the error context */
605 pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
606
607 /* Proceed to program the new data */
608 SET_BIT(FLASH->CR, FLASH_CR_PG);
609
610 /* Write data in the address */
611 *(__IO uint16_t*)Address = Data;
612 }
613
614 /**
615 * @brief Wait for a FLASH operation to complete.
616 * @param Timeout maximum flash operation timeout
617 * @retval HAL Status
618 */
FLASH_WaitForLastOperation(uint32_t Timeout)619 HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
620 {
621 /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
622 Even if the FLASH operation fails, the BUSY flag will be reset and an error
623 flag will be set */
624
625 uint32_t tickstart = HAL_GetTick();
626
627 while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY))
628 {
629 if (Timeout != HAL_MAX_DELAY)
630 {
631 if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout))
632 {
633 return HAL_TIMEOUT;
634 }
635 }
636 }
637
638 /* Check FLASH End of Operation flag */
639 if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP))
640 {
641 /* Clear FLASH End of Operation pending bit */
642 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
643 }
644
645 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||
646 __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
647 {
648 /*Save the error code*/
649 FLASH_SetErrorCode();
650 return HAL_ERROR;
651 }
652
653 /* There is no error flag set */
654 return HAL_OK;
655 }
656
657
658 /**
659 * @brief Set the specific FLASH error flag.
660 * @retval None
661 */
FLASH_SetErrorCode(void)662 static void FLASH_SetErrorCode(void)
663 {
664 uint32_t flags = 0U;
665
666 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR))
667 {
668 pFlash.ErrorCode |= HAL_FLASH_ERROR_WRP;
669 flags |= FLASH_FLAG_WRPERR;
670 }
671 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
672 {
673 pFlash.ErrorCode |= HAL_FLASH_ERROR_PROG;
674 flags |= FLASH_FLAG_PGERR;
675 }
676 /* Clear FLASH error pending bits */
677 __HAL_FLASH_CLEAR_FLAG(flags);
678 }
679 /**
680 * @}
681 */
682
683 /**
684 * @}
685 */
686
687 #endif /* HAL_FLASH_MODULE_ENABLED */
688
689 /**
690 * @}
691 */
692
693