/**
  @page IAP_H753ZI_AUTDBG/ STM32H753ZI Secure User Memory and debug protection demonstration 
  
  @verbatim
  ******************** (C) COPYRIGHT 2017 STMicroelectronics *******************
  * @file    IAP_H753ZI_AUTDBG/readme.txt 
  * @brief   Description of implementation of the AN4657 (in-application programming
  *          using the USART (IAP)) on STM32H7xx devices.
  *          + Demonstration of Secure User Memory and debug protection and reopen
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under Ultimate Liberty license
  * SLA0044, the "License"; You may not use this file except in compliance with
  * the License. You may obtain a copy of the License at:
  *                             www.st.com/SLA0044
  *
  ******************************************************************************
  @endverbatim

@par Application Description

 This directory contains a set of sources files and pre-configured projects that 
 describes how to build an In-Application Programming (IAP) that uses an USART
 interface to load an application binary.

 At the beginning of the main program the HAL_Init() function is called to reset 
 all the peripherals, initialize the Flash interface and the systick.
 The SystemClock_Config() function is used to configure the system clock for STM32H753xx Devices :
 The CPU at 400MHz 
 The HCLK for D1 Domain AXI and AHB3 peripherals , D2 Domain AHB1/AHB2 peripherals and D3 Domain AHB4  peripherals at 200MHz.
 The APB clock dividers for D1 Domain APB3 peripherals, D2 Domain APB1 and APB2 peripherals and D3 Domain APB4 peripherals to  run at 100MHz.  

 Application check if Tamper button is pressed, than it open an USART session throught
 USART1 (CN2), present a menu for user to choose next operation. Else will check if
 an application is already loaded at the APPLICATION_ADDRESS and jump to it.

 Table 1. IAP implementation on NUCLEO-H753ZI
 /*** Platform ***|************* Implementation **************************|***** Configuration *****\
 ****************************************************************************************************
 |    Firmware    | The IAP program is located at 0x08000000. The Flash   |                         |
 |                | routines (program/erase) are executed from the Flash  |                         |
 |                | memory.                                               |                         |
 |                | The size of this program is about 16 Kbytes and       |                         |
 |                | programmed on:                                        | Sector 0                |  
 |                | ------------------------------------------------------|-------------------------|
 |                |                                                       | Bank1                   | 
 |                | The user application (image to be downloaded with the | (Sector 1 - Sector 7)   |
 |                | IAP) will be programmed starting from address         | 896 Kbytes              | 
 |                | (uint32_t)0x08020000(1).                              | Bank2                   | 
 |                | The maximum size of the image to be loaded is:        | (Sector 0 - Sector 7)   | 
 |                |                                                       | 1024 Kbytes             | 
 |                | ------------------------------------------------------|-------------------------|
 |                | The image is uploaded with the IAP from the STM32H7xx | 1920 Kbytes             | 
 |                | internal Flash.                                       | 12 KBytes for this case |
 |                | The size of the image to be uploaded up to:           |                         |
 |----------------|-------------------------------------------------------|-------------------------|
 |    Hardware    | Push-button (active level: high)                      | Tamper push-button      |                                                                     
 |                |                                                       | connected to pin PC13   |
 |                | ------------------------------------------------------|-------------------------| 
 |                | USART used                                            |  USART1   (CN2)         |
 \**************************************************************************************************/
 (1) User application location address is defined in the flash_if.h file as: 
 #define APPLICATION_ADDRESS           ((uint32_t)0x08020000)
 To modify it, change the default value to the desired one. Note that the application must be linked
 relatively to the new address too.
 
 Following picture illustrates the situation in program memory:
 Figure 2. Flash memory usage

 Top Flash Memory address /-------------------------------------------\  0x081FFFFF
                          |                                           |
                          |                                           |
                          |                                           |
                          |          Sector 0 - Sector 7 (Bank 2)     |
                          |                                           |
                          |                                           |
                          |                                           |
                          |                                           |
                          |                                           |
                          |          Sector 1 - Sector 7 (Bank 1)     |
                          |                                           |
                          |                                           |
                          |          User code                        |
                          |                                           |
                          |- - - - - - - - - - - - - - - - - - - - - -|
                          |          Vector table                     |
                          |-------------------------------------------|  0x08020000
                          |          IAP code                         |
                          |- - - - - - - - - - - - - - - - - - - - - -|
                          |          Vector table                     |
                          \-------------------------------------------/	 0x08000000					  

   
 
@note Care must be taken when using HAL_Delay(), this function provides accurate delay (in milliseconds)
      based on variable incremented in SysTick ISR. This implies that if HAL_Delay() is called from
      a peripheral ISR process, then the SysTick interrupt must have higher priority (numerically lower)
      than the peripheral interrupt. Otherwise the caller ISR process will be blocked.
      To change the SysTick interrupt priority you have to use HAL_NVIC_SetPriority() function.
      
@note The application needs to ensure that the SysTick time base is always set to 1 millisecond
      to have correct HAL operation.

@Note If the  application is using the DTCM/ITCM memories (@0x20000000/ 0x0000000: not cacheable and only accessible
      by the Cortex M7 and the MDMA), no need for cache maintenance when the Cortex M7 and the MDMA access these RAMs.
 If the application needs to use DMA(or other masters) based access or requires more RAM, then the user has to:
  - Use a non TCM SRAM. (example : D1 AXI-SRAM @ 0x24000000)
  - Add a cache maintenance mechanism to ensure the cache coherence between CPU and other masters(DMAs,DMA2D,LTDC,MDMA).
       - The addresses and the size of cacheable buffers (shared between CPU and other masters)
                must be	properlydefined to be aligned to L1-CACHE line size (32 bytes). 

@Note It is recommended to enable the cache and maintain its coherence.
      Depending on the use case it is also possible to configure the cache attributes using the MPU.
Please refer to the AN4838 "Managing memory protection unit (MPU) in STM32 MCUs"
Please refer to the AN4839 "Level 1 cache on STM32F7 Series"

@par Directory contents

 - IAP_H753ZI_AUTDBG/Inc/main.h                Main configuration file
 - IAP_H753ZI_AUTDBG/Inc/common.h              Common function header file
 - IAP_H753ZI_AUTDBG/Inc/flash_if.h            Flash Interface header file
 - IAP_H753ZI_AUTDBG/Inc/menu.h                Menu header file
 - IAP_H753ZI_AUTDBG/Inc/ymodem.h              Ymodem communication header file
 - IAP_H753ZI_AUTDBG/Inc/crypto.h              Crypto functions for ECDSA signature verification
 - IAP_H753ZI_AUTDBG/Inc/ecc_pub_key.h         ECC public key header file
 - IAP_H753ZI_AUTDBG/Inc/stm32h7xx_hal_conf.h  HAL Configuration file 
 - IAP_H753ZI_AUTDBG/Inc/stm32h7xx_it.h        Interrupt handlers header file
 - IAP_H753ZI_AUTDBG/Src/main.c                Main program
 - IAP_H753ZI_AUTDBG/Src/stm32h7xx_it.c        Interrupt handlers
 - IAP_H753ZI_AUTDBG/Src/flash_if.c            Flash Interface source file
 - IAP_H753ZI_AUTDBG/Src/menu.c                Menu source file
 - IAP_H753ZI_AUTDBG/Src/crypto.c              Crypto functions for ECDSA signature verification
 - IAP_H753ZI_AUTDBG/Src/common.c              Common function source file
 - IAP_H753ZI_AUTDBG/Src/ymodem.c              Ymodem communication source file
 - IAP_H753ZI_AUTDBG/Src/system_stm32h7xx.c    STM32H7xx system source file

@par Hardware and Software environment

  - This application runs on STM32H753ZI Nucleo board.
  - This application has been tested with STMicroelectronics NUCLEO-H753ZI evaluation board
    and can be easily tailored to any other supported device and development board.

@par Hardware and Software environment

  - This application runs on STM32H753xx device.

  - This application has been tested with NUCLEO-H753ZI board and can be
    easily tailored to any other supported device and development board.

  - NUCLEO-H753ZI Set-up
    - Connect a null-modem female/female RS232 cable between the boards DB9 connector 
      and PC serial port.
    - Hold the Tamper push-button during reset to enter the IAP.    

  - Terminal configuration: 
    - Word Length = 8 Bits
    - One Stop Bit
    - No parity
    - BaudRate = 115200 baud
    - flow control: None 
    - Ymodem protocol is using CRC16 by default. To switch to checksum, comment #define CRC16_F
      in ymodem.c
 
@par How to use it? 

In order to demonstrate debug protection and reopen with authentication, you must do the following:
  
  1. Generate the binary image of the project provided in IAP_H753ZI_AUTDBG/ directory
  2. Generate the binary image of the project provided in APP_GPIO_EXTI/ directory 
	 (or another application with the same flash start address @0x08020000)
  3. Flash both binary to the board. Open Teraterm to get the UART print from board
	 You should see some print message as follows:
	  Bootloader COM Init done.
		 ***** BL (Build (GCC): Jun 30 2020 17:21:48) *****
		  Launching application ...

		 Application COM Init done.
		 ============ App (Build (GCC): Jun 30 2020 16:20:37)============

		 CHIP UID: 38 00 26 00 10 51 38 34 32 32 35 36

		 Press user button to toggle LED1 (GREEN LED)
	
	At this moment debug connection from CubeProgrammer should be OK (with different connecting mode)
 
  4. Activate security bit and secure user mem protection in OB. 
	 This can be done with the test menu included in the IAP bootloader.
	 Test menu can be activated with user button pressed during reset. A menu like this will show up
	 
	=================== Main Menu =================
	  Download image to the internal Flash ------ 1
	  Upload image from the internal Flash ------ 2
	  Execute the loaded application ------------ a
	  Execute application and hide bootloader --- b
	  Open debug under authentication ----------- D

	  Enable the write protection --------------- [4]

	  Check secure memory protection ------------ <5>
	  Set security bit               ------------ [6]
	  Reset security bit             ------------ [7]
	  Set secure memory              ------------ [8]
	  Clear secure memory            ------------ [9]
	  Set RDPL1                      ------------ [r]
	  Erase all/Regression           ------------ [e]
	===============================================
	Press 5 to check the current security settings from OB
	Press 6 to enable security bit
	Press 8 to enable secure user memory
	
	Now try to connect to the board with CubeProgrammer, you should find that the connection is not possible anymore
	
  5. Check debug reenable directly through menu
    Test 1: 
	Activate the test menu again and choose a -> Debug connection still not OK
	Test 2: 
	Activate the test menu again and choose b -> Debug connection with hotplug mode is possible 
	(but flash content from 0x08000000 to 0x08020000 are all RAZ)

  6. Check debug re-open with authentication 
    Activate the test menu again and choose D
	A set of challenge data will show up. e.g.
		
		 d5  cd  c2  cc  b0  30  df  81  90  be  fd  0b  e6  9b  e2  10
		 00  3c  cf  88  d3  52  70  ce  df  c4  96  85  ea  79  9d  cc
		 37  af  5d  2d  3b  00  23  f1  e9  5c  71  5a  d8  bf  b0  99
		 7e  0c  c6  cb  c0  22  b4  23  60  ac  c4  4c  b6  67  77  c3
		 5b  cc  c3  88  db  39  1b  9d  f0  ad  85  69  21  9b  23  33
		 0b  9a  a5  22  8d  0b  fd  c1  61  5a  f0  0c  74  4d  14  2f
		 47  c3  47  c2  ae  cb  5d  89  35  c8  19  95  9d  80  ed  d4
		 f1  93  25  77  a3  61  1f  2b  43  72  17  8f  0d  08  ea  a1
		 cf  e1  d1  9f  1c  46  46  b2  a7  77  e9  70  82  55  c9  10
		 99  1e  cb  c1  99  cc  d1  f9  d6  2e  0c  1d  f3  70  26  65
		 ea  c1  bc  a2  94  a2  f5  4c  2c  49  c2  fc  3b  76  22  96
		 96  a5  e1  46  b1  3f  a9  da  09  9d  97  ba  cd  f9  5d  99
		 42  d8  0a  d6  65  38  a2  17  43  73  66  66  e9  cc  98  3c
		 1b  e1  71  88  73  83  b2  3d  b5  2f  d7  03  0e  8d  d9  fa
		 d2  b7  91  d8  b0  ac  2d  7a  66  7d  0f  d1  47  ca  76  4d
		 e1  7b  5a  fe  3e  48  be  cf  b4  df  29  18  a2  79  fb  12

	Now copy the data to a text file (e.g. named challenge.txt). 
	Open a window cmd window and go to folder Utils/
	Run the script to get valid response data file with command:
		sign_message_txt.bat challenge.txt ecc.key

	A signature file will be generated if the script runs successfully: 
		message_ecdsa.sig
		
	Get back to the Teraterm window 
		type c -> to continue to send the response file
		Send the response binary file through menu option
			File->send file 
		Make sure that "Binary" option check box is checked.
	
	Then on the Teraterm you will see the validation log like this:
		 Response Data Received Successfully!
		-------------------

		 Response Data

		==============================================================
		 b1  3d  18  8a  2c  4c  a1  67  1d  27  2f  21  af  41  95  10
		 19  b7  72  7f  fc  fd  31  cf  7c  64  9e  f5  2e  1a  b0  96
		 f9  30  9b  ba  c0  be  08  a8  3d  e0  fe  e3  5c  68  e8  d3
		 9d  29  f4  0d  41  b2  a8  3f  19  87  bd  31  32  bd  ca  dd

		==============================================================

		 Compute SHA256 HASH:

		 SHA256 value computed:
		 e9  d8  ee  0c  a0  e0  d3  89  f8  7b  46  76  e8  5b  7b  c3
		 7b  63  aa  f0  32  92  6c  92  20  87  a2  6a  5f  aa  ba  a7

		 ECDSA Signature Verify

		 Result: OK, ret = 0
		Signature Verification OK!
		Jump to app with debug activation ......
		
	In case the response data is correct, then the debug will be reopened similar to Test 2 of step 5.
	
 * <h3><center>&copy; COPYRIGHT STMicroelectronics</center></h3>
 */
