From d67ba714caeaf1669919a5bbc8142fab7b3a861d Mon Sep 17 00:00:00 2001 From: Arto Kinnunen Date: Tue, 19 Sep 2017 11:25:40 +0300 Subject: [PATCH 01/60] Fix redefinition of mbed TLS error codes -Use guards around MBEDTLS macros. --- .../source/include/coap_security_handler.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/features/nanostack/FEATURE_NANOSTACK/coap-service/source/include/coap_security_handler.h b/features/nanostack/FEATURE_NANOSTACK/coap-service/source/include/coap_security_handler.h index f02167e028..4a1f11d0e0 100644 --- a/features/nanostack/FEATURE_NANOSTACK/coap-service/source/include/coap_security_handler.h +++ b/features/nanostack/FEATURE_NANOSTACK/coap-service/source/include/coap_security_handler.h @@ -100,10 +100,21 @@ const void *coap_security_handler_keyblock(const coap_security_t *sec); NS_DUMMY_DEFINITIONS_OK /* Dummy definitions, including needed error codes */ +#ifndef MBEDTLS_ERR_SSL_TIMEOUT #define MBEDTLS_ERR_SSL_TIMEOUT (-1) +#endif + +#ifndef MBEDTLS_ERR_SSL_WANT_READ #define MBEDTLS_ERR_SSL_WANT_READ (-2) +#endif + +#ifndef MBEDTLS_ERR_SSL_WANT_WRITE #define MBEDTLS_ERR_SSL_WANT_WRITE (-3) +#endif + +#ifndef MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE #define MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE (-4) +#endif #define coap_security_create(socket_id, timer_id, handle, \ mode, send_cb, receive_cb, start_timer_cb, timer_status_cb) ((coap_security_t *) 0) From 174d53649f3d051e8392a1cc0fd43e96e3144879 Mon Sep 17 00:00:00 2001 From: Tony Wu Date: Wed, 20 Sep 2017 09:58:46 +0800 Subject: [PATCH 02/60] rtl8195am - fix us_ticker porting commit f7bc126 (Re-work Rtl8195AM ticker) tried to address ticker drifting issue, but in fact broke ticker functionality. This patch adjusts us_ticker porting to unbreak it, and to fix the following tests: mbed-os-tests-mbed_drivers-ticker mbed-os-tests-mbed_drivers-timeout mbed-os-tests-mbedmicro-rtos-mbed-isr mbed-os-features-frameworks-utest-tests-unit_tests-minimal_async_scheduler mbed-os-features-frameworks-utest-tests-unit_tests-case_control_async mbed-os-features-frameworks-utest-tests-unit_tests-case_async_validate Changes are: 1. Dont disable timer after every us_ticker interrupt. That basically breaks ticker functionality. 2. Fine-tune us to tick conversion macro. Previous conversion method yields 1 tick drift every 2 ms. 3. Remove special placement of ticker objects. No longer necessary. Signed-off-by: Tony Wu --- .../device/TOOLCHAIN_ARM_STD/rtl8195a.sct | 13 +---- .../device/TOOLCHAIN_GCC_ARM/rtl8195a.ld | 8 --- .../device/TOOLCHAIN_IAR/rtl8195a.icf | 7 --- .../TARGET_Realtek/TARGET_AMEBA/us_ticker.c | 49 ++++++++++++------- 4 files changed, 32 insertions(+), 45 deletions(-) diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/rtl8195a.sct b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/rtl8195a.sct index e76cc189fe..20a476ba54 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/rtl8195a.sct +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_ARM_STD/rtl8195a.sct @@ -19,18 +19,9 @@ LR_IRAM 0x10007000 (0x70000 - 0x7000) { ER_IRAM +0 FIXED { *rtl8195a_crypto.o (+RO) - * (i.mbedtls*) + *(i.mbedtls*) *libc.a (+RO) - - *rtx_*.o (+RO) - *Ticker.o (+RO) - *Timeout.o (+RO) - *rtx_timer.o (+RO) - *TimerEvent.o (+RO) - *mbed_ticker_api.o (+RO) - *mbed_critical.o (+RO) - *us_ticker.o (+RO) - + *rtx_*.o (+RO) *lib_peripheral_mbed_arm.ar (+RO) } diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/rtl8195a.ld b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/rtl8195a.ld index 4c05ef9641..6a99b066b5 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/rtl8195a.ld +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_GCC_ARM/rtl8195a.ld @@ -70,15 +70,7 @@ SECTIONS *rtl8195a_crypto.o (.text* .rodata*) *mbedtls*.o (.text* .rodata*) *libc.a: (.text* .rodata*) - *Ticker.o (.text*) - *Timeout.o (.text*) - *TimerEvent.o (.text*) - *mbed_ticker_api.o (.text*) - *mbed_critical.o (.text*) - *us_ticker.o (.text*) - *lib_peripheral_mbed_gcc.a: (.text*) - } > SRAM1 .text.sram2 : diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/rtl8195a.icf b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/rtl8195a.icf index 5244ef9a5c..ed434c9355 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/rtl8195a.icf +++ b/targets/TARGET_Realtek/TARGET_AMEBA/TARGET_RTL8195A/device/TOOLCHAIN_IAR/rtl8195a.icf @@ -213,13 +213,6 @@ define block MBEDTLS_TEXT with alignment = 8, fixed order{ define block .sram1.text with fixed order { block MBEDTLS_TEXT, - section .text* object Ticker.o, - section .text* object Timeout.o, - section .text* object TimerEvent.o, - section .text* object mbed_ticker_api.o, - section .text* object mbed_critical.o, - section .text* object us_ticker.o, - section .text* object lib_peripheral_mbed_iar.a, }; diff --git a/targets/TARGET_Realtek/TARGET_AMEBA/us_ticker.c b/targets/TARGET_Realtek/TARGET_AMEBA/us_ticker.c index 87b5ede9eb..504eb7c1bd 100644 --- a/targets/TARGET_Realtek/TARGET_AMEBA/us_ticker.c +++ b/targets/TARGET_Realtek/TARGET_AMEBA/us_ticker.c @@ -20,10 +20,22 @@ #include "PeripheralNames.h" #define TICK_READ_FROM_CPU 0 // 1: read tick from CPU, 0: read tick from G-Timer -#define SYS_TIM_ID 1 // the G-Timer ID for System -#define APP_TIM_ID 6 // the G-Timer ID for Application +#define SYS_TIM_ID 1 // the G-Timer ID for System +#define APP_TIM_ID 6 // the G-Timer ID for Application -#define TICK_TO_US(x) (uint64_t)(((x)/2) * 61 + ((x)%2) * TIMER_TICK_US) +/* + * For RTL8195AM, clock source is 32k + * + * us per tick: 30.5 + * tick per ms: 32.7 + * tick per us: 0.032 + * tick per sec: 32768 + * + * Define the following macros to convert between TICK and US. + */ +#define MS_TO_TICK(x) (uint64_t)(((x)*327) / 10) +#define US_TO_TICK(x) (uint64_t)(((x)*32) / 1000) +#define TICK_TO_US(x) (uint64_t)(((x)/2) * 61 + ((x)%2) * TIMER_TICK_US) static int us_ticker_inited = 0; static TIMER_ADAPTER TimerAdapter; @@ -34,23 +46,22 @@ extern HAL_TIMER_OP_EXT HalTimerOpExt; VOID _us_ticker_irq_handler(void *Data) { us_ticker_irq_handler(); - HalTimerOp.HalTimerDis((u32)TimerAdapter.TimerId); } -void us_ticker_init(void) +void us_ticker_init(void) { - - if (us_ticker_inited){ + if (us_ticker_inited) { return; } - + us_ticker_inited = 1; - + + // Reload and restart sys-timer HalTimerOp.HalTimerDis(SYS_TIM_ID); HalTimerOpExt.HalTimerReLoad(SYS_TIM_ID, 0xFFFFFFFFUL); HalTimerOp.HalTimerEn(SYS_TIM_ID); - - // Initial a G-Timer + + // Initial a app-timer TimerAdapter.IrqDis = 0; // Enable Irq @ initial TimerAdapter.IrqHandle.IrqFun = (IRQ_FUN) _us_ticker_irq_handler; TimerAdapter.IrqHandle.IrqNum = TIMER2_7_IRQ; @@ -66,22 +77,22 @@ void us_ticker_init(void) DBG_TIMER_INFO("%s: Timer_Id=%d\n", __FUNCTION__, APP_TIM_ID); } -uint32_t us_ticker_read(void) +uint32_t us_ticker_read(void) { uint32_t tick_cnt; uint64_t tick_us; - + if (!us_ticker_inited) { us_ticker_init(); } - + tick_cnt = HalTimerOp.HalTimerReadCount(SYS_TIM_ID); tick_us = TICK_TO_US(0xFFFFFFFFUL - tick_cnt); return ((uint32_t)tick_us); //return ticker value in micro-seconds (us) } -void us_ticker_set_interrupt(timestamp_t timestamp) +void us_ticker_set_interrupt(timestamp_t timestamp) { uint32_t time_cur; uint32_t time_cnt; @@ -95,9 +106,9 @@ void us_ticker_set_interrupt(timestamp_t timestamp) HalTimerOp.HalTimerEn((u32)TimerAdapter.TimerId); us_ticker_fire_interrupt(); return; - } + } - TimerAdapter.TimerLoadValueUs = time_cnt / TIMER_TICK_US; + TimerAdapter.TimerLoadValueUs = MAX(MS_TO_TICK(time_cnt/1000) + US_TO_TICK(time_cnt%1000), 1); HalTimerOpExt.HalTimerReLoad((u32)TimerAdapter.TimerId, TimerAdapter.TimerLoadValueUs); HalTimerOp.HalTimerEn((u32)TimerAdapter.TimerId); } @@ -107,12 +118,12 @@ void us_ticker_fire_interrupt(void) NVIC_SetPendingIRQ(TIMER2_7_IRQ); } -void us_ticker_disable_interrupt(void) +void us_ticker_disable_interrupt(void) { HalTimerOp.HalTimerDis((u32)TimerAdapter.TimerId); } -void us_ticker_clear_interrupt(void) +void us_ticker_clear_interrupt(void) { HalTimerOp.HalTimerIrqClear((u32)TimerAdapter.TimerId); } From eb2bb84e8384fa062813e1f4a4c5d6d21d389e3c Mon Sep 17 00:00:00 2001 From: Laurent MEUNIER Date: Thu, 17 Aug 2017 14:52:20 +0200 Subject: [PATCH 03/60] STM32: move can_s definition to common_objects.h This will ease up further changes to the structure. --- .../TARGET_STM32F0/TARGET_NUCLEO_F042K6/objects.h | 5 ----- .../TARGET_STM32F0/TARGET_NUCLEO_F072RB/objects.h | 5 ----- .../TARGET_STM32F0/TARGET_NUCLEO_F091RC/objects.h | 5 ----- targets/TARGET_STM/TARGET_STM32F0/common_objects.h | 7 +++++++ .../TARGET_STM32F1/TARGET_BLUEPILL_F103C8/objects.h | 5 ----- .../TARGET_STM32F1/TARGET_NUCLEO_F103RB/objects.h | 5 ----- targets/TARGET_STM/TARGET_STM32F1/common_objects.h | 7 +++++++ .../TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/objects.h | 7 ------- targets/TARGET_STM/TARGET_STM32F3/common_objects.h | 7 +++++++ .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F413xH/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/objects.h | 5 ----- targets/TARGET_STM/TARGET_STM32F4/common_objects.h | 7 +++++++ .../TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/objects.h | 5 ----- targets/TARGET_STM/TARGET_STM32F7/common_objects.h | 7 +++++++ .../TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/objects.h | 5 ----- .../TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/objects.h | 5 ----- targets/TARGET_STM/TARGET_STM32L4/common_objects.h | 7 +++++++ 31 files changed, 42 insertions(+), 127 deletions(-) diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F042K6/objects.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F042K6/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F042K6/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F042K6/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/objects.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/objects.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h index 3d11acebd0..64f6f7b3a6 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h @@ -128,6 +128,13 @@ struct dac_s { }; #endif +#if DEVICE_CAN +struct can_s { + CANName can; + int index; +}; +#endif + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/objects.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/objects.h index 24fa9d1f17..5ddc595468 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/objects.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/objects.h index 24fa9d1f17..5ddc595468 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h index 12487fcf0b..ea1dd35db3 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h @@ -116,6 +116,13 @@ struct analogin_s { uint8_t channel; }; +#if DEVICE_CAN +struct can_s { + CANName can; + int index; +}; +#endif + #include "gpio_object.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/objects.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/objects.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/objects.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/objects.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/objects.h index 8022de0cb7..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/objects.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/objects.h index 90b0f732c1..d0f3565f66 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/objects.h @@ -54,13 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -#if defined (DEVICE_CAN) -struct can_s { - CANName can; - int index; -}; -#endif - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h index 8db726ed14..07f4ec8b10 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h @@ -124,6 +124,13 @@ struct analogin_s { uint8_t channel; }; +#if DEVICE_CAN +struct can_s { + CANName can; + int index; +}; +#endif + #include "gpio_object.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/objects.h index 9ab04158e0..565319422c 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/objects.h @@ -40,11 +40,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F413xH/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F413xH/objects.h index ceee07a594..9b3aa0b3f9 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F413xH/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F413xH/objects.h @@ -40,11 +40,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/objects.h index a7e928ec3a..ece5f1679f 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h index e1b80b20e4..d2474f4e52 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h @@ -59,11 +59,6 @@ struct trng_s { }; #include "common_objects.h" -struct can_s { - CANName can; - int index; -}; - #include "gpio_object.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/objects.h index a7e928ec3a..ece5f1679f 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/objects.h index a2e2ad0f34..16467b7c87 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - #include "common_objects.h" #ifdef __cplusplus diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/objects.h index 0de614ff89..bea7fef547 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/common_objects.h b/targets/TARGET_STM/TARGET_STM32F4/common_objects.h index d5d8a6c184..98f51e4450 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/common_objects.h @@ -133,6 +133,13 @@ struct dac_s { }; #endif +#if DEVICE_CAN +struct can_s { + CANName can; + int index; +}; +#endif + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/objects.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/objects.h index 52b8e159eb..2894691118 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/objects.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/objects.h index 52b8e159eb..2894691118 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/objects.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/objects.h index 52b8e159eb..2894691118 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/objects.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/objects.h index 52b8e159eb..2894691118 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/common_objects.h b/targets/TARGET_STM/TARGET_STM32F7/common_objects.h index ee81970f04..ba02b99c02 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/common_objects.h @@ -132,6 +132,13 @@ struct flash_s { uint32_t dummy; }; +#if DEVICE_CAN +struct can_s { + CANName can; + int index; +}; +#endif + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/objects.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/objects.h index a7e928ec3a..ece5f1679f 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/objects.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/objects.h index a0dee029b4..e68c4eb619 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/objects.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/objects.h index a7e928ec3a..ece5f1679f 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/objects.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/objects.h index a7e928ec3a..ece5f1679f 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/objects.h @@ -54,11 +54,6 @@ struct port_s { __IO uint32_t *reg_out; }; -struct can_s { - CANName can; - int index; -}; - struct trng_s { RNG_HandleTypeDef handle; }; diff --git a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h index e9e10f3069..211612aa7a 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h @@ -135,6 +135,13 @@ struct dac_s { } #endif +#if DEVICE_CAN +struct can_s { + CANName can; + int index; +}; +#endif + /* STM32L4 HAL doesn't provide this API called in rtc_api.c */ #define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) From 9ad4a913cdca020315aa59bcb7704d681918f1f2 Mon Sep 17 00:00:00 2001 From: Laurent MEUNIER Date: Thu, 17 Aug 2017 15:02:30 +0200 Subject: [PATCH 04/60] STM32: Define CAN handle as part of can object Instead of a static object, this will make driver instantiation more robust and allow to re-use init configuration on a need basis. The CANName struct member is actually the CAN registers base address, which is now available in the CanHandle.Instance field, so we don't need CANName anymore. --- .../TARGET_STM32F0/common_objects.h | 2 +- .../TARGET_STM32F1/common_objects.h | 2 +- targets/TARGET_STM/TARGET_STM32F2/objects.h | 2 +- .../TARGET_STM32F3/common_objects.h | 2 +- .../TARGET_STM32F4/common_objects.h | 2 +- .../TARGET_STM32F7/common_objects.h | 2 +- .../TARGET_STM32L4/common_objects.h | 2 +- targets/TARGET_STM/can_api.c | 71 +++++++++---------- 8 files changed, 42 insertions(+), 43 deletions(-) diff --git a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h index 64f6f7b3a6..66ad9a2b56 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h @@ -130,7 +130,7 @@ struct dac_s { #if DEVICE_CAN struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h index ea1dd35db3..561b220476 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h @@ -118,7 +118,7 @@ struct analogin_s { #if DEVICE_CAN struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F2/objects.h b/targets/TARGET_STM/TARGET_STM32F2/objects.h index c2489cb851..019673a529 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F2/objects.h @@ -137,7 +137,7 @@ struct pwmout_s { }; struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; diff --git a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h index 07f4ec8b10..295ca9a048 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h @@ -126,7 +126,7 @@ struct analogin_s { #if DEVICE_CAN struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/common_objects.h b/targets/TARGET_STM/TARGET_STM32F4/common_objects.h index 98f51e4450..5715bf5240 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/common_objects.h @@ -135,7 +135,7 @@ struct dac_s { #if DEVICE_CAN struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F7/common_objects.h b/targets/TARGET_STM/TARGET_STM32F7/common_objects.h index ba02b99c02..10e857c9a0 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/common_objects.h @@ -134,7 +134,7 @@ struct flash_s { #if DEVICE_CAN struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h index 211612aa7a..870e98c49b 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h @@ -137,7 +137,7 @@ struct dac_s { #if DEVICE_CAN struct can_s { - CANName can; + CAN_HandleTypeDef CanHandle; int index; }; #endif diff --git a/targets/TARGET_STM/can_api.c b/targets/TARGET_STM/can_api.c index cd3c9b8888..bbae653776 100644 --- a/targets/TARGET_STM/can_api.c +++ b/targets/TARGET_STM/can_api.c @@ -25,7 +25,6 @@ #include #include -static CAN_HandleTypeDef CanHandle; static uint32_t can_irq_ids[CAN_NUM] = {0}; static can_irq_handler irq_handler; @@ -38,16 +37,16 @@ void can_init_freq (can_t *obj, PinName rd, PinName td, int hz) { CANName can_rd = (CANName)pinmap_peripheral(rd, PinMap_CAN_RD); CANName can_td = (CANName)pinmap_peripheral(td, PinMap_CAN_TD); + CANName can = (CANName)pinmap_merge(can_rd, can_td); - obj->can = (CANName)pinmap_merge(can_rd, can_td); - MBED_ASSERT((int)obj->can != NC); + MBED_ASSERT((int)can != NC); - if (obj->can == CAN_1) { + if (can == CAN_1) { __HAL_RCC_CAN1_CLK_ENABLE(); obj->index = 0; } #if defined(CAN2_BASE) && (CAN_NUM == 2) - else if (obj->can == CAN_2) { + else if (can == CAN_2) { __HAL_RCC_CAN1_CLK_ENABLE(); // needed to set filters __HAL_RCC_CAN2_CLK_ENABLE(); obj->index = 1; @@ -67,21 +66,21 @@ void can_init_freq (can_t *obj, PinName rd, PinName td, int hz) pin_mode(td, PullUp); } - CanHandle.Instance = (CAN_TypeDef *)(obj->can); + obj->CanHandle.Instance = (CAN_TypeDef *)can; - CanHandle.Init.TTCM = DISABLE; - CanHandle.Init.ABOM = DISABLE; - CanHandle.Init.AWUM = DISABLE; - CanHandle.Init.NART = DISABLE; - CanHandle.Init.RFLM = DISABLE; - CanHandle.Init.TXFP = DISABLE; - CanHandle.Init.Mode = CAN_MODE_NORMAL; - CanHandle.Init.SJW = CAN_SJW_1TQ; - CanHandle.Init.BS1 = CAN_BS1_6TQ; - CanHandle.Init.BS2 = CAN_BS2_8TQ; - CanHandle.Init.Prescaler = 2; + obj->CanHandle.Init.TTCM = DISABLE; + obj->CanHandle.Init.ABOM = DISABLE; + obj->CanHandle.Init.AWUM = DISABLE; + obj->CanHandle.Init.NART = DISABLE; + obj->CanHandle.Init.RFLM = DISABLE; + obj->CanHandle.Init.TXFP = DISABLE; + obj->CanHandle.Init.Mode = CAN_MODE_NORMAL; + obj->CanHandle.Init.SJW = CAN_SJW_1TQ; + obj->CanHandle.Init.BS1 = CAN_BS1_6TQ; + obj->CanHandle.Init.BS2 = CAN_BS2_8TQ; + obj->CanHandle.Init.Prescaler = 2; - if (HAL_CAN_Init(&CanHandle) != HAL_OK) { + if (HAL_CAN_Init(&obj->CanHandle) != HAL_OK) { error("Cannot initialize CAN"); } @@ -90,7 +89,7 @@ void can_init_freq (can_t *obj, PinName rd, PinName td, int hz) error("Can frequency could not be set\n"); } - uint32_t filter_number = (obj->can == CAN_1) ? 0 : 14; + uint32_t filter_number = (can == CAN_1) ? 0 : 14; can_filter(obj, 0, 0, CANStandard, filter_number); } @@ -102,7 +101,7 @@ void can_irq_init(can_t *obj, can_irq_handler handler, uint32_t id) void can_irq_free(can_t *obj) { - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; can->IER &= ~(CAN_IT_FMP0 | CAN_IT_FMP1 | CAN_IT_TME | \ CAN_IT_ERR | CAN_IT_EPV | CAN_IT_BOF); @@ -111,14 +110,15 @@ void can_irq_free(can_t *obj) void can_free(can_t *obj) { + CANName can = (CANName) obj->CanHandle.Instance; // Reset CAN and disable clock - if (obj->can == CAN_1) { + if (can == CAN_1) { __HAL_RCC_CAN1_FORCE_RESET(); __HAL_RCC_CAN1_RELEASE_RESET(); __HAL_RCC_CAN1_CLK_DISABLE(); } #if defined(CAN2_BASE) && (CAN_NUM == 2) - if (obj->can == CAN_2) { + if (can == CAN_2) { __HAL_RCC_CAN2_FORCE_RESET(); __HAL_RCC_CAN2_RELEASE_RESET(); __HAL_RCC_CAN2_CLK_DISABLE(); @@ -196,7 +196,7 @@ int can_frequency(can_t *obj, int f) { int pclk = HAL_RCC_GetPCLK1Freq(); int btr = can_speed(pclk, (unsigned int)f, 1); - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; uint32_t tickstart = 0; int status = 1; @@ -236,7 +236,7 @@ int can_frequency(can_t *obj, int f) int can_write(can_t *obj, CAN_Message msg, int cc) { uint32_t transmitmailbox = CAN_TXSTATUS_NOMAILBOX; - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; /* Select one empty transmit mailbox */ if ((can->TSR & CAN_TSR_TME0) == CAN_TSR_TME0) { @@ -279,7 +279,7 @@ int can_read(can_t *obj, CAN_Message *msg, int handle) { //handle is the FIFO number - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; // check FPM0 which holds the pending message count in FIFO 0 // if no message is pending, return 0 @@ -324,26 +324,26 @@ int can_read(can_t *obj, CAN_Message *msg, int handle) void can_reset(can_t *obj) { - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; can->MCR |= CAN_MCR_RESET; can->ESR = 0x0; } unsigned char can_rderror(can_t *obj) { - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; return (can->ESR >> 24) & 0xFF; } unsigned char can_tderror(can_t *obj) { - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; return (can->ESR >> 16) & 0xFF; } void can_monitor(can_t *obj, int silent) { - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; can->MCR |= CAN_MCR_INRQ ; while ((can->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) { @@ -363,7 +363,7 @@ void can_monitor(can_t *obj, int silent) int can_mode(can_t *obj, CanMode mode) { int success = 0; - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; can->MCR |= CAN_MCR_INRQ ; while ((can->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) { @@ -407,7 +407,6 @@ int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t // filter for CANAny format cannot be configured for STM32 if ((format == CANStandard) || (format == CANExtended)) { - CanHandle.Instance = (CAN_TypeDef *)(obj->can); CAN_FilterConfTypeDef sFilterConfig; sFilterConfig.FilterNumber = handle; sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK; @@ -429,7 +428,7 @@ int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t sFilterConfig.FilterActivation = ENABLE; sFilterConfig.BankNumber = 14 + handle; - HAL_CAN_ConfigFilter(&CanHandle, &sFilterConfig); + HAL_CAN_ConfigFilter(&obj->CanHandle, &sFilterConfig); retval = handle; } return retval; @@ -438,6 +437,7 @@ int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t static void can_irq(CANName name, int id) { uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0; + CAN_HandleTypeDef CanHandle; CanHandle.Instance = (CAN_TypeDef *)name; if (__HAL_CAN_GET_IT_SOURCE(&CanHandle, CAN_IT_TME)) { @@ -535,13 +535,12 @@ void CAN2_SCE_IRQHandler(void) void can_irq_set(can_t *obj, CanIrqType type, uint32_t enable) { - - CAN_TypeDef *can = (CAN_TypeDef *)(obj->can); + CAN_TypeDef *can = obj->CanHandle.Instance; IRQn_Type irq_n = (IRQn_Type)0; uint32_t vector = 0; uint32_t ier; - if (obj->can == CAN_1) { + if ((CANName) can == CAN_1) { switch (type) { case IRQ_RX: ier = CAN_IT_FMP0; @@ -573,7 +572,7 @@ void can_irq_set(can_t *obj, CanIrqType type, uint32_t enable) } } #if defined(CAN2_BASE) && (CAN_NUM == 2) - else if (obj->can == CAN_2) { + else if ((CANName) can == CAN_2) { switch (type) { case IRQ_RX: ier = CAN_IT_FMP0; From a6ad257d55c35496de7fd62d0649a5041528ac16 Mon Sep 17 00:00:00 2001 From: Laurent MEUNIER Date: Thu, 17 Aug 2017 15:02:30 +0200 Subject: [PATCH 05/60] STM32: CAN: restore registers after can_reset After reset the MCR register content needs to be restored so we're introducing the can_registers_init function to be called at the first init stage, but also after reset. We also store the can frequency to go through the initialisation phase again. --- .../TARGET_STM32F0/common_objects.h | 1 + .../TARGET_STM32F1/common_objects.h | 1 + targets/TARGET_STM/TARGET_STM32F2/objects.h | 1 + .../TARGET_STM32F3/common_objects.h | 1 + .../TARGET_STM32F4/common_objects.h | 1 + .../TARGET_STM32F7/common_objects.h | 1 + .../TARGET_STM32L4/common_objects.h | 1 + targets/TARGET_STM/can_api.c | 30 ++++++++++++++----- 8 files changed, 29 insertions(+), 8 deletions(-) diff --git a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h index 66ad9a2b56..c6ebc7bd02 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F0/common_objects.h @@ -132,6 +132,7 @@ struct dac_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h index 561b220476..3bd078970c 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F1/common_objects.h @@ -120,6 +120,7 @@ struct analogin_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F2/objects.h b/targets/TARGET_STM/TARGET_STM32F2/objects.h index 019673a529..adad4a21ec 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F2/objects.h @@ -139,6 +139,7 @@ struct pwmout_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #define GPIO_IP_WITHOUT_BRR diff --git a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h index 295ca9a048..ba731890ce 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F3/common_objects.h @@ -128,6 +128,7 @@ struct analogin_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/common_objects.h b/targets/TARGET_STM/TARGET_STM32F4/common_objects.h index 5715bf5240..3f39a9ce53 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F4/common_objects.h @@ -137,6 +137,7 @@ struct dac_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F7/common_objects.h b/targets/TARGET_STM/TARGET_STM32F7/common_objects.h index 10e857c9a0..b3f02642c7 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32F7/common_objects.h @@ -136,6 +136,7 @@ struct flash_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h index 870e98c49b..9ee16729ea 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/common_objects.h +++ b/targets/TARGET_STM/TARGET_STM32L4/common_objects.h @@ -139,6 +139,7 @@ struct dac_s { struct can_s { CAN_HandleTypeDef CanHandle; int index; + int hz; }; #endif diff --git a/targets/TARGET_STM/can_api.c b/targets/TARGET_STM/can_api.c index bbae653776..7069ee6bb7 100644 --- a/targets/TARGET_STM/can_api.c +++ b/targets/TARGET_STM/can_api.c @@ -28,6 +28,18 @@ static uint32_t can_irq_ids[CAN_NUM] = {0}; static can_irq_handler irq_handler; +static void can_registers_init(can_t *obj) +{ + if (HAL_CAN_Init(&obj->CanHandle) != HAL_OK) { + error("Cannot initialize CAN"); + } + + // Set initial CAN frequency to specified frequency + if (can_frequency(obj, obj->hz) != 1) { + error("Can frequency could not be set\n"); + } +} + void can_init(can_t *obj, PinName rd, PinName td) { can_init_freq(obj, rd, td, 100000); @@ -66,8 +78,8 @@ void can_init_freq (can_t *obj, PinName rd, PinName td, int hz) pin_mode(td, PullUp); } + /* Use default values for rist init */ obj->CanHandle.Instance = (CAN_TypeDef *)can; - obj->CanHandle.Init.TTCM = DISABLE; obj->CanHandle.Init.ABOM = DISABLE; obj->CanHandle.Init.AWUM = DISABLE; @@ -80,19 +92,16 @@ void can_init_freq (can_t *obj, PinName rd, PinName td, int hz) obj->CanHandle.Init.BS2 = CAN_BS2_8TQ; obj->CanHandle.Init.Prescaler = 2; - if (HAL_CAN_Init(&obj->CanHandle) != HAL_OK) { - error("Cannot initialize CAN"); - } + /* Store frequency to be restored in case of reset */ + obj->hz = hz; - // Set initial CAN frequency to specified frequency - if (can_frequency(obj, hz) != 1) { - error("Can frequency could not be set\n"); - } + can_registers_init(obj); uint32_t filter_number = (can == CAN_1) ? 0 : 14; can_filter(obj, 0, 0, CANStandard, filter_number); } + void can_irq_init(can_t *obj, can_irq_handler handler, uint32_t id) { irq_handler = handler; @@ -325,8 +334,13 @@ int can_read(can_t *obj, CAN_Message *msg, int handle) void can_reset(can_t *obj) { CAN_TypeDef *can = obj->CanHandle.Instance; + + /* Reset IP and delete errors */ can->MCR |= CAN_MCR_RESET; can->ESR = 0x0; + + /* restore registers state as saved in obj context */ + can_registers_init(obj); } unsigned char can_rderror(can_t *obj) From 08eba6ccd92a9f7f7663ea5e52186f5951f60f7e Mon Sep 17 00:00:00 2001 From: Laurent MEUNIER Date: Thu, 17 Aug 2017 17:00:01 +0200 Subject: [PATCH 06/60] STM32: CAN: do not overwite BTR register when setting frequency BTR register has other bits than the ones calculated and set through the can_speed function, so let's take care to only write to the right registers. --- targets/TARGET_STM/can_api.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/targets/TARGET_STM/can_api.c b/targets/TARGET_STM/can_api.c index 7069ee6bb7..a8d71e5f6f 100644 --- a/targets/TARGET_STM/can_api.c +++ b/targets/TARGET_STM/can_api.c @@ -220,7 +220,11 @@ int can_frequency(can_t *obj, int f) } } if (status != 0) { - can->BTR = btr; + /* Do not erase all BTR registers (e.g. silent mode), only the + * ones calculated in can_speed */ + can->BTR &= ~(CAN_BTR_TS2 | CAN_BTR_TS1 | CAN_BTR_SJW | CAN_BTR_BRP); + can->BTR |= btr; + can->MCR &= ~(uint32_t)CAN_MCR_INRQ; /* Get tick */ tickstart = HAL_GetTick(); From ca3a1aa66cf0994b10c8d0e320df0cad0cb21c06 Mon Sep 17 00:00:00 2001 From: Laurent MEUNIER Date: Fri, 18 Aug 2017 10:13:18 +0200 Subject: [PATCH 07/60] STM32: CAN: store the mode in object context In order to apply the same mode in case of reset, we store the current requested mode in the HAL structure. To make storage in a single place, we also change can_monitor to call can_mode function as they actually acting on same registers. --- targets/TARGET_STM/can_api.c | 38 ++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/targets/TARGET_STM/can_api.c b/targets/TARGET_STM/can_api.c index a8d71e5f6f..b89f62891c 100644 --- a/targets/TARGET_STM/can_api.c +++ b/targets/TARGET_STM/can_api.c @@ -361,21 +361,31 @@ unsigned char can_tderror(can_t *obj) void can_monitor(can_t *obj, int silent) { - CAN_TypeDef *can = obj->CanHandle.Instance; - - can->MCR |= CAN_MCR_INRQ ; - while ((can->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) { - } - - if (silent) { - can->BTR |= ((uint32_t)1 << 31); + CanMode mode = MODE_NORMAL; + /* Update current state w/ or w/o silent */ + if(silent) { + switch (obj->CanHandle.Init.Mode) { + case CAN_MODE_LOOPBACK: + case CAN_MODE_SILENT_LOOPBACK: + mode = MODE_TEST_SILENT; + break; + default: + mode = MODE_SILENT; + break; + } } else { - can->BTR &= ~((uint32_t)1 << 31); + switch (obj->CanHandle.Init.Mode) { + case CAN_MODE_LOOPBACK: + case CAN_MODE_SILENT_LOOPBACK: + mode = MODE_TEST_LOCAL; + break; + default: + mode = MODE_NORMAL; + break; + } } - can->MCR &= ~(uint32_t)CAN_MCR_INRQ; - while ((can->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) { - } + can_mode(obj, mode); } int can_mode(can_t *obj, CanMode mode) @@ -389,21 +399,25 @@ int can_mode(can_t *obj, CanMode mode) switch (mode) { case MODE_NORMAL: + obj->CanHandle.Init.Mode = CAN_MODE_NORMAL; can->BTR &= ~(CAN_BTR_SILM | CAN_BTR_LBKM); success = 1; break; case MODE_SILENT: + obj->CanHandle.Init.Mode = CAN_MODE_SILENT; can->BTR |= CAN_BTR_SILM; can->BTR &= ~CAN_BTR_LBKM; success = 1; break; case MODE_TEST_GLOBAL: case MODE_TEST_LOCAL: + obj->CanHandle.Init.Mode = CAN_MODE_LOOPBACK; can->BTR |= CAN_BTR_LBKM; can->BTR &= ~CAN_BTR_SILM; success = 1; break; case MODE_TEST_SILENT: + obj->CanHandle.Init.Mode = CAN_MODE_SILENT_LOOPBACK; can->BTR |= (CAN_BTR_SILM | CAN_BTR_LBKM); success = 1; break; From 7a7ccd7743e132e62a29504ecd860e591a1f59d5 Mon Sep 17 00:00:00 2001 From: Laurent MEUNIER Date: Mon, 21 Aug 2017 14:41:08 +0200 Subject: [PATCH 08/60] STM32: F2: put can_s struct under DEVICE_CAN option In case of F2 devices without CAN support. --- targets/TARGET_STM/TARGET_STM32F2/objects.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/targets/TARGET_STM/TARGET_STM32F2/objects.h b/targets/TARGET_STM/TARGET_STM32F2/objects.h index adad4a21ec..e87ecf78a7 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/objects.h +++ b/targets/TARGET_STM/TARGET_STM32F2/objects.h @@ -136,11 +136,13 @@ struct pwmout_s { uint8_t inverted; }; +#ifdef DEVICE_CAN struct can_s { CAN_HandleTypeDef CanHandle; int index; int hz; }; +#endif #define GPIO_IP_WITHOUT_BRR #include "gpio_object.h" From f9ac4d676d517603893d262e1d570346ec965bcb Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Fri, 8 Sep 2017 14:17:09 -0500 Subject: [PATCH 09/60] Fix travis requirements install pip requires --user flag when installing executables outside of sudo context --- .travis.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0bd0e8a185..3fecbafc4e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ python: - "2.7" -group: deprecated-2017Q3 script: - mkdir BUILD # Assert that the Doxygen build produced no warnings. @@ -36,10 +35,10 @@ before_install: - python --version - doxygen --version install: - - pip install -r requirements.txt - - pip install pytest - - pip install pylint - - pip install hypothesis - - pip install mock - - pip install coverage - - pip install coveralls + - pip install --user -r requirements.txt + - pip install --user pytest + - pip install --user pylint + - pip install --user hypothesis + - pip install --user mock + - pip install --user coverage + - pip install --user coveralls From 0673e248517b4f152a709ebc4314090663bbda0c Mon Sep 17 00:00:00 2001 From: adustm Date: Tue, 5 Sep 2017 10:25:37 +0200 Subject: [PATCH 10/60] Enable AES_ALT mode again (remove workaround) --- .../TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h index 90213bea11..dfbc82055e 100644 --- a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h +++ b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h @@ -20,9 +20,7 @@ #ifndef MBEDTLS_DEVICE_H #define MBEDTLS_DEVICE_H -/* FIXME: Don't enable AES hardware acceleration until issue #4928 is fixed. - * (https://github.com/ARMmbed/mbed-os/issues/4928) */ -/* #define MBEDTLS_AES_ALT */ +#define MBEDTLS_AES_ALT #define MBEDTLS_SHA256_ALT From 8888e3911bf1bf70b5bdb51ead4ac39b7c6e841a Mon Sep 17 00:00:00 2001 From: adustm Date: Mon, 4 Sep 2017 17:13:00 +0200 Subject: [PATCH 11/60] Fix multi context for AES CBC and ECB mode Fix mbed-os-example-tls-client use case --- features/mbedtls/targets/TARGET_STM/aes_alt.c | 123 +++++++++++++++--- features/mbedtls/targets/TARGET_STM/aes_alt.h | 3 + 2 files changed, 105 insertions(+), 21 deletions(-) diff --git a/features/mbedtls/targets/TARGET_STM/aes_alt.c b/features/mbedtls/targets/TARGET_STM/aes_alt.c index 8736d7ee47..ae10c919ca 100644 --- a/features/mbedtls/targets/TARGET_STM/aes_alt.c +++ b/features/mbedtls/targets/TARGET_STM/aes_alt.c @@ -129,6 +129,7 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, /* allow multi-instance of CRYP use: restore context for CRYP hw module */ ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr; + ctx->hcryp_aes.Phase = HAL_CRYP_PHASE_READY; if(mode == MBEDTLS_AES_DECRYPT) { /* AES decryption */ ctx->hcryp_aes.Init.DataType = CRYP_DATATYPE_8B; @@ -147,31 +148,93 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, #if defined(MBEDTLS_CIPHER_MODE_CBC) #if defined (TARGET_STM32L486xG) +static int st_cbc_restore_context(mbedtls_aes_context *ctx){ + uint32_t tickstart; + tickstart = HAL_GetTick(); + while((ctx->hcryp_aes.Instance->SR & AES_SR_BUSY) != 0){ + if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { + return 1; // timeout: CRYP processor is busy + } + } + /* allow multi-instance of CRYP use: restore context for CRYP hw module */ + ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr; + return 0; +} +static int st_cbc_save_context(mbedtls_aes_context *ctx){ + uint32_t tickstart; + + tickstart = HAL_GetTick(); + while((ctx->hcryp_aes.Instance->SR & AES_SR_BUSY) != 0){ + if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { + return 1; // timeout: CRYP processor is busy + } + } + /* allow multi-instance of CRYP use: save context for CRYP HW module CR */ + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; + + return 0; +} static int st_hal_cryp_cbc( mbedtls_aes_context *ctx, uint32_t opmode, size_t length, unsigned char iv[16], uint8_t *input, uint8_t *output) { int status = 0; ctx->hcryp_aes.Init.pInitVect = &iv[0]; // used in process, not in the init - if ((ctx->hcryp_aes.Init.OperatingMode != opmode) || \ - (ctx->hcryp_aes.Init.ChainingMode != CRYP_CHAINMODE_AES_CBC) || \ - (ctx->hcryp_aes.Init.KeyWriteFlag != CRYP_KEY_WRITE_ENABLE)) { - - /* Re-initialize AES IP with proper parameters */ - if (HAL_CRYP_DeInit(&ctx->hcryp_aes) != HAL_OK) - return HAL_ERROR; - ctx->hcryp_aes.Init.OperatingMode = opmode; - ctx->hcryp_aes.Init.ChainingMode = CRYP_CHAINMODE_AES_CBC; - ctx->hcryp_aes.Init.KeyWriteFlag = CRYP_KEY_WRITE_ENABLE; - if (HAL_CRYP_Init(&ctx->hcryp_aes) != HAL_OK) - return HAL_ERROR; - } + /* At this moment only, we know we have CBC mode: Re-initialize AES + IP with proper parameters and apply key and IV for multi context usecase */ + if (HAL_CRYP_DeInit(&ctx->hcryp_aes) != HAL_OK) + return HAL_ERROR; + ctx->hcryp_aes.Init.OperatingMode = opmode; + ctx->hcryp_aes.Init.ChainingMode = CRYP_CHAINMODE_AES_CBC; + ctx->hcryp_aes.Init.KeyWriteFlag = CRYP_KEY_WRITE_ENABLE; + if (HAL_CRYP_Init(&ctx->hcryp_aes) != HAL_OK) + return HAL_ERROR; status = HAL_CRYPEx_AES(&ctx->hcryp_aes, input, length, output, 10); return status; } +#else +static int st_cbc_restore_context(mbedtls_aes_context *ctx){ + uint32_t tickstart; + tickstart = HAL_GetTick(); + while((ctx->hcryp_aes.Instance->SR & (CRYP_SR_IFEM | CRYP_SR_OFNE | CRYP_SR_BUSY)) != CRYP_SR_IFEM){ + if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { + return 1; // timeout: CRYP processor is busy + } + } + ctx->hcryp_aes.Instance->CR &= ~CRYP_CR_CRYPEN; + /* save initvector for multi-instance use of CRYP */ + ctx->hcryp_aes.Instance->IV1RR = ctx->save_iv[3]; + ctx->hcryp_aes.Instance->IV1LR = ctx->save_iv[2]; + ctx->hcryp_aes.Instance->IV0RR = ctx->save_iv[1]; + ctx->hcryp_aes.Instance->IV0LR = ctx->save_iv[0]; + ctx->hcryp_aes.Phase = HAL_CRYP_PHASE_READY; + /* allow multi-instance of CRYP use: restore context for CRYP hw module */ + ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr; + return 0; +} +static int st_cbc_save_context(mbedtls_aes_context *ctx){ + uint32_t tickstart; + tickstart = HAL_GetTick(); + while((ctx->hcryp_aes.Instance->SR & (CRYP_SR_IFEM | CRYP_SR_OFNE | CRYP_SR_BUSY)) != CRYP_SR_IFEM){ + if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { + return 1; // timeout: CRYP processor is busy + } + } + /* allow multi-instance of CRYP use: save context for CRYP HW module CR */ + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; + ctx->hcryp_aes.Instance->CR &= ~CRYP_CR_CRYPEN; + /* save initvector for multi-instance use of CRYP */ + ctx->save_iv[3] = ctx->hcryp_aes.Instance->IV1RR; + ctx->save_iv[2] = ctx->hcryp_aes.Instance->IV1LR; + ctx->save_iv[1] = ctx->hcryp_aes.Instance->IV0RR; + ctx->save_iv[0] = ctx->hcryp_aes.Instance->IV0LR; + if ((ctx->ctx_save_cr & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN) { + ctx->hcryp_aes.Instance->CR &= CRYP_CR_CRYPEN; + } + return 0; +} #endif /* TARGET_STM32L486xG */ - int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, int mode, size_t length, @@ -180,23 +243,43 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, unsigned char *output ) { int status = 0; + uint32_t *iv_ptr = (uint32_t *)&iv[0]; if( length % 16 ) return( MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH ); + ctx->hcryp_aes.Init.pInitVect = &iv[0]; + status |= st_cbc_restore_context(ctx); #if defined (TARGET_STM32L486xG) if( mode == MBEDTLS_AES_DECRYPT ) { - status = st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_KEYDERIVATION_DECRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); + status |= st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_KEYDERIVATION_DECRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); + // update IV + uint32_t tickstart; + tickstart = HAL_GetTick(); + while((ctx->hcryp_aes.Instance->SR & AES_SR_BUSY) != 0){ + if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { + return 1; // timeout: CRYP processor is busy + } + } + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; + ctx->hcryp_aes.Instance->CR &= ~AES_CR_EN; + *iv_ptr++ = ctx->hcryp_aes.Instance->IVR3; + *iv_ptr++ = ctx->hcryp_aes.Instance->IVR2; + *iv_ptr++ = ctx->hcryp_aes.Instance->IVR1; + *iv_ptr++ = ctx->hcryp_aes.Instance->IVR0; + } else { - status = st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_ENCRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); + status |= st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_ENCRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); + memcpy( iv, output, 16 ); } #else - ctx->hcryp_aes.Init.pInitVect = &iv[0]; if( mode == MBEDTLS_AES_DECRYPT ) { - status = HAL_CRYP_AESCBC_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10); + status |= HAL_CRYP_AESCBC_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10); } else { - status = HAL_CRYP_AESCBC_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10); + status |= HAL_CRYP_AESCBC_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10); } #endif + status |= st_cbc_save_context(ctx); + return( status ); } #endif /* MBEDTLS_CIPHER_MODE_CBC */ @@ -308,7 +391,6 @@ void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { - if (HAL_CRYP_AESECB_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10) !=0) { // error found to be returned } @@ -319,7 +401,6 @@ void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { - if(HAL_CRYP_AESECB_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10)) { // error found to be returned } diff --git a/features/mbedtls/targets/TARGET_STM/aes_alt.h b/features/mbedtls/targets/TARGET_STM/aes_alt.h index dbe4fdeec3..6964381660 100644 --- a/features/mbedtls/targets/TARGET_STM/aes_alt.h +++ b/features/mbedtls/targets/TARGET_STM/aes_alt.h @@ -30,6 +30,8 @@ #ifdef __cplusplus extern "C" { #endif + +#define ST_AES_TIMEOUT ((uint32_t) 3) /** * \brief AES context structure * @@ -43,6 +45,7 @@ typedef struct unsigned char aes_key[32]; /* Decryption key */ CRYP_HandleTypeDef hcryp_aes; uint32_t ctx_save_cr; /* save context for multi-instance */ + uint32_t save_iv[4]; /* save context for multi-instance */ } mbedtls_aes_context; From 56f5d7f70d832a6dfde27967258831c44cf48273 Mon Sep 17 00:00:00 2001 From: adustm Date: Thu, 14 Sep 2017 13:45:02 +0200 Subject: [PATCH 12/60] Use new interface of mbedtls instead of deprecated functions --- features/mbedtls/targets/TARGET_STM/aes_alt.c | 47 +++++++++++----- features/mbedtls/targets/TARGET_STM/aes_alt.h | 55 ++++++++++++++++--- 2 files changed, 81 insertions(+), 21 deletions(-) diff --git a/features/mbedtls/targets/TARGET_STM/aes_alt.c b/features/mbedtls/targets/TARGET_STM/aes_alt.c index ae10c919ca..e4b100aa35 100644 --- a/features/mbedtls/targets/TARGET_STM/aes_alt.c +++ b/features/mbedtls/targets/TARGET_STM/aes_alt.c @@ -1,5 +1,5 @@ /* - * Hardware aes collector for the STM32F4 family + * Hardware aes collector for the STM32F4 F7 and L4 family ******************************************************************************* * Copyright (c) 2017, STMicroelectronics * SPDX-License-Identifier: Apache-2.0 @@ -130,15 +130,17 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, /* allow multi-instance of CRYP use: restore context for CRYP hw module */ ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr; ctx->hcryp_aes.Phase = HAL_CRYP_PHASE_READY; + ctx->hcryp_aes.Init.DataType = CRYP_DATATYPE_8B; + ctx->hcryp_aes.Init.pKey = ctx->aes_key; if(mode == MBEDTLS_AES_DECRYPT) { /* AES decryption */ - ctx->hcryp_aes.Init.DataType = CRYP_DATATYPE_8B; - ctx->hcryp_aes.Init.pKey = ctx->aes_key; - mbedtls_aes_decrypt( ctx, input, output ); + if (mbedtls_internal_aes_decrypt( ctx, input, output )){ + return 1; + } } else { /* AES encryption */ - ctx->hcryp_aes.Init.DataType = CRYP_DATATYPE_8B; - ctx->hcryp_aes.Init.pKey = ctx->aes_key; - mbedtls_aes_encrypt( ctx, input, output ); + if (mbedtls_internal_aes_encrypt( ctx, input, output )) { + return 1; + } } /* allow multi-instance of CRYP use: save context for CRYP HW module CR */ ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; @@ -243,12 +245,12 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, unsigned char *output ) { int status = 0; - uint32_t *iv_ptr = (uint32_t *)&iv[0]; if( length % 16 ) return( MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH ); ctx->hcryp_aes.Init.pInitVect = &iv[0]; status |= st_cbc_restore_context(ctx); #if defined (TARGET_STM32L486xG) + uint32_t *iv_ptr = (uint32_t *)&iv[0]; if( mode == MBEDTLS_AES_DECRYPT ) { status |= st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_KEYDERIVATION_DECRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); // update IV @@ -387,24 +389,41 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, } #endif /* MBEDTLS_CIPHER_MODE_CTR */ -void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, +int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { if (HAL_CRYP_AESECB_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10) !=0) { - // error found to be returned + // error found + return 1; } + return 0; } +int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ) +{ + if(HAL_CRYP_AESECB_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10)) { + // error found + return 1; + } + return 0; +} + +void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ) +{ + mbedtls_internal_aes_encrypt( ctx, input, output ); +} + void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { - if(HAL_CRYP_AESECB_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10)) { - // error found to be returned - } + mbedtls_internal_aes_decrypt( ctx, input, output ); } - #endif /*MBEDTLS_AES_ALT*/ diff --git a/features/mbedtls/targets/TARGET_STM/aes_alt.h b/features/mbedtls/targets/TARGET_STM/aes_alt.h index 6964381660..7c8bc44c89 100644 --- a/features/mbedtls/targets/TARGET_STM/aes_alt.h +++ b/features/mbedtls/targets/TARGET_STM/aes_alt.h @@ -1,7 +1,7 @@ /* * aes_alt.h AES block cipher ******************************************************************************* - * Copyright (c) 2016, STMicroelectronics + * Copyright (c) 2017, STMicroelectronics * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -239,10 +239,12 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, * \param ctx AES context * \param input Plaintext block * \param output Output (ciphertext) block + * + * \return 0 if successful */ -void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, - const unsigned char input[16], - unsigned char output[16] ); +int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); /** * \brief Internal AES block decryption function @@ -252,10 +254,49 @@ void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, * \param ctx AES context * \param input Ciphertext block * \param output Output (plaintext) block + * + * \return 0 if successful */ -void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, - const unsigned char input[16], - unsigned char output[16] ); +int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Deprecated internal AES block encryption function + * without return value. + * + * \deprecated Superseded by mbedtls_aes_encrypt_ext() in 2.5.0 + * + * \param ctx AES context + * \param input Plaintext block + * \param output Output (ciphertext) block + */ +MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +/** + * \brief Deprecated internal AES block decryption function + * without return value. + * + * \deprecated Superseded by mbedtls_aes_decrypt_ext() in 2.5.0 + * + * \param ctx AES context + * \param input Ciphertext block + * \param output Output (plaintext) block + */ +MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ #ifdef __cplusplus } From 4f423ed50f1d11ed31a7927160a24cb524898797 Mon Sep 17 00:00:00 2001 From: adustm Date: Fri, 15 Sep 2017 14:59:08 +0200 Subject: [PATCH 13/60] Change after code review : standardize calls among ST families Check return values in alignment with MBEDTLS error codes --- features/mbedtls/targets/TARGET_STM/aes_alt.c | 161 ++++++++---------- features/mbedtls/targets/TARGET_STM/aes_alt.h | 4 +- 2 files changed, 75 insertions(+), 90 deletions(-) diff --git a/features/mbedtls/targets/TARGET_STM/aes_alt.c b/features/mbedtls/targets/TARGET_STM/aes_alt.c index e4b100aa35..15e57eb095 100644 --- a/features/mbedtls/targets/TARGET_STM/aes_alt.c +++ b/features/mbedtls/targets/TARGET_STM/aes_alt.c @@ -1,5 +1,5 @@ /* - * Hardware aes collector for the STM32F4 F7 and L4 family + * Hardware aes implementation for STM32F4 STM32F7 and STM32L4 families ******************************************************************************* * Copyright (c) 2017, STMicroelectronics * SPDX-License-Identifier: Apache-2.0 @@ -135,11 +135,11 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, if(mode == MBEDTLS_AES_DECRYPT) { /* AES decryption */ if (mbedtls_internal_aes_decrypt( ctx, input, output )){ - return 1; + return ST_ERR_AES_BUSY; } } else { /* AES encryption */ if (mbedtls_internal_aes_encrypt( ctx, input, output )) { - return 1; + return ST_ERR_AES_BUSY; } } /* allow multi-instance of CRYP use: save context for CRYP HW module CR */ @@ -155,88 +155,47 @@ static int st_cbc_restore_context(mbedtls_aes_context *ctx){ tickstart = HAL_GetTick(); while((ctx->hcryp_aes.Instance->SR & AES_SR_BUSY) != 0){ if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { - return 1; // timeout: CRYP processor is busy + return ST_ERR_AES_BUSY; // timeout: CRYP processor is busy } } /* allow multi-instance of CRYP use: restore context for CRYP hw module */ ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr; return 0; } -static int st_cbc_save_context(mbedtls_aes_context *ctx){ - uint32_t tickstart; - - tickstart = HAL_GetTick(); - while((ctx->hcryp_aes.Instance->SR & AES_SR_BUSY) != 0){ - if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { - return 1; // timeout: CRYP processor is busy - } - } - /* allow multi-instance of CRYP use: save context for CRYP HW module CR */ - ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; - return 0; -} static int st_hal_cryp_cbc( mbedtls_aes_context *ctx, uint32_t opmode, size_t length, unsigned char iv[16], uint8_t *input, uint8_t *output) { - int status = 0; ctx->hcryp_aes.Init.pInitVect = &iv[0]; // used in process, not in the init /* At this moment only, we know we have CBC mode: Re-initialize AES IP with proper parameters and apply key and IV for multi context usecase */ if (HAL_CRYP_DeInit(&ctx->hcryp_aes) != HAL_OK) - return HAL_ERROR; + return ST_ERR_AES_BUSY; ctx->hcryp_aes.Init.OperatingMode = opmode; ctx->hcryp_aes.Init.ChainingMode = CRYP_CHAINMODE_AES_CBC; ctx->hcryp_aes.Init.KeyWriteFlag = CRYP_KEY_WRITE_ENABLE; if (HAL_CRYP_Init(&ctx->hcryp_aes) != HAL_OK) - return HAL_ERROR; + return ST_ERR_AES_BUSY; - status = HAL_CRYPEx_AES(&ctx->hcryp_aes, input, length, output, 10); - - return status; + if(HAL_CRYPEx_AES(&ctx->hcryp_aes, input, length, output, 10) != 0) + return ST_ERR_AES_BUSY; + return 0; } -#else +#else /* STM32F4 and STM32F7 */ static int st_cbc_restore_context(mbedtls_aes_context *ctx){ - uint32_t tickstart; - tickstart = HAL_GetTick(); - while((ctx->hcryp_aes.Instance->SR & (CRYP_SR_IFEM | CRYP_SR_OFNE | CRYP_SR_BUSY)) != CRYP_SR_IFEM){ - if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { - return 1; // timeout: CRYP processor is busy - } - } - ctx->hcryp_aes.Instance->CR &= ~CRYP_CR_CRYPEN; - /* save initvector for multi-instance use of CRYP */ - ctx->hcryp_aes.Instance->IV1RR = ctx->save_iv[3]; - ctx->hcryp_aes.Instance->IV1LR = ctx->save_iv[2]; - ctx->hcryp_aes.Instance->IV0RR = ctx->save_iv[1]; - ctx->hcryp_aes.Instance->IV0LR = ctx->save_iv[0]; - ctx->hcryp_aes.Phase = HAL_CRYP_PHASE_READY; /* allow multi-instance of CRYP use: restore context for CRYP hw module */ ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr; + /* Re-initialize AES processor with proper parameters + and (re-)apply key and IV for multi context usecases */ + if (HAL_CRYP_DeInit(&ctx->hcryp_aes) != HAL_OK) + return ST_ERR_AES_BUSY; + if (HAL_CRYP_Init(&ctx->hcryp_aes) != HAL_OK) + return ST_ERR_AES_BUSY; return 0; } -static int st_cbc_save_context(mbedtls_aes_context *ctx){ - uint32_t tickstart; - tickstart = HAL_GetTick(); - while((ctx->hcryp_aes.Instance->SR & (CRYP_SR_IFEM | CRYP_SR_OFNE | CRYP_SR_BUSY)) != CRYP_SR_IFEM){ - if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { - return 1; // timeout: CRYP processor is busy - } - } - /* allow multi-instance of CRYP use: save context for CRYP HW module CR */ - ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; - ctx->hcryp_aes.Instance->CR &= ~CRYP_CR_CRYPEN; - /* save initvector for multi-instance use of CRYP */ - ctx->save_iv[3] = ctx->hcryp_aes.Instance->IV1RR; - ctx->save_iv[2] = ctx->hcryp_aes.Instance->IV1LR; - ctx->save_iv[1] = ctx->hcryp_aes.Instance->IV0RR; - ctx->save_iv[0] = ctx->hcryp_aes.Instance->IV0LR; - if ((ctx->ctx_save_cr & CRYP_CR_CRYPEN) == CRYP_CR_CRYPEN) { - ctx->hcryp_aes.Instance->CR &= CRYP_CR_CRYPEN; - } - return 0; -} + #endif /* TARGET_STM32L486xG */ + int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, int mode, size_t length, @@ -244,45 +203,66 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, const unsigned char *input, unsigned char *output ) { - int status = 0; + uint32_t tickstart; + uint32_t *iv_ptr = (uint32_t *)&iv[0]; if( length % 16 ) return( MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH ); ctx->hcryp_aes.Init.pInitVect = &iv[0]; - status |= st_cbc_restore_context(ctx); + if (st_cbc_restore_context(ctx) != 0) + return (ST_ERR_AES_BUSY); + #if defined (TARGET_STM32L486xG) - uint32_t *iv_ptr = (uint32_t *)&iv[0]; + if( mode == MBEDTLS_AES_DECRYPT ) { - status |= st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_KEYDERIVATION_DECRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); - // update IV - uint32_t tickstart; + if (st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_KEYDERIVATION_DECRYPT, length, iv, (uint8_t *)input, (uint8_t *)output) != 0) + return ST_ERR_AES_BUSY; + /* Save the internal IV vector for multi context purpose */ tickstart = HAL_GetTick(); while((ctx->hcryp_aes.Instance->SR & AES_SR_BUSY) != 0){ if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { - return 1; // timeout: CRYP processor is busy + return ST_ERR_AES_BUSY; // timeout: CRYP processor is busy } } - ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; // save here before overwritten ctx->hcryp_aes.Instance->CR &= ~AES_CR_EN; *iv_ptr++ = ctx->hcryp_aes.Instance->IVR3; *iv_ptr++ = ctx->hcryp_aes.Instance->IVR2; *iv_ptr++ = ctx->hcryp_aes.Instance->IVR1; *iv_ptr++ = ctx->hcryp_aes.Instance->IVR0; - } else { - status |= st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_ENCRYPT, length, iv, (uint8_t *)input, (uint8_t *)output); - memcpy( iv, output, 16 ); + if (st_hal_cryp_cbc(ctx, CRYP_ALGOMODE_ENCRYPT, length, iv, (uint8_t *)input, (uint8_t *)output) != 0) + return ST_ERR_AES_BUSY; + memcpy( iv, output, 16 ); /* current output is the IV vector for the next call */ + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; } + #else - - if( mode == MBEDTLS_AES_DECRYPT ) { - status |= HAL_CRYP_AESCBC_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10); - } else { - status |= HAL_CRYP_AESCBC_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10); - } -#endif - status |= st_cbc_save_context(ctx); - return( status ); + if( mode == MBEDTLS_AES_DECRYPT ) { + if (HAL_CRYP_AESCBC_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10) != HAL_OK) + return ST_ERR_AES_BUSY; + /* Save the internal IV vector for multi context purpose */ + tickstart = HAL_GetTick(); + while((ctx->hcryp_aes.Instance->SR & (CRYP_SR_IFEM | CRYP_SR_OFNE | CRYP_SR_BUSY)) != CRYP_SR_IFEM){ + if ((HAL_GetTick() - tickstart) > ST_AES_TIMEOUT) { + return ST_ERR_AES_BUSY; // timeout: CRYP processor is busy + } + } + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; // save here before overwritten + ctx->hcryp_aes.Instance->CR &= ~CRYP_CR_CRYPEN; + *iv_ptr++ = ctx->hcryp_aes.Instance->IV0LR; + *iv_ptr++ = ctx->hcryp_aes.Instance->IV0RR; + *iv_ptr++ = ctx->hcryp_aes.Instance->IV1LR; + *iv_ptr++ = ctx->hcryp_aes.Instance->IV1RR; + } else { + if (HAL_CRYP_AESCBC_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, length, (uint8_t *)output, 10) != HAL_OK) + return ST_ERR_AES_BUSY; + memcpy( iv, output, 16 ); /* current output is the IV vector for the next call */ + ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; + } + +#endif + return 0; } #endif /* MBEDTLS_CIPHER_MODE_CBC */ @@ -301,7 +281,8 @@ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, if( mode == MBEDTLS_AES_DECRYPT ) { while( length-- ) { if( n == 0 ) - mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); + if (mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ) != 0) + return ST_ERR_AES_BUSY; c = *input++; *output++ = (unsigned char)( c ^ iv[n] ); @@ -312,7 +293,8 @@ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, } else { while( length-- ) { if( n == 0 ) - mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); + if (mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ) != 0) + return ST_ERR_AES_BUSY; iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ ); @@ -338,7 +320,8 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, while( length-- ) { memcpy( ov, iv, 16 ); - mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); + if (mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ) != 0) + return ST_ERR_AES_BUSY; if( mode == MBEDTLS_AES_DECRYPT ) ov[16] = *input; @@ -371,7 +354,8 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, while( length-- ) { if( n == 0 ) { - mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, nonce_counter, stream_block ); + if (mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, nonce_counter, stream_block ) != 0) + return ST_ERR_AES_BUSY; for( i = 16; i > 0; i-- ) if( ++nonce_counter[i - 1] != 0 ) @@ -393,9 +377,9 @@ int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { - if (HAL_CRYP_AESECB_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10) !=0) { + if (HAL_CRYP_AESECB_Encrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10) != HAL_OK) { // error found - return 1; + return ST_ERR_AES_BUSY; } return 0; @@ -405,13 +389,14 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { - if(HAL_CRYP_AESECB_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10)) { + if(HAL_CRYP_AESECB_Decrypt(&ctx->hcryp_aes, (uint8_t *)input, 16, (uint8_t *)output, 10) != HAL_OK) { // error found - return 1; + return ST_ERR_AES_BUSY; } return 0; } +#if !defined(MBEDTLS_DEPRECATED_REMOVED) void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) @@ -425,5 +410,5 @@ void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, { mbedtls_internal_aes_decrypt( ctx, input, output ); } - +#endif /* MBEDTLS_DEPRECATED_REMOVED */ #endif /*MBEDTLS_AES_ALT*/ diff --git a/features/mbedtls/targets/TARGET_STM/aes_alt.h b/features/mbedtls/targets/TARGET_STM/aes_alt.h index 7c8bc44c89..120c9af5f1 100644 --- a/features/mbedtls/targets/TARGET_STM/aes_alt.h +++ b/features/mbedtls/targets/TARGET_STM/aes_alt.h @@ -31,7 +31,8 @@ extern "C" { #endif -#define ST_AES_TIMEOUT ((uint32_t) 3) +#define ST_AES_TIMEOUT ((uint32_t) 0xFF) /* 255 ms timeout for the crypto processor */ +#define ST_ERR_AES_BUSY (-0x0023) /* Crypto processor is busy, timeout occured */ /** * \brief AES context structure * @@ -45,7 +46,6 @@ typedef struct unsigned char aes_key[32]; /* Decryption key */ CRYP_HandleTypeDef hcryp_aes; uint32_t ctx_save_cr; /* save context for multi-instance */ - uint32_t save_iv[4]; /* save context for multi-instance */ } mbedtls_aes_context; From 843da7b8cb16b0e3958744b8f641c63e57924984 Mon Sep 17 00:00:00 2001 From: Andres Amaya Garcia Date: Tue, 12 Sep 2017 13:39:04 +0100 Subject: [PATCH 14/60] mbedtls: Disable MD5, SHA1, SHA256 HW ACC for STM32F439xI STM32F439xI-family MD5, SHA1 and SHA256 hardware acceleration occasionally produces incorrect output (#5079). Don't enable MD5, SHA1 and SHA256 HW acceleration on STM32F439xI-family targets by default until issue #5079 is fixed. --- .../TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h index dfbc82055e..03ddf8f8ac 100644 --- a/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h +++ b/features/mbedtls/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/mbedtls_device.h @@ -22,10 +22,12 @@ #define MBEDTLS_AES_ALT -#define MBEDTLS_SHA256_ALT +/* FIXME: Don't enable SHA1, SHA256 and MD5 hardware acceleration until issue + * #5079 is fixed. (https://github.com/ARMmbed/mbed-os/issues/5079) */ +/* #define MBEDTLS_SHA256_ALT */ -#define MBEDTLS_SHA1_ALT +/* #define MBEDTLS_SHA1_ALT */ -#define MBEDTLS_MD5_ALT +/* #define MBEDTLS_MD5_ALT */ #endif /* MBEDTLS_DEVICE_H */ From 614bbe7ae5f2d665f82cf171bffec13c1e510a61 Mon Sep 17 00:00:00 2001 From: Russ Butler Date: Wed, 13 Sep 2017 19:48:33 -0500 Subject: [PATCH 15/60] Remove direct use of us and lp ticker from tests Remove the direct use of the microsecond and low power ticker from the tests. This enforces that sleep mode is properly locked when using timers. Furthermore, this prepares the codebase for new ticker changes which allow differing clock frequencies and timer bit widths. --- TESTS/mbed_drivers/lp_timeout/main.cpp | 21 +++++----- TESTS/mbed_hal/lp_ticker/main.cpp | 40 ++++++++++---------- TESTS/mbedmicro-rtos-mbed/mutex/main.cpp | 5 ++- TESTS/mbedmicro-rtos-mbed/queue/main.cpp | 20 ++++++---- TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp | 10 +++-- TESTS/mbedmicro-rtos-mbed/threads/main.cpp | 5 ++- 6 files changed, 55 insertions(+), 46 deletions(-) diff --git a/TESTS/mbed_drivers/lp_timeout/main.cpp b/TESTS/mbed_drivers/lp_timeout/main.cpp index f3b5b63c6b..df56388dc5 100644 --- a/TESTS/mbed_drivers/lp_timeout/main.cpp +++ b/TESTS/mbed_drivers/lp_timeout/main.cpp @@ -23,7 +23,6 @@ #include "greentea-client/test_env.h" #include "mbed.h" -#include "us_ticker_api.h" using namespace utest::v1; @@ -42,6 +41,7 @@ void cb_done() { void lp_timeout_1s_deepsleep(void) { complete = false; + LowPowerTimer timer; /* * Since deepsleep() may shut down the UART peripheral, we wait for 10ms @@ -54,33 +54,32 @@ void lp_timeout_1s_deepsleep(void) wait_ms(10); /* - * We use here lp_ticker_read() instead of us_ticker_read() for start and + * We use here the low power timer instead of microsecond timer for start and * end because the microseconds timer might be disable during deepsleep. */ - timestamp_t start = lp_ticker_read(); + timer.start(); lpt.attach(&cb_done, 1); deepsleep(); while (!complete); - timestamp_t end = lp_ticker_read(); /* It takes longer to wake up from deep sleep */ - TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, end - start); + TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, timer.read_us()); TEST_ASSERT_TRUE(complete); } void lp_timeout_1s_sleep(void) { complete = false; + Timer timer; + timer.start(); sleep_manager_lock_deep_sleep(); - timestamp_t start = us_ticker_read(); lpt.attach(&cb_done, 1); sleep(); while (!complete); - timestamp_t end = us_ticker_read(); sleep_manager_unlock_deep_sleep(); - TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, end - start); + TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, timer.read_us()); TEST_ASSERT_TRUE(complete); } #endif /* DEVICE_SLEEP */ @@ -88,14 +87,14 @@ void lp_timeout_1s_sleep(void) void lp_timeout_us(uint32_t delay_us, uint32_t tolerance) { complete = false; + Timer timer; + timer.start(); - timestamp_t start = us_ticker_read(); lpt.attach_us(&cb_done, delay_us); while (!complete); - timestamp_t end = us_ticker_read(); /* Using RTC which is less accurate */ - TEST_ASSERT_UINT32_WITHIN(tolerance, delay_us, end - start); + TEST_ASSERT_UINT32_WITHIN(tolerance, delay_us, timer.read_us()); TEST_ASSERT_TRUE(complete); } diff --git a/TESTS/mbed_hal/lp_ticker/main.cpp b/TESTS/mbed_hal/lp_ticker/main.cpp index 05d497fa93..c609c57b8a 100644 --- a/TESTS/mbed_hal/lp_ticker/main.cpp +++ b/TESTS/mbed_hal/lp_ticker/main.cpp @@ -23,17 +23,16 @@ #include "greentea-client/test_env.h" #include "mbed.h" -#include "us_ticker_api.h" #include "lp_ticker_api.h" -#include "TimerEvent.h" using namespace utest::v1; static volatile bool complete; -static volatile timestamp_t complete_timestamp; +static volatile timestamp_t complete_time; static ticker_event_t delay_event; static const ticker_data_t *lp_ticker_data = get_lp_ticker_data(); - +static Timer timer; +static LowPowerTimer lp_timer; /* Timeouts are quite arbitrary due to large number of boards with varying level of accuracy */ #define LONG_TIMEOUT (100000) @@ -41,7 +40,7 @@ static const ticker_data_t *lp_ticker_data = get_lp_ticker_data(); void cb_done(uint32_t id) { if ((uint32_t)&delay_event == id) { - complete_timestamp = us_ticker_read(); + complete_time = timer.read_us(); complete = true; } else { // Normal ticker handling @@ -51,7 +50,7 @@ void cb_done(uint32_t id) { void cb_done_deepsleep(uint32_t id) { if ((uint32_t)&delay_event == id) { - complete_timestamp = lp_ticker_read(); + complete_time = lp_timer.read_us(); complete = true; } else { // Normal ticker handling @@ -66,14 +65,15 @@ void lp_ticker_delay_us(uint32_t delay_us, uint32_t tolerance) ticker_set_handler(lp_ticker_data, cb_done); ticker_remove_event(lp_ticker_data, &delay_event); - delay_ts = lp_ticker_read() + delay_us; + delay_ts = ticker_read(lp_ticker_data) + delay_us; - timestamp_t start = us_ticker_read(); + timer.reset(); + timer.start(); ticker_insert_event(lp_ticker_data, &delay_event, delay_ts, (uint32_t)&delay_event); while (!complete); - timestamp_t end = complete_timestamp; + timer.stop(); - TEST_ASSERT_UINT32_WITHIN(tolerance, delay_us, end - start); + TEST_ASSERT_UINT32_WITHIN(tolerance, delay_us, complete_time); TEST_ASSERT_TRUE(complete); } @@ -95,19 +95,20 @@ void lp_ticker_1s_deepsleep() ticker_set_handler(lp_ticker_data, cb_done_deepsleep); ticker_remove_event(lp_ticker_data, &delay_event); - delay_ts = lp_ticker_read() + 1000000; + delay_ts = ticker_read(lp_ticker_data) + 1000000; /* - * We use here lp_ticker_read() instead of us_ticker_read() for start and + * We use here the low power timer instead of microsecond timer for start and * end because the microseconds timer might be disable during deepsleep. */ - timestamp_t start = lp_ticker_read(); + lp_timer.reset(); + lp_timer.start(); ticker_insert_event(lp_ticker_data, &delay_event, delay_ts, (uint32_t)&delay_event); deepsleep(); while (!complete); - timestamp_t end = complete_timestamp; + lp_timer.stop(); - TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, end - start); + TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, complete_time); TEST_ASSERT_TRUE(complete); } @@ -118,17 +119,18 @@ void lp_ticker_1s_sleep() ticker_set_handler(lp_ticker_data, cb_done); ticker_remove_event(lp_ticker_data, &delay_event); - delay_ts = lp_ticker_read() + 1000000; + delay_ts = ticker_read(lp_ticker_data) + 1000000; sleep_manager_lock_deep_sleep(); - timestamp_t start = us_ticker_read(); + timer.reset(); + timer.start(); ticker_insert_event(lp_ticker_data, &delay_event, delay_ts, (uint32_t)&delay_event); sleep(); while (!complete); - timestamp_t end = complete_timestamp; + timer.stop(); sleep_manager_unlock_deep_sleep(); - TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, end - start); + TEST_ASSERT_UINT32_WITHIN(LONG_TIMEOUT, 1000000, complete_time); TEST_ASSERT_TRUE(complete); } #endif /* DEVICE_SLEEP */ diff --git a/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp b/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp index a3aef568b0..0506a66dbd 100644 --- a/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp @@ -191,11 +191,12 @@ void test_dual_thread_lock_trylock_thread(Mutex *mutex) void test_dual_thread_lock_lock_thread(Mutex *mutex) { - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); osStatus stat = mutex->lock(TEST_DELAY); TEST_ASSERT_EQUAL(osErrorTimeout, stat); - TEST_ASSERT_UINT32_WITHIN(5000, TEST_DELAY*1000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(5000, TEST_DELAY*1000, timer.read_us()); } /** Test dual thread lock diff --git a/TESTS/mbedmicro-rtos-mbed/queue/main.cpp b/TESTS/mbedmicro-rtos-mbed/queue/main.cpp index 374dc8662c..d275784dbd 100644 --- a/TESTS/mbedmicro-rtos-mbed/queue/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/queue/main.cpp @@ -135,11 +135,12 @@ void test_get_empty_no_timeout() void test_get_empty_timeout() { Queue q; - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); osEvent evt = q.get(50); TEST_ASSERT_EQUAL(osEventTimeout, evt.status); - TEST_ASSERT_UINT32_WITHIN(5000, 50000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(5000, 50000, timer.read_us()); } /** Test get empty wait forever @@ -157,12 +158,13 @@ void test_get_empty_wait_forever() t.start(callback(thread_put_uint_msg, &q)); - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); osEvent evt = q.get(); TEST_ASSERT_EQUAL(osEventMessage, evt.status); TEST_ASSERT_EQUAL(TEST_UINT_MSG, evt.value.v); - TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, timer.read_us()); } /** Test put full no timeout @@ -195,11 +197,12 @@ void test_put_full_timeout() osStatus stat = q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT); TEST_ASSERT_EQUAL(osOK, stat); - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); stat = q.put((uint32_t*) TEST_UINT_MSG, TEST_TIMEOUT); TEST_ASSERT_EQUAL(osErrorTimeout, stat); - TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, timer.read_us()); } /** Test put full wait forever @@ -220,10 +223,11 @@ void test_put_full_waitforever() osStatus stat = q.put((uint32_t*) TEST_UINT_MSG); TEST_ASSERT_EQUAL(osOK, stat); - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); stat = q.put((uint32_t*) TEST_UINT_MSG, osWaitForever); TEST_ASSERT_EQUAL(osOK, stat); - TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(TEST_TIMEOUT * 100, TEST_TIMEOUT * 1000, timer.read_us()); t.join(); } diff --git a/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp b/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp index 33f50204c9..691589d0e8 100644 --- a/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp @@ -152,7 +152,8 @@ void test_timeout() Semaphore sem(0); osStatus res; - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); res = t.start(callback(timeout_thread, &sem)); TEST_ASSERT_EQUAL(osOK, res); Thread::wait(SHORT_WAIT); @@ -160,7 +161,7 @@ void test_timeout() TEST_ASSERT_EQUAL(Thread::WaitingSemaphore, t.get_state()); t.join(); - TEST_ASSERT_UINT32_WITHIN(5000, 30000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(5000, 30000, timer.read_us()); } /** Test no timeouts @@ -180,12 +181,13 @@ void test_no_timeout() { Semaphore sem(T); - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); int32_t cnt = sem.wait(0); TEST_ASSERT_EQUAL(T, cnt); - TEST_ASSERT_UINT32_WITHIN(5000, 0, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(5000, 0, timer.read_us()); } /** Test multiple tokens wait diff --git a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp index 1ece21524d..7423bd957c 100644 --- a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp @@ -377,11 +377,12 @@ void test_thread_stack_info() { then the thread sleeps for given amount of time */ void test_thread_wait() { - uint32_t start = us_ticker_read(); + Timer timer; + timer.start(); Thread::wait(150); - TEST_ASSERT_UINT32_WITHIN(50000, 150000, us_ticker_read() - start); + TEST_ASSERT_UINT32_WITHIN(50000, 150000, timer.read_us()); } /** Testing thread name From 8c10a627f66158c6907c0191d0550dbe2cfc2804 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Mon, 28 Aug 2017 13:58:53 -0500 Subject: [PATCH 16/60] bd: Changed BlockDevice erase to default as no-op This should help with confusion around devices that don't have a physical erase operation, such as SD cards and spinny disks. --- features/filesystem/bd/BlockDevice.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/features/filesystem/bd/BlockDevice.h b/features/filesystem/bd/BlockDevice.h index a45dfee298..a088b179d1 100644 --- a/features/filesystem/bd/BlockDevice.h +++ b/features/filesystem/bd/BlockDevice.h @@ -91,7 +91,10 @@ public: * @param size Size to erase in bytes, must be a multiple of erase block size * @return 0 on success, negative error code on failure */ - virtual int erase(bd_addr_t addr, bd_size_t size) = 0; + virtual int erase(bd_addr_t addr, bd_size_t size) + { + return 0; + } /** Get the size of a readable block * @@ -111,7 +114,10 @@ public: * @return Size of a eraseable block in bytes * @note Must be a multiple of the program size */ - virtual bd_size_t get_erase_size() const = 0; + virtual bd_size_t get_erase_size() const + { + return get_program_size(); + } /** Get the total size of the underlying device * From 55b992f130b847d2851a978e55a53de7930d4be5 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Mon, 28 Aug 2017 14:06:18 -0500 Subject: [PATCH 17/60] bd: Added trim function to let filesystems give erase hints to FTLs --- features/filesystem/bd/BlockDevice.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/features/filesystem/bd/BlockDevice.h b/features/filesystem/bd/BlockDevice.h index a088b179d1..da46c7b727 100644 --- a/features/filesystem/bd/BlockDevice.h +++ b/features/filesystem/bd/BlockDevice.h @@ -96,6 +96,22 @@ public: return 0; } + /** Mark blocks as no longer in use + * + * This function provides a hint to the underlying block device that a region of blocks + * is no longer in use and may be erased without side effects. Erase must still be called + * before programming, but trimming allows flash-translation-layers to schedule erases when + * the device is not busy. + * + * @param addr Address of block to mark as unused + * @param size Size to mark as unused in bytes, must be a multiple of erase block size + * @return 0 on success, negative error code on failure + */ + virtual int trim(bd_addr_t addr, bd_size_t size) + { + return 0; + } + /** Get the size of a readable block * * @return Size of a readable block in bytes From e4f368d89e9eb0de1f9ff1489e7fca32c1452436 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Mon, 28 Aug 2017 14:33:34 -0500 Subject: [PATCH 18/60] fatfs: Adopted the trim function in the FAT filesystem --- features/filesystem/fat/ChaN/ffconf.h | 2 +- features/filesystem/fat/FATFileSystem.cpp | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/features/filesystem/fat/ChaN/ffconf.h b/features/filesystem/fat/ChaN/ffconf.h index 9d461c1e26..cab80cf21b 100644 --- a/features/filesystem/fat/ChaN/ffconf.h +++ b/features/filesystem/fat/ChaN/ffconf.h @@ -171,7 +171,7 @@ / disk_ioctl() function. */ -#define _USE_TRIM 0 +#define _USE_TRIM 1 /* This option switches ATA-TRIM feature. (0:Disable or 1:Enable) / To enable Trim feature, also CTRL_TRIM command should be implemented to the / disk_ioctl() function. */ diff --git a/features/filesystem/fat/FATFileSystem.cpp b/features/filesystem/fat/FATFileSystem.cpp index 20e981099e..1829bbda8e 100644 --- a/features/filesystem/fat/FATFileSystem.cpp +++ b/features/filesystem/fat/FATFileSystem.cpp @@ -244,6 +244,15 @@ DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff) case GET_BLOCK_SIZE: *((DWORD*)buff) = 1; // default when not known return RES_OK; + case CTRL_TRIM: + if (_ffs[pdrv] == NULL) { + return RES_NOTRDY; + } else { + DWORD *sectors = (DWORD*)buff; + DWORD ssize = disk_get_sector_size(pdrv); + int err = _ffs[pdrv]->trim(sectors[0]*ssize, (sectors[1]-sectors[0]+1)*ssize); + return err ? RES_PARERR : RES_OK; + } } return RES_PARERR; From a658230956bada40ed917a465ccc388364379dd1 Mon Sep 17 00:00:00 2001 From: Martin Kojtal <0xc0170@gmail.com> Date: Thu, 31 Aug 2017 14:39:03 +0100 Subject: [PATCH 19/60] flash: add note about program size Program size - the writable page size that flash controller supports. Plus fix program page description - multiple pages program --- drivers/FlashIAP.h | 1 + hal/flash_api.h | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/FlashIAP.h b/drivers/FlashIAP.h index dd7b167e84..a6acc1bed9 100644 --- a/drivers/FlashIAP.h +++ b/drivers/FlashIAP.h @@ -112,6 +112,7 @@ public: /** Get the program page size * + * The page size defines the writable page size * @return Size of a program page in bytes */ uint32_t get_page_size() const; diff --git a/hal/flash_api.h b/hal/flash_api.h index 1804250fd8..4231c083ba 100644 --- a/hal/flash_api.h +++ b/hal/flash_api.h @@ -75,9 +75,9 @@ int32_t flash_erase_sector(flash_t *obj, uint32_t address); */ int32_t flash_read(flash_t *obj, uint32_t address, uint8_t *data, uint32_t size); -/** Program one page starting at defined address +/** Program pages starting at defined address * - * The page should be at page boundary, should not cross multiple sectors. + * The pages should not cross multiple sectors. * This function does not do any check for address alignments or if size is aligned to a page size. * @param obj The flash object * @param address The sector starting address @@ -97,6 +97,7 @@ uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address); /** Get page size * + * The page size defines the writable page size * @param obj The flash object * @return The size of a page */ From e5bc908b465729d522c48309240811e2073831c2 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 29 Aug 2017 21:48:10 +0100 Subject: [PATCH 20/60] initial IAP routine --- .../TARGET_LPC176X/device/flash_api.c | 191 ++++++++++++++---- targets/TARGET_NXP/TARGET_LPC176X/objects.h | 5 +- 2 files changed, 155 insertions(+), 41 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index 0b140350bf..5dddff4e68 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -5,7 +5,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,54 +14,165 @@ * limitations under the License. */ -#include "flash_api.h" -#include "platform/mbed_critical.h" - -// This file is automatically generated +#include "mbed_critical.h" #if DEVICE_FLASH +#include "mbed_assert.h" +#include "cmsis.h" -#include "flash_data.h" -// This is a flash algo binary blob. It is PIC (position independent code) that should be stored in RAM -static uint32_t FLASH_ALGO[] = { - 0x28100b00, 0x210ed302, 0x00d0eb01, 0xf44f4770, 0xfbb1707a, 0x4933f0f0, 0x60084449, 0x20014932, - 0x20006408, 0x20004770, 0xe92d4770, 0xf7ff41f0, 0x4d2effe7, 0x444d4604, 0xe9c52032, 0xf1050400, - 0x4e2b0114, 0x4628460f, 0x47b060ac, 0xb9686968, 0xe9c52034, 0x48230400, 0x444860ac, 0x68004639, - 0x462860e8, 0x696847b0, 0xd0002800, 0xe8bd2001, 0xe92d81f0, 0x461441f0, 0xd10e0006, 0x0100e9d4, - 0xe9d44408, 0x44111202, 0x69214408, 0x69614408, 0x69a14408, 0x42404408, 0x463061e0, 0xffb0f7ff, - 0x21324d12, 0x4f12444d, 0x1000e9c5, 0x0114f105, 0x468860a8, 0x47b84628, 0xb9806968, 0xe9c52033, - 0xf44f0600, 0xe9c56080, 0x48064002, 0x44484641, 0x61286800, 0x47b84628, 0x28006968, 0x2001d0c7, - 0x0000e7c5, 0x00000004, 0x400fc000, 0x00000008, 0x1fff1ff1, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 -}; + #define MEMMAP (*((volatile unsigned long *) 0x400FC040)) -static const flash_algo_t flash_algo_config = { - .init = 0xf, - .uninit = 0x27, - .erase_sector = 0x2b, - .program_page = 0x73, - .static_base = 0xf4, - .algo_blob = FLASH_ALGO -}; + #define PLL0CON (*((volatile unsigned long *) 0x400FC080)) + #define PLL0CFG (*((volatile unsigned long *) 0x400FC084)) + #define PLL0STAT (*((volatile unsigned long *) 0x400FC088)) + #define PLL0FEED (*((volatile unsigned long *) 0x400FC08C)) + #define CCLKSEL (*((volatile unsigned long *) 0x400FC104)) + #define CLKSRCSEL (*((volatile unsigned long *) 0x400FC10C)) -static const sector_info_t sectors_info[] = { - {0x0, 0x1000}, - {0x10000, 0x8000}, -}; +#define STACK_SIZE 64 // Stack Size -static const flash_target_config_t flash_target_config = { - .page_size = 0x400, - .flash_start = 0x0, - .flash_size = 0x80000, - .sectors = sectors_info, - .sector_info_count = sizeof(sectors_info) / sizeof(sector_info_t) -}; +#define SET_VALID_CODE 1 // Set Valid User Code Signature +/* IAP Call */ +typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); +#define IAP_Call ((IAP_Entry) 0x1FFF1FF1) -void flash_set_target_config(flash_t *obj) +typedef struct flash_s flash_t; +unsigned long CCLK; // CCLK in kHz + + +struct sIAP { // IAP Structure + unsigned long cmd; // Command + unsigned long par[4]; // Parameters + unsigned long stat; // Status + unsigned long res[2]; // Result +} IAP; + +/* + * Get Sector Number + * Parameter: address: Sector Address + * Return Value: Sector Number + */ + +unsigned long GetSecNum (unsigned long address) { + unsigned long n; + + + n = address >> 12; // 4kB Sector + if (n >= 0x10) { + n = 0x0E + (n >> 3); // 32kB Sector + } + + + return (n); // Sector Number +} +int32_t flash_init(flash_t *obj) { - obj->flash_algo = &flash_algo_config; - obj->target_config = &flash_target_config; + CCLK = SystemCoreClock / 1000; // CCLK value is in kHz, clk in Hz + + MEMMAP = 0x01; // User Flash Mode + + return (0); +} + +int32_t flash_free(flash_t *obj) +{ + return 0; +} + +int32_t flash_erase_sector(flash_t *obj, uint32_t address) +{ + unsigned long n; + + n = GetSecNum(address); // Get Sector Number + + IAP.cmd = 50; // Prepare Sector for Erase + IAP.par[0] = n; // Start Sector + IAP.par[1] = n; // End Sector + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + if (IAP.stat) return (1); // Command Failed + + IAP.cmd = 52; // Erase Sector + IAP.par[0] = n; // Start Sector + IAP.par[1] = n; // End Sector + IAP.par[2] = CCLK; // CCLK in kHz + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + if (IAP.stat) return (1); // Command Failed + + return (0); // Finished without Errors + +} + +/* IAP Call */ +typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); +#define IAP_Call ((IAP_Entry) 0x1FFF1FF1) + + +int32_t flash_program_page(flash_t *obj, uint32_t address, + const uint8_t *data, uint32_t size) +{ + unsigned long n; + +#if SET_VALID_CODE != 0 // Set valid User Code Signature + if (address == 0) { // Check for Vector Table + n = *((unsigned long *)(data + 0x00)) + + *((unsigned long *)(data + 0x04)) + + *((unsigned long *)(data + 0x08)) + + *((unsigned long *)(data + 0x0C)) + + *((unsigned long *)(data + 0x10)) + + *((unsigned long *)(data + 0x14)) + + *((unsigned long *)(data + 0x18)); + *((unsigned long *)(data + 0x1C)) = 0 - n; // Signature at Reserved Vector + } +#endif + + n = GetSecNum(address); // Get Sector Number + + IAP.cmd = 50; // Prepare Sector for Write + IAP.par[0] = n; // Start Sector + IAP.par[1] = n; // End Sector + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + if (IAP.stat) return (1); // Command Failed + + IAP.cmd = 51; // Copy RAM to Flash + IAP.par[0] = address; // Destination Flash Address + IAP.par[1] = (unsigned long)data; // Source RAM Address + + IAP.par[2] = 1024; // Fixed Page Size + IAP.par[3] = CCLK; // CCLK in kHz + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + if (IAP.stat) return (1); // Command Failed + + return (0); // Finished without Errors +} + +uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address) +{ + + if(GetSecNum(address)>=0x10) + { + return 0x8000; + } + else + { + return 0x1000; + } +} + + +uint32_t flash_get_page_size(const flash_t *obj) +{ + return 1024; +} + +uint32_t flash_get_start_address(const flash_t *obj) +{ + return LPC_FLASH_BASE; +} + +uint32_t flash_get_size(const flash_t *obj) +{ + return 0x80000; } #endif diff --git a/targets/TARGET_NXP/TARGET_LPC176X/objects.h b/targets/TARGET_NXP/TARGET_LPC176X/objects.h index ecbd354934..6678bc2fc9 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/objects.h +++ b/targets/TARGET_NXP/TARGET_LPC176X/objects.h @@ -71,7 +71,10 @@ struct spi_s { LPC_SSP_TypeDef *spi; }; -#ifdef __cplusplus +struct flash_s { + /* nothing to be stored for now */ + uint32_t dummy; +};#ifdef __cplusplus } #endif From 26dc3c60df6798103f68a67cd2ae0801f0a53fd7 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 29 Aug 2017 22:25:12 +0100 Subject: [PATCH 21/60] remove CMSIS algorithm and enable bootloader --- targets/targets.json | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/targets/targets.json b/targets/targets.json index 452e29db01..790fd14ae2 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -238,10 +238,11 @@ "extra_labels": ["NXP", "LPC176X", "MBED_LPC1768"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "GCC_CR", "IAR"], "detect_code": ["1010"], - "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES"], + "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "features": ["LWIP"], - "device_name": "LPC1768" + "device_name": "LPC1768", + "bootloader_supported": true }, "ARCH_PRO": { "supported_form_factors": ["ARDUINO"], @@ -250,16 +251,17 @@ "extra_labels": ["NXP", "LPC176X"], "macros": ["TARGET_LPC1768"], "inherits": ["LPCTarget"], - "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES"], + "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "features": ["LWIP"], - "device_name": "LPC1768" + "device_name": "LPC1768", + "bootloader_supported": true }, "UBLOX_C027": { "supported_form_factors": ["ARDUINO"], "core": "Cortex-M3", "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "GCC_CR", "IAR"], - "extra_labels": ["NXP", "LPC176X", "FLASH_CMSIS_ALGO"], + "extra_labels": ["NXP", "LPC176X"], "config": { "modem_is_on_board": { "help": "Value: Tells the build system that the modem is on-board as oppose to a plug-in shield/module.", @@ -277,17 +279,19 @@ "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "features": ["LWIP"], - "device_name": "LPC1768" + "device_name": "LPC1768", + "bootloader_supported": true }, "XBED_LPC1768": { "inherits": ["LPCTarget"], "core": "Cortex-M3", "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "GCC_CR", "IAR"], - "extra_labels": ["NXP", "LPC176X", "XBED_LPC1768", "FLASH_CMSIS_ALGO"], + "extra_labels": ["NXP", "LPC176X", "XBED_LPC1768"], "macros": ["TARGET_LPC1768"], "detect_code": ["1010"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], - "device_name": "LPC1768" + "device_name": "LPC1768", + "bootloader_supported": true }, "LPC810": { "inherits": ["LPCTarget"], From 1382e61f4f48662ea7b199f3e15d67daa3a1229b Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 29 Aug 2017 22:46:14 +0100 Subject: [PATCH 22/60] missing CR --- targets/TARGET_NXP/TARGET_LPC176X/objects.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/objects.h b/targets/TARGET_NXP/TARGET_LPC176X/objects.h index 6678bc2fc9..331ccc9ceb 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/objects.h +++ b/targets/TARGET_NXP/TARGET_LPC176X/objects.h @@ -74,7 +74,8 @@ struct spi_s { struct flash_s { /* nothing to be stored for now */ uint32_t dummy; -};#ifdef __cplusplus +}; +#ifdef __cplusplus } #endif From 272b9cc2ca8e75ad84c9c1b55429e2710356a4f2 Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 30 Aug 2017 12:12:59 +0100 Subject: [PATCH 23/60] Ensure IAP uses word boundary aligned data. --- .../TARGET_LPC176X/device/flash_api.c | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index 5dddff4e68..4d51d37c78 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -19,7 +19,8 @@ #if DEVICE_FLASH #include "mbed_assert.h" #include "cmsis.h" - +#include +#include #define MEMMAP (*((volatile unsigned long *) 0x400FC040)) @@ -109,9 +110,21 @@ typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); int32_t flash_program_page(flash_t *obj, uint32_t address, - const uint8_t *data, uint32_t size) + const uint8_t *datain, uint32_t size) { + uint8_t *data; unsigned long n; + + if ((unsigned long)datain%4==0)//word boundary + { + data = datain; + } + else + { + data = malloc(size); + memcpy(data,datain,size); + } + #if SET_VALID_CODE != 0 // Set valid User Code Signature if (address == 0) { // Check for Vector Table @@ -141,6 +154,10 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, IAP.par[2] = 1024; // Fixed Page Size IAP.par[3] = CCLK; // CCLK in kHz IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + if(data !=datain)//We allocated our own memory + { + free(data); + } if (IAP.stat) return (1); // Command Failed return (0); // Finished without Errors From 6d97b8961bd93464d7dba98f46d77d16708b9d9a Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 30 Aug 2017 13:23:52 +0100 Subject: [PATCH 24/60] Fix flash_mapping_alignment_test so that invalid addresses are reported correctly. Tidy up --- .../TARGET_LPC176X/device/flash_api.c | 156 +++++++++--------- 1 file changed, 80 insertions(+), 76 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index 4d51d37c78..d12086770e 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -17,19 +17,20 @@ #include "mbed_critical.h" #if DEVICE_FLASH +#include "flash_api.h" #include "mbed_assert.h" #include "cmsis.h" #include #include - #define MEMMAP (*((volatile unsigned long *) 0x400FC040)) +#define MEMMAP (*((volatile unsigned long *) 0x400FC040)) - #define PLL0CON (*((volatile unsigned long *) 0x400FC080)) - #define PLL0CFG (*((volatile unsigned long *) 0x400FC084)) - #define PLL0STAT (*((volatile unsigned long *) 0x400FC088)) - #define PLL0FEED (*((volatile unsigned long *) 0x400FC08C)) - #define CCLKSEL (*((volatile unsigned long *) 0x400FC104)) - #define CLKSRCSEL (*((volatile unsigned long *) 0x400FC10C)) +#define PLL0CON (*((volatile unsigned long *) 0x400FC080)) +#define PLL0CFG (*((volatile unsigned long *) 0x400FC084)) +#define PLL0STAT (*((volatile unsigned long *) 0x400FC088)) +#define PLL0FEED (*((volatile unsigned long *) 0x400FC08C)) +#define CCLKSEL (*((volatile unsigned long *) 0x400FC104)) +#define CLKSRCSEL (*((volatile unsigned long *) 0x400FC10C)) #define STACK_SIZE 64 // Stack Size @@ -42,10 +43,10 @@ typedef struct flash_s flash_t; unsigned long CCLK; // CCLK in kHz -struct sIAP { // IAP Structure - unsigned long cmd; // Command +struct sIAP { // IAP Structure + unsigned long cmd; // Command unsigned long par[4]; // Parameters - unsigned long stat; // Status + unsigned long stat; // Status unsigned long res[2]; // Result } IAP; @@ -59,19 +60,19 @@ unsigned long GetSecNum (unsigned long address) { unsigned long n; - n = address >> 12; // 4kB Sector + n = address >> 12; // 4kB Sector if (n >= 0x10) { - n = 0x0E + (n >> 3); // 32kB Sector + n = 0x0E + (n >> 3); // 32kB Sector } - return (n); // Sector Number + return (n); // Sector Number } int32_t flash_init(flash_t *obj) { - CCLK = SystemCoreClock / 1000; // CCLK value is in kHz, clk in Hz + CCLK = SystemCoreClock / 1000; // CCLK value is in kHz, clk in Hz - MEMMAP = 0x01; // User Flash Mode + MEMMAP = 0x01; // User Flash Mode return (0); } @@ -83,24 +84,24 @@ int32_t flash_free(flash_t *obj) int32_t flash_erase_sector(flash_t *obj, uint32_t address) { - unsigned long n; + unsigned long n; - n = GetSecNum(address); // Get Sector Number + n = GetSecNum(address); // Get Sector Number - IAP.cmd = 50; // Prepare Sector for Erase - IAP.par[0] = n; // Start Sector - IAP.par[1] = n; // End Sector - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + IAP.cmd = 50; // Prepare Sector for Erase + IAP.par[0] = n; // Start Sector + IAP.par[1] = n; // End Sector + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command if (IAP.stat) return (1); // Command Failed - IAP.cmd = 52; // Erase Sector - IAP.par[0] = n; // Start Sector - IAP.par[1] = n; // End Sector - IAP.par[2] = CCLK; // CCLK in kHz - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + IAP.cmd = 52; // Erase Sector + IAP.par[0] = n; // Start Sector + IAP.par[1] = n; // End Sector + IAP.par[2] = CCLK; // CCLK in kHz + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command if (IAP.stat) return (1); // Command Failed - return (0); // Finished without Errors + return (0); // Finished without Errors } @@ -110,86 +111,89 @@ typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); int32_t flash_program_page(flash_t *obj, uint32_t address, - const uint8_t *datain, uint32_t size) + const uint8_t *datain, uint32_t size) { - uint8_t *data; - unsigned long n; - - if ((unsigned long)datain%4==0)//word boundary - { - data = datain; - } - else - { - data = malloc(size); - memcpy(data,datain,size); - } - + uint8_t *data; + unsigned long n; + + if ((unsigned long)datain%4==0)//word boundary + { + data = datain; + } + else + { + data = malloc(size); + memcpy(data,datain,size); + } -#if SET_VALID_CODE != 0 // Set valid User Code Signature - if (address == 0) { // Check for Vector Table - n = *((unsigned long *)(data + 0x00)) + - *((unsigned long *)(data + 0x04)) + - *((unsigned long *)(data + 0x08)) + - *((unsigned long *)(data + 0x0C)) + - *((unsigned long *)(data + 0x10)) + - *((unsigned long *)(data + 0x14)) + - *((unsigned long *)(data + 0x18)); - *((unsigned long *)(data + 0x1C)) = 0 - n; // Signature at Reserved Vector + +#if SET_VALID_CODE != 0 // Set valid User Code Signature + if (address == 0) { // Check for Vector Table + n = *((unsigned long *)(data + 0x00)) + + *((unsigned long *)(data + 0x04)) + + *((unsigned long *)(data + 0x08)) + + *((unsigned long *)(data + 0x0C)) + + *((unsigned long *)(data + 0x10)) + + *((unsigned long *)(data + 0x14)) + + *((unsigned long *)(data + 0x18)); + *((unsigned long *)(data + 0x1C)) = 0 - n; // Signature at Reserved Vector } #endif - n = GetSecNum(address); // Get Sector Number + n = GetSecNum(address); // Get Sector Number - IAP.cmd = 50; // Prepare Sector for Write - IAP.par[0] = n; // Start Sector - IAP.par[1] = n; // End Sector - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + IAP.cmd = 50; // Prepare Sector for Write + IAP.par[0] = n; // Start Sector + IAP.par[1] = n; // End Sector + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command if (IAP.stat) return (1); // Command Failed - IAP.cmd = 51; // Copy RAM to Flash - IAP.par[0] = address; // Destination Flash Address - IAP.par[1] = (unsigned long)data; // Source RAM Address + IAP.cmd = 51; // Copy RAM to Flash + IAP.par[0] = address; // Destination Flash Address + IAP.par[1] = (unsigned long)data; // Source RAM Address - IAP.par[2] = 1024; // Fixed Page Size - IAP.par[3] = CCLK; // CCLK in kHz - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command + IAP.par[2] = 1024; // Fixed Page Size + IAP.par[3] = CCLK; // CCLK in kHz + IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command if(data !=datain)//We allocated our own memory { - free(data); + free(data); } if (IAP.stat) return (1); // Command Failed - return (0); // Finished without Errors + return (0); // Finished without Errors } uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address) { - - if(GetSecNum(address)>=0x10) - { - return 0x8000; - } - else - { - return 0x1000; - } + if(address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)) + { + return MBED_FLASH_INVALID_SIZE; + } + if(GetSecNum(address)>=0x10) + { + return 0x8000; + } + else + { + return 0x1000; + } } uint32_t flash_get_page_size(const flash_t *obj) { - return 1024; + return 1024; } uint32_t flash_get_start_address(const flash_t *obj) { - return LPC_FLASH_BASE; + return LPC_FLASH_BASE; } uint32_t flash_get_size(const flash_t *obj) { - return 0x80000; + return 0x80000; } #endif From 51b7e1a26e4a6f0d005081078045cc532500a551 Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 30 Aug 2017 13:57:09 +0100 Subject: [PATCH 25/60] Disable bootloader's for now --- targets/targets.json | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/targets/targets.json b/targets/targets.json index 790fd14ae2..b177fd82e2 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -241,8 +241,7 @@ "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "features": ["LWIP"], - "device_name": "LPC1768", - "bootloader_supported": true + "device_name": "LPC1768" }, "ARCH_PRO": { "supported_form_factors": ["ARDUINO"], @@ -254,8 +253,7 @@ "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "features": ["LWIP"], - "device_name": "LPC1768", - "bootloader_supported": true + "device_name": "LPC1768" }, "UBLOX_C027": { "supported_form_factors": ["ARDUINO"], @@ -279,8 +277,7 @@ "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], "release_versions": ["2", "5"], "features": ["LWIP"], - "device_name": "LPC1768", - "bootloader_supported": true + "device_name": "LPC1768" }, "XBED_LPC1768": { "inherits": ["LPCTarget"], @@ -290,8 +287,7 @@ "macros": ["TARGET_LPC1768"], "detect_code": ["1010"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], - "device_name": "LPC1768", - "bootloader_supported": true + "device_name": "LPC1768" }, "LPC810": { "inherits": ["LPCTarget"], From 3c9f8ce7161d2bafabc6d7c5c9fe41af3085936b Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 4 Sep 2017 12:26:03 +0100 Subject: [PATCH 26/60] Code tidy. --- .../TARGET_LPC176X/device/flash_api.c | 196 +++++++++--------- 1 file changed, 95 insertions(+), 101 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index d12086770e..20b0d29edb 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -5,7 +5,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,76 +32,73 @@ #define CCLKSEL (*((volatile unsigned long *) 0x400FC104)) #define CLKSRCSEL (*((volatile unsigned long *) 0x400FC10C)) -#define STACK_SIZE 64 // Stack Size +#define STACK_SIZE 64 // Stack Size -#define SET_VALID_CODE 1 // Set Valid User Code Signature +#define SET_VALID_CODE 1 // Set Valid User Code Signature /* IAP Call */ typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); #define IAP_Call ((IAP_Entry) 0x1FFF1FF1) typedef struct flash_s flash_t; -unsigned long CCLK; // CCLK in kHz +unsigned long CCLK;// CCLK in kHz - -struct sIAP { // IAP Structure - unsigned long cmd; // Command - unsigned long par[4]; // Parameters - unsigned long stat; // Status - unsigned long res[2]; // Result -} IAP; +struct sIAP {// IAP Structure + unsigned long cmd;// Command + unsigned long par[4];// Parameters + unsigned long stat;// Status + unsigned long res[2];// Result +}IAP; /* * Get Sector Number - * Parameter: address: Sector Address - * Return Value: Sector Number + * Parameter: address: Sector Address + * Return Value: Sector Number */ unsigned long GetSecNum (unsigned long address) { - unsigned long n; + unsigned long n; + n = address >> 12;// 4kB Sector + if (n >= 0x10) { + n = 0x0E + (n >> 3);// 32kB Sector + } - n = address >> 12; // 4kB Sector - if (n >= 0x10) { - n = 0x0E + (n >> 3); // 32kB Sector - } - - - return (n); // Sector Number + return (n);// Sector Number } int32_t flash_init(flash_t *obj) { - CCLK = SystemCoreClock / 1000; // CCLK value is in kHz, clk in Hz + CCLK = SystemCoreClock / 1000;// CCLK value is in kHz, clk in Hz - MEMMAP = 0x01; // User Flash Mode + MEMMAP = 0x01;// User Flash Mode - return (0); + return (0); } int32_t flash_free(flash_t *obj) { - return 0; + return 0; } int32_t flash_erase_sector(flash_t *obj, uint32_t address) { - unsigned long n; + unsigned long n; - n = GetSecNum(address); // Get Sector Number + n = GetSecNum(address); // Get Sector Number - IAP.cmd = 50; // Prepare Sector for Erase - IAP.par[0] = n; // Start Sector - IAP.par[1] = n; // End Sector - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command - if (IAP.stat) return (1); // Command Failed + IAP.cmd = 50;// Prepare Sector for Erase + IAP.par[0] = n;// Start Sector + IAP.par[1] = n;// End Sector + IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command + if (IAP.stat) return (1);// Command Failed - IAP.cmd = 52; // Erase Sector - IAP.par[0] = n; // Start Sector - IAP.par[1] = n; // End Sector - IAP.par[2] = CCLK; // CCLK in kHz - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command - if (IAP.stat) return (1); // Command Failed + IAP.cmd = 52;// Erase Sector + IAP.par[0] = n;// Start Sector + IAP.par[1] = n;// End Sector + IAP.par[2] = CCLK;// CCLK in kHz + IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command + if (IAP.stat) return (1);// Command Failed - return (0); // Finished without Errors + return (0);// Finished without Errors } @@ -109,91 +106,88 @@ int32_t flash_erase_sector(flash_t *obj, uint32_t address) typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); #define IAP_Call ((IAP_Entry) 0x1FFF1FF1) - int32_t flash_program_page(flash_t *obj, uint32_t address, - const uint8_t *datain, uint32_t size) + const uint8_t *datain, uint32_t size) { - uint8_t *data; - unsigned long n; - - if ((unsigned long)datain%4==0)//word boundary - { - data = datain; - } - else - { - data = malloc(size); - memcpy(data,datain,size); - } + uint8_t *data; + unsigned long n; + if ((unsigned long)datain%4==0)//word boundary + { + data = datain; + } + else + { + data = malloc(size); + memcpy(data,datain,size); + } -#if SET_VALID_CODE != 0 // Set valid User Code Signature - if (address == 0) { // Check for Vector Table - n = *((unsigned long *)(data + 0x00)) + - *((unsigned long *)(data + 0x04)) + - *((unsigned long *)(data + 0x08)) + - *((unsigned long *)(data + 0x0C)) + - *((unsigned long *)(data + 0x10)) + - *((unsigned long *)(data + 0x14)) + - *((unsigned long *)(data + 0x18)); - *((unsigned long *)(data + 0x1C)) = 0 - n; // Signature at Reserved Vector - } +#if SET_VALID_CODE != 0// Set valid User Code Signature + if (address == 0) {// Check for Vector Table + n = *((unsigned long *)(data + 0x00)) + + *((unsigned long *)(data + 0x04)) + + *((unsigned long *)(data + 0x08)) + + *((unsigned long *)(data + 0x0C)) + + *((unsigned long *)(data + 0x10)) + + *((unsigned long *)(data + 0x14)) + + *((unsigned long *)(data + 0x18)); + *((unsigned long *)(data + 0x1C)) = 0 - n;// Signature at Reserved Vector + } #endif - n = GetSecNum(address); // Get Sector Number + n = GetSecNum(address);// Get Sector Number - IAP.cmd = 50; // Prepare Sector for Write - IAP.par[0] = n; // Start Sector - IAP.par[1] = n; // End Sector - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command - if (IAP.stat) return (1); // Command Failed + IAP.cmd = 50;// Prepare Sector for Write + IAP.par[0] = n;// Start Sector + IAP.par[1] = n;// End Sector + IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command + if (IAP.stat) return (1);// Command Failed - IAP.cmd = 51; // Copy RAM to Flash - IAP.par[0] = address; // Destination Flash Address - IAP.par[1] = (unsigned long)data; // Source RAM Address + IAP.cmd = 51;// Copy RAM to Flash + IAP.par[0] = address;// Destination Flash Address + IAP.par[1] = (unsigned long)data;// Source RAM Address - IAP.par[2] = 1024; // Fixed Page Size - IAP.par[3] = CCLK; // CCLK in kHz - IAP_Call (&IAP.cmd, &IAP.stat); // Call IAP Command - if(data !=datain)//We allocated our own memory - { - free(data); - } - if (IAP.stat) return (1); // Command Failed + IAP.par[2] = 1024;// Fixed Page Size + IAP.par[3] = CCLK;// CCLK in kHz + IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command + if(data !=datain)//We allocated our own memory + { + free(data); + } + if (IAP.stat) return (1);// Command Failed - return (0); // Finished without Errors + return (0);// Finished without Errors } -uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address) +uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address) { - if(address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)) - { - return MBED_FLASH_INVALID_SIZE; - } - if(GetSecNum(address)>=0x10) - { - return 0x8000; - } - else - { - return 0x1000; - } + if(address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)) + { + return MBED_FLASH_INVALID_SIZE; + } + if(GetSecNum(address)>=0x10) + { + return 0x8000; + } + else + { + return 0x1000; + } } - uint32_t flash_get_page_size(const flash_t *obj) { - return 1024; + return 1024; } -uint32_t flash_get_start_address(const flash_t *obj) +uint32_t flash_get_start_address(const flash_t *obj) { - return LPC_FLASH_BASE; + return LPC_FLASH_BASE; } -uint32_t flash_get_size(const flash_t *obj) +uint32_t flash_get_size(const flash_t *obj) { - return 0x80000; + return 0x80000; } #endif From 606f205e5be57fdb986a8a85dcb06cc689879f70 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 4 Sep 2017 13:17:12 +0100 Subject: [PATCH 27/60] Remove SET_VALID_CODE --- .../TARGET_NXP/TARGET_LPC176X/device/flash_api.c | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index 20b0d29edb..d00dc12c64 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -16,7 +16,6 @@ #include "mbed_critical.h" -#if DEVICE_FLASH #include "flash_api.h" #include "mbed_assert.h" #include "cmsis.h" @@ -122,19 +121,6 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, memcpy(data,datain,size); } -#if SET_VALID_CODE != 0// Set valid User Code Signature - if (address == 0) {// Check for Vector Table - n = *((unsigned long *)(data + 0x00)) + - *((unsigned long *)(data + 0x04)) + - *((unsigned long *)(data + 0x08)) + - *((unsigned long *)(data + 0x0C)) + - *((unsigned long *)(data + 0x10)) + - *((unsigned long *)(data + 0x14)) + - *((unsigned long *)(data + 0x18)); - *((unsigned long *)(data + 0x1C)) = 0 - n;// Signature at Reserved Vector - } -#endif - n = GetSecNum(address);// Get Sector Number IAP.cmd = 50;// Prepare Sector for Write From d3b1f69c2dba11bdd26a56403d424100a31f3c94 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 4 Sep 2017 13:46:13 +0100 Subject: [PATCH 28/60] Resolve warning --- .../TARGET_LPC176X/device/flash_api.c | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index d00dc12c64..f7821e9224 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#if DEVICE_FLASH #include "mbed_critical.h" #include "flash_api.h" @@ -106,20 +106,10 @@ typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); #define IAP_Call ((IAP_Entry) 0x1FFF1FF1) int32_t flash_program_page(flash_t *obj, uint32_t address, - const uint8_t *datain, uint32_t size) + const uint8_t *data, uint32_t size) { - uint8_t *data; unsigned long n; - - if ((unsigned long)datain%4==0)//word boundary - { - data = datain; - } - else - { - data = malloc(size); - memcpy(data,datain,size); - } + uint8_t *alignedData = 0; n = GetSecNum(address);// Get Sector Number @@ -131,15 +121,27 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, IAP.cmd = 51;// Copy RAM to Flash IAP.par[0] = address;// Destination Flash Address - IAP.par[1] = (unsigned long)data;// Source RAM Address + + if ((unsigned long)data%4==0)// Word boundary + { + IAP.par[1] = (unsigned long)data;// Source RAM Address + } + else + { + alignedData = malloc(size); + memcpy(alignedData,data,size); + IAP.par[1] = (unsigned long)alignedData;// Source RAM Address + } IAP.par[2] = 1024;// Fixed Page Size IAP.par[3] = CCLK;// CCLK in kHz IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command - if(data !=datain)//We allocated our own memory + + if(alignedData !=0)//We allocated our own memory { - free(data); + free(alignedData); } + if (IAP.stat) return (1);// Command Failed return (0);// Finished without Errors From 0711bb14e6d5e22c120f54282976d232819db9da Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 4 Sep 2017 15:06:26 +0100 Subject: [PATCH 29/60] Tidy if else code aligment. --- .../TARGET_LPC176X/device/flash_api.c | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index f7821e9224..d7a96a1639 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -122,12 +122,9 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, IAP.cmd = 51;// Copy RAM to Flash IAP.par[0] = address;// Destination Flash Address - if ((unsigned long)data%4==0)// Word boundary - { + if ((unsigned long)data%4==0){// Word boundary IAP.par[1] = (unsigned long)data;// Source RAM Address - } - else - { + } else { alignedData = malloc(size); memcpy(alignedData,data,size); IAP.par[1] = (unsigned long)alignedData;// Source RAM Address @@ -137,8 +134,7 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, IAP.par[3] = CCLK;// CCLK in kHz IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command - if(alignedData !=0)//We allocated our own memory - { + if(alignedData !=0){//We allocated our own memory free(alignedData); } @@ -149,16 +145,12 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address) { - if(address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)) - { + if(address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)){ return MBED_FLASH_INVALID_SIZE; } - if(GetSecNum(address)>=0x10) - { + if(GetSecNum(address)>=0x10){ return 0x8000; - } - else - { + } else { return 0x1000; } } From 1e454c4b925add3cbf2c8ddba3d172df89151d59 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 4 Sep 2017 15:54:07 +0100 Subject: [PATCH 30/60] Code tidy. --- .../TARGET_LPC176X/device/flash_api.c | 55 +++++++++++-------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index d7a96a1639..372cc49972 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -39,9 +39,9 @@ typedef void (*IAP_Entry) (unsigned long *cmd, unsigned long *stat); #define IAP_Call ((IAP_Entry) 0x1FFF1FF1) typedef struct flash_s flash_t; -unsigned long CCLK;// CCLK in kHz +unsigned long CCLK; // CCLK in kHz -struct sIAP {// IAP Structure +struct sIAP { // IAP Structure unsigned long cmd;// Command unsigned long par[4];// Parameters unsigned long stat;// Status @@ -57,16 +57,16 @@ struct sIAP {// IAP Structure unsigned long GetSecNum (unsigned long address) { unsigned long n; - n = address >> 12;// 4kB Sector + n = address >> 12; // 4kB Sector if (n >= 0x10) { - n = 0x0E + (n >> 3);// 32kB Sector + n = 0x0E + (n >> 3); // 32kB Sector } - return (n);// Sector Number + return (n); // Sector Number } int32_t flash_init(flash_t *obj) { - CCLK = SystemCoreClock / 1000;// CCLK value is in kHz, clk in Hz + CCLK = SystemCoreClock / 1000; // CCLK value is in kHz, clk in Hz MEMMAP = 0x01;// User Flash Mode @@ -88,16 +88,20 @@ int32_t flash_erase_sector(flash_t *obj, uint32_t address) IAP.par[0] = n;// Start Sector IAP.par[1] = n;// End Sector IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command - if (IAP.stat) return (1);// Command Failed + if (IAP.stat) { + return (1); // Command Failed + } - IAP.cmd = 52;// Erase Sector + IAP.cmd = 52; // Erase Sector IAP.par[0] = n;// Start Sector IAP.par[1] = n;// End Sector IAP.par[2] = CCLK;// CCLK in kHz IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command - if (IAP.stat) return (1);// Command Failed + if (IAP.stat) { + return (1); // Command Failed + } - return (0);// Finished without Errors + return (0); // Finished without Errors } @@ -111,44 +115,47 @@ int32_t flash_program_page(flash_t *obj, uint32_t address, unsigned long n; uint8_t *alignedData = 0; - n = GetSecNum(address);// Get Sector Number + n = GetSecNum(address); // Get Sector Number IAP.cmd = 50;// Prepare Sector for Write IAP.par[0] = n;// Start Sector IAP.par[1] = n;// End Sector IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command - if (IAP.stat) return (1);// Command Failed + if (IAP.stat) { + return (1); // Command Failed + } - IAP.cmd = 51;// Copy RAM to Flash + IAP.cmd = 51; // Copy RAM to Flash IAP.par[0] = address;// Destination Flash Address - - if ((unsigned long)data%4==0){// Word boundary + + if ((unsigned long)data%4==0) { // Word boundary IAP.par[1] = (unsigned long)data;// Source RAM Address } else { alignedData = malloc(size); memcpy(alignedData,data,size); - IAP.par[1] = (unsigned long)alignedData;// Source RAM Address + IAP.par[1] = (unsigned long)alignedData; // Source RAM Address } - IAP.par[2] = 1024;// Fixed Page Size + IAP.par[2] = 1024; // Fixed Page Size IAP.par[3] = CCLK;// CCLK in kHz IAP_Call (&IAP.cmd, &IAP.stat);// Call IAP Command - - if(alignedData !=0){//We allocated our own memory + + if(alignedData !=0) { // We allocated our own memory free(alignedData); } - - if (IAP.stat) return (1);// Command Failed - return (0);// Finished without Errors + if (IAP.stat) { + return (1); // Command Failed + } + return (0); // Finished without Errors } uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address) { - if(address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)){ + if (address < flash_get_start_address(obj) || address >= flash_get_start_address(obj) +flash_get_size(obj)) { return MBED_FLASH_INVALID_SIZE; } - if(GetSecNum(address)>=0x10){ + if(GetSecNum(address)>=0x10) { return 0x8000; } else { return 0x1000; From 56777ab64a369f8b8835caa31166d159577ca4a0 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 4 Sep 2017 16:00:58 +0100 Subject: [PATCH 31/60] Code tidy --- targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c index 372cc49972..40e72a92f3 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c @@ -54,7 +54,8 @@ struct sIAP { // IAP Structure * Return Value: Sector Number */ -unsigned long GetSecNum (unsigned long address) { +unsigned long GetSecNum (unsigned long address) +{ unsigned long n; n = address >> 12; // 4kB Sector From 567d64e6491533541f22cf9e760c8f02b98ef6ae Mon Sep 17 00:00:00 2001 From: Deepika Date: Tue, 29 Aug 2017 15:21:23 -0500 Subject: [PATCH 32/60] Added thread terminate hook Hook was added in RTX4 code to assist test framework to log thread info on thread terminate, which was not working with RTX5. --- rtos/TARGET_CORTEX/mbed_rtx_handlers.c | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/rtos/TARGET_CORTEX/mbed_rtx_handlers.c b/rtos/TARGET_CORTEX/mbed_rtx_handlers.c index e5dcabaa79..882d4636af 100644 --- a/rtos/TARGET_CORTEX/mbed_rtx_handlers.c +++ b/rtos/TARGET_CORTEX/mbed_rtx_handlers.c @@ -19,8 +19,17 @@ #include "rtx_evr.h" #include "mbed_rtx.h" #include "mbed_error.h" +#include "RTX_Config.h" + +#ifdef RTE_Compiler_EventRecorder +#include "EventRecorder.h" // Keil::Compiler:Event Recorder +// Used from rtx_evr.c +#define EvtRtxThreadExit EventID(EventLevelAPI, 0xF2U, 0x19U) +#define EvtRtxThreadTerminate EventID(EventLevelAPI, 0xF2U, 0x1AU) +#endif extern void rtos_idle_loop(void); +extern void thread_terminate_hook(osThreadId_t id); __NO_RETURN void osRtxIdleThread (void *argument) { @@ -136,3 +145,21 @@ void EvrRtxMessageQueueError (osMessageQueueId_t mq_id, int32_t status) } #endif + +// RTX hook which gets called when a thread terminates, using the event function to call hook +void EvrRtxThreadExit (void) +{ + osThreadId_t thread_id = osThreadGetId(); + thread_terminate_hook(thread_id); +#if (!defined(EVR_RTX_DISABLE) && (OS_EVR_THREAD != 0) && !defined(EVR_RTX_THREAD_EXIT_DISABLE) && defined(RTE_Compiler_EventRecorder)) + EventRecord2(EvtRtxThreadExit, 0U, 0U); +#endif +} + +void EvrRtxThreadTerminate (osThreadId_t thread_id) +{ + thread_terminate_hook(thread_id); +#if (!defined(EVR_RTX_DISABLE) && (OS_EVR_THREAD != 0) && !defined(EVR_RTX_THREAD_TERMINATE_DISABLE) && defined(RTE_Compiler_EventRecorder)) + EventRecord2(EvtRtxThreadTerminate, (uint32_t)thread_id, 0U); +#endif +} From 6323d18c876155eba4564f536d58b61e6742289d Mon Sep 17 00:00:00 2001 From: Deepika Date: Fri, 15 Sep 2017 11:39:47 -0500 Subject: [PATCH 33/60] Threads test require more time to finish --- TESTS/mbedmicro-rtos-mbed/threads/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp index 7423bd957c..931d14d941 100644 --- a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp @@ -657,7 +657,7 @@ void test_thread_prio() { } utest::v1::status_t test_setup(const size_t number_of_cases) { - GREENTEA_SETUP(15, "default_auto"); + GREENTEA_SETUP(20, "default_auto"); return verbose_test_setup_handler(number_of_cases); } From b46e7d9b2fa4066ba4428baaae41c995e4eca8ef Mon Sep 17 00:00:00 2001 From: gorazd Date: Thu, 24 Aug 2017 19:24:02 +0200 Subject: [PATCH 34/60] new target added L-TEK FF1705 based on XDOT --- targets/targets.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/targets/targets.json b/targets/targets.json index b177fd82e2..9d903bbfec 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -1662,6 +1662,12 @@ "device_name": "STM32L151CC", "bootloader_supported": true }, + "FF1705_L151CC": { + "supported_form_factors": ["ARDUINO"], + "inherits": ["XDOT_L151CC"], + "detect_code": ["8080"], + "extra_labels_add": ["L-TEK"] + }, "MOTE_L152RC": { "inherits": ["FAMILY_STM32"], "core": "Cortex-M3", From 110c3d6de98a2d5b485006a496e7b65f8872eb77 Mon Sep 17 00:00:00 2001 From: gorazd Date: Wed, 30 Aug 2017 08:16:08 +0200 Subject: [PATCH 35/60] extra label deleted --- targets/targets.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/targets/targets.json b/targets/targets.json index 9d903bbfec..cab9a4e95e 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -1665,8 +1665,7 @@ "FF1705_L151CC": { "supported_form_factors": ["ARDUINO"], "inherits": ["XDOT_L151CC"], - "detect_code": ["8080"], - "extra_labels_add": ["L-TEK"] + "detect_code": ["8080"] }, "MOTE_L152RC": { "inherits": ["FAMILY_STM32"], From ad183b19cbc36dd7907c16a67d0f9b22b6ea3942 Mon Sep 17 00:00:00 2001 From: gorazd Date: Thu, 31 Aug 2017 15:18:14 +0200 Subject: [PATCH 36/60] arduino connector namings added --- .../TARGET_STM32L1/TARGET_XDOT_L151CC/PinNames.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/targets/TARGET_STM/TARGET_STM32L1/TARGET_XDOT_L151CC/PinNames.h b/targets/TARGET_STM/TARGET_STM32L1/TARGET_XDOT_L151CC/PinNames.h index 7060d7da3c..4bf3b2f446 100644 --- a/targets/TARGET_STM/TARGET_STM32L1/TARGET_XDOT_L151CC/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L1/TARGET_XDOT_L151CC/PinNames.h @@ -170,6 +170,22 @@ typedef enum { SE_IO = PB_10, SE_CLK = PB_11, +#ifdef TARGET_FF1705_L151CC + // Arduino Headers + A0 = PA_0, + A1 = PB_0, + D0 = PA_10, + D1 = PA_9, + D2 = PA_11, + D3 = PA_12, + D10 = PB_12, + D11 = PB_15, + D12 = PB_14, + D13 = PB_13, + D14 = I2C_SDA, + D15 = I2C_SCL, +#endif + // Not connected NC = (int)0xFFFFFFFF } PinName; From 80e8351bcb20f6005e7b673f617c894e4d6afcc9 Mon Sep 17 00:00:00 2001 From: Dexter Fryar Date: Wed, 23 Aug 2017 21:19:51 -0500 Subject: [PATCH 37/60] Add bootloader support for NXP FRDM-KW24D --- .../TOOLCHAIN_ARM_STD/MKW24D512xxx5.sct | 16 +++++++++++---- .../device/TOOLCHAIN_GCC_ARM/MKW24D512xxx5.ld | 14 ++++++++++--- .../device/TOOLCHAIN_IAR/MKW24D512xxx5.icf | 20 +++++++++++++------ targets/targets.json | 5 +++-- 4 files changed, 40 insertions(+), 15 deletions(-) diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_ARM_STD/MKW24D512xxx5.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_ARM_STD/MKW24D512xxx5.sct index 0cee641643..7bf8db50b2 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_ARM_STD/MKW24D512xxx5.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_ARM_STD/MKW24D512xxx5.sct @@ -51,14 +51,22 @@ #define __ram_vector_table_size__ 0x00000000 #endif -#define m_interrupts_start 0x00000000 +#if !defined(MBED_APP_START) + #define MBED_APP_START 0 +#endif + +#if !defined(MBED_APP_SIZE) + #define MBED_APP_SIZE 0x80000 +#endif + +#define m_interrupts_start MBED_APP_START #define m_interrupts_size 0x00000400 -#define m_flash_config_start 0x00000400 +#define m_flash_config_start MBED_APP_START + 0x400 #define m_flash_config_size 0x00000010 -#define m_text_start 0x00000410 -#define m_text_size 0x0007FBF0 +#define m_text_start MBED_APP_START + 0x410 +#define m_text_size MBED_APP_SIZE - 0x410 #define m_interrupts_ram_start 0x1FFF8000 #define m_interrupts_ram_size __ram_vector_table_size__ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_GCC_ARM/MKW24D512xxx5.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_GCC_ARM/MKW24D512xxx5.ld index 3ee0095bd3..bc648a957b 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_GCC_ARM/MKW24D512xxx5.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_GCC_ARM/MKW24D512xxx5.ld @@ -58,6 +58,14 @@ __stack_size__ = 0x400; * heap and the page heap in uVisor applications. */ __heap_size__ = 0x4000; +#if !defined(MBED_APP_START) + #define MBED_APP_START 0 +#endif + +#if !defined(MBED_APP_SIZE) + #define MBED_APP_SIZE 0x80000 +#endif + HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; STACK_SIZE = DEFINED(__stack_size__) ? __stack_size__ : 0x0400; M_VECTOR_RAM_SIZE = DEFINED(__ram_vector_table__) ? 0x0400 : 0x0; @@ -65,9 +73,9 @@ M_VECTOR_RAM_SIZE = DEFINED(__ram_vector_table__) ? 0x0400 : 0x0; /* Specify the memory areas */ MEMORY { - m_interrupts (RX) : ORIGIN = 0x00000000, LENGTH = 0x00000400 - m_flash_config (RX) : ORIGIN = 0x00000400, LENGTH = 0x00000010 - m_text (RX) : ORIGIN = 0x00000410, LENGTH = 0x0007FBF0 + m_interrupts (RX) : ORIGIN = MBED_APP_START, LENGTH = 0x400 + m_flash_config (RX) : ORIGIN = MBED_APP_START + 0x400, LENGTH = 0x10 + m_text (RX) : ORIGIN = MBED_APP_START + 0x410, LENGTH = MBED_APP_SIZE - 0x410 m_data (RW) : ORIGIN = 0x1FFF8000, LENGTH = 0x00008000 m_data_2 (RW) : ORIGIN = 0x20000000, LENGTH = 0x00008000 } diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_IAR/MKW24D512xxx5.icf b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_IAR/MKW24D512xxx5.icf index ed39474da9..28794497a9 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_IAR/MKW24D512xxx5.icf +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/device/TOOLCHAIN_IAR/MKW24D512xxx5.icf @@ -48,17 +48,25 @@ define symbol __ram_vector_table__ = 1; define symbol __stack_size__=0x2000; define symbol __heap_size__=0x4000; +if (!isdefinedsymbol(MBED_APP_START)) { + define symbol MBED_APP_START = 0; +} + +if (!isdefinedsymbol(MBED_APP_SIZE)) { + define symbol MBED_APP_SIZE = 0x80000; +} + define symbol __ram_vector_table_size__ = isdefinedsymbol(__ram_vector_table__) ? 0x00000400 : 0; define symbol __ram_vector_table_offset__ = isdefinedsymbol(__ram_vector_table__) ? 0x000003FF : 0; -define symbol m_interrupts_start = 0x00000000; -define symbol m_interrupts_end = 0x000003FF; +define symbol m_interrupts_start = MBED_APP_START; +define symbol m_interrupts_end = MBED_APP_START + 0x3FF; -define symbol m_flash_config_start = 0x00000400; -define symbol m_flash_config_end = 0x0000040F; +define symbol m_flash_config_start = MBED_APP_START + 0x400; +define symbol m_flash_config_end = MBED_APP_START + 0x40F; -define symbol m_text_start = 0x00000410; -define symbol m_text_end = 0x0007FFFF; +define symbol m_text_start = MBED_APP_START + 0x410; +define symbol m_text_end = MBED_APP_START + MBED_APP_SIZE - 1; define symbol m_interrupts_ram_start = 0x1FFF8000; define symbol m_interrupts_ram_end = 0x1FFF8000 + __ram_vector_table_offset__; diff --git a/targets/targets.json b/targets/targets.json index cab9a4e95e..c9ae0ea0a0 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -563,9 +563,10 @@ "macros": ["CPU_MKW24D512VHA5", "FSL_RTOS_MBED"], "inherits": ["Target"], "detect_code": ["0250"], - "device_has": ["ANALOGIN", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG"], + "device_has": ["ANALOGIN", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG", "FLASH"], "release_versions": ["2", "5"], - "device_name": "MKW24D512xxx5" + "device_name": "MKW24D512xxx5", + "bootloader_supported": true }, "KW41Z": { "supported_form_factors": ["ARDUINO"], From ba0e6d6a4c21f04e7443e8b1fba034d277fd1361 Mon Sep 17 00:00:00 2001 From: Deepika Date: Fri, 15 Sep 2017 15:05:20 -0500 Subject: [PATCH 38/60] IAR heap stats added --- TESTS/mbed_drivers/stats/main.cpp | 2 +- platform/mbed_alloc_wrappers.cpp | 59 ++++++++++++++++++++----------- 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/TESTS/mbed_drivers/stats/main.cpp b/TESTS/mbed_drivers/stats/main.cpp index 2d5404d0d5..b99adead2f 100644 --- a/TESTS/mbed_drivers/stats/main.cpp +++ b/TESTS/mbed_drivers/stats/main.cpp @@ -22,7 +22,7 @@ #include #include -#if !defined(MBED_HEAP_STATS_ENABLED) || !MBED_HEAP_STATS_ENABLED || defined(__ICCARM__) +#if !defined(MBED_HEAP_STATS_ENABLED) #error [NOT_SUPPORTED] test not supported #endif diff --git a/platform/mbed_alloc_wrappers.cpp b/platform/mbed_alloc_wrappers.cpp index 200ce2e563..9431811472 100644 --- a/platform/mbed_alloc_wrappers.cpp +++ b/platform/mbed_alloc_wrappers.cpp @@ -207,26 +207,46 @@ extern "C" void * __wrap__memalign_r(struct _reent * r, size_t alignment, size_t /******************************************************************************/ -/* ARMCC memory allocation wrappers */ +/* ARMCC / IAR memory allocation wrappers */ /******************************************************************************/ -#elif defined(TOOLCHAIN_ARM) // #if defined(TOOLCHAIN_GCC) +#elif defined(TOOLCHAIN_ARM) || defined(__ICCARM__) + +#if defined(TOOLCHAIN_ARM) +#define SUPER_MALLOC $Super$$malloc +#define SUB_MALLOC $Sub$$malloc +#define SUPER_REALLOC $Super$$realloc +#define SUB_REALLOC $Sub$$realloc +#define SUPER_CALLOC $Super$$calloc +#define SUB_CALLOC $Sub$$calloc +#define SUPER_FREE $Super$$free +#define SUB_FREE $Sub$$free +#elif defined(__ICCARM__) +#define SUPER_MALLOC $Super$$__iar_dlmalloc +#define SUB_MALLOC $Sub$$__iar_dlmalloc +#define SUPER_REALLOC $Super$$__iar_dlrealloc +#define SUB_REALLOC $Sub$$__iar_dlrealloc +#define SUPER_CALLOC $Super$$__iar_dlcalloc +#define SUB_CALLOC $Sub$$__iar_dlcalloc +#define SUPER_FREE $Super$$__iar_dlfree +#define SUB_FREE $Sub$$__iar_dlfree +#endif /* Enable hooking of memory function only if tracing is also enabled */ #if defined(MBED_MEM_TRACING_ENABLED) || defined(MBED_HEAP_STATS_ENABLED) extern "C" { - void *$Super$$malloc(size_t size); - void *$Super$$realloc(void *ptr, size_t size); - void *$Super$$calloc(size_t nmemb, size_t size); - void $Super$$free(void *ptr); + void *SUPER_MALLOC(size_t size); + void *SUPER_REALLOC(void *ptr, size_t size); + void *SUPER_CALLOC(size_t nmemb, size_t size); + void SUPER_FREE(void *ptr); } -extern "C" void* $Sub$$malloc(size_t size) { +extern "C" void* SUB_MALLOC(size_t size) { void *ptr = NULL; #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); - alloc_info_t *alloc_info = (alloc_info_t*)$Super$$malloc(size + sizeof(alloc_info_t)); + alloc_info_t *alloc_info = (alloc_info_t*)SUPER_MALLOC(size + sizeof(alloc_info_t)); if (alloc_info != NULL) { alloc_info->size = size; ptr = (void*)(alloc_info + 1); @@ -241,7 +261,7 @@ extern "C" void* $Sub$$malloc(size_t size) { } malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED - ptr = $Super$$malloc(size); + ptr = SUPER_MALLOC(size); #endif // #ifdef MBED_HEAP_STATS_ENABLED #ifdef MBED_MEM_TRACING_ENABLED mem_trace_mutex->lock(); @@ -251,7 +271,7 @@ extern "C" void* $Sub$$malloc(size_t size) { return ptr; } -extern "C" void* $Sub$$realloc(void *ptr, size_t size) { +extern "C" void* SUB_REALLOC(void *ptr, size_t size) { void *new_ptr = NULL; #ifdef MBED_HEAP_STATS_ENABLED // Note - no lock needed since malloc and free are thread safe @@ -276,7 +296,7 @@ extern "C" void* $Sub$$realloc(void *ptr, size_t size) { free(ptr); } #else // #ifdef MBED_HEAP_STATS_ENABLED - new_ptr = $Super$$realloc(ptr, size); + new_ptr = SUPER_REALLOC(ptr, size); #endif // #ifdef MBED_HEAP_STATS_ENABLED #ifdef MBED_MEM_TRACING_ENABLED mem_trace_mutex->lock(); @@ -286,7 +306,7 @@ extern "C" void* $Sub$$realloc(void *ptr, size_t size) { return new_ptr; } -extern "C" void *$Sub$$calloc(size_t nmemb, size_t size) { +extern "C" void *SUB_CALLOC(size_t nmemb, size_t size) { void *ptr = NULL; #ifdef MBED_HEAP_STATS_ENABLED // Note - no lock needed since malloc is thread safe @@ -295,7 +315,7 @@ extern "C" void *$Sub$$calloc(size_t nmemb, size_t size) { memset(ptr, 0, nmemb * size); } #else // #ifdef MBED_HEAP_STATS_ENABLED - ptr = $Super$$calloc(nmemb, size); + ptr = SUPER_CALLOC(nmemb, size); #endif // #ifdef MBED_HEAP_STATS_ENABLED #ifdef MBED_MEM_TRACING_ENABLED mem_trace_mutex->lock(); @@ -305,7 +325,7 @@ extern "C" void *$Sub$$calloc(size_t nmemb, size_t size) { return ptr; } -extern "C" void $Sub$$free(void *ptr) { +extern "C" void SUB_FREE(void *ptr) { #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); alloc_info_t *alloc_info = NULL; @@ -314,10 +334,10 @@ extern "C" void $Sub$$free(void *ptr) { heap_stats.current_size -= alloc_info->size; heap_stats.alloc_cnt -= 1; } - $Super$$free((void*)alloc_info); + SUPER_FREE((void*)alloc_info); malloc_stats_mutex->unlock(); #else // #ifdef MBED_HEAP_STATS_ENABLED - $Super$$free(ptr); + SUPER_FREE(ptr); #endif // #ifdef MBED_HEAP_STATS_ENABLED #ifdef MBED_MEM_TRACING_ENABLED mem_trace_mutex->lock(); @@ -332,15 +352,14 @@ extern "C" void $Sub$$free(void *ptr) { /* Allocation wrappers for other toolchains are not supported yet */ /******************************************************************************/ -#else // #if defined(TOOLCHAIN_GCC) +#else #ifdef MBED_MEM_TRACING_ENABLED -#warning Memory tracing is not supported with the current toolchain. +#error Memory tracing is not supported with the current toolchain. #endif #ifdef MBED_HEAP_STATS_ENABLED -#warning Heap statistics are not supported with the current toolchain. +#error Heap statistics are not supported with the current toolchain. #endif #endif // #if defined(TOOLCHAIN_GCC) - From f870269075a4613e6686e0ec95a72f28f2660f83 Mon Sep 17 00:00:00 2001 From: Jarno Komula Date: Wed, 19 Jul 2017 12:23:03 +0300 Subject: [PATCH 39/60] Fixed sw4stm32 exporter --- tools/export/sw4stm32/__init__.py | 89 ++++++++++++++++++++-- tools/export/sw4stm32/cproject_common.tmpl | 14 +++- 2 files changed, 94 insertions(+), 9 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index 8ed4fdcc57..e50d0e763c 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -14,7 +14,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ -from os.path import splitext, basename, join +import os + +from os.path import splitext, basename, join, dirname from random import randint from tools.utils import mkdir from tools.export.exporters import Exporter @@ -79,32 +81,103 @@ class Sw4STM32(Exporter): def __generate_uid(self): return "%0.9u" % randint(0, 999999999) + @staticmethod + def filter_dot(str): + """ + This function removes ./ from str. + str must be converted with win_to_unix() before using this function. + """ + if str == None: + return None + if str[:2] == './': + return str[2:] + return str + + def build_excludelist(self): + self.source_folders = [self.filter_dot(s) for s in set(dirname( + src) for src in self.resources.c_sources + self.resources.cpp_sources + self.resources.s_sources)] + if '.' in self.source_folders: + self.source_folders.remove('.') + #print source_folders + + top_folders = [f for f in set(s.split('/')[0] for s in self.source_folders)] + #print top_folders + + for top_folder in top_folders: + # + for root, dirs, files in os.walk(top_folder, topdown=True): + # Paths returned by os.walk() must be split with os.dep + # to accomodate Windows weirdness. + parts = root.split(os.sep) + self.remove_unused('/'.join(parts)) + + def remove_unused(self, path): + found = False + for used in self.include_path: + if path == used: + found = True + needToAdd = True + if not found: + for dir in self.exclude_dirs: + # Do not exclude subfolders from excluded folder + if path.find(dir+'/') != -1: + needToAdd = False + if needToAdd: + self.exclude_dirs.append(path) + def generate(self): fp_hardware = "no" fp_abi = "soft" core = self.toolchain.target.core if core == "Cortex-M4F" or core == "Cortex-M7F": fp_hardware = "fpv4-sp-d16" - fp_abi = "soft-fp" + fp_abi = "softfp" elif core == "Cortex-M7FD": fp_hardware = "fpv5-d16" - fp_abi = "soft-fp" - + fp_abi = "softfp" + + self.resources.win_to_unix() + libraries = [] for lib in self.resources.libraries: l, _ = splitext(basename(lib)) libraries.append(l[3:]) + self.include_path = [self.filter_dot(s) for s in self.resources.inc_dirs] + print 'Include folders: {0}'.format(len(self.include_path)) + #for dir in self.include_path: + # print "%s" % dir + + self.exclude_dirs = [] + self.build_excludelist() + + print 'Exclude folders: {0}'.format(len(self.exclude_dirs)) + #for dir in self.exclude_dirs: + # print "%s" % dir + + self.exclude_dirs = '|'.join(self.exclude_dirs) + + self.ld_script = self.filter_dot(self.resources.linker_script) + #print 'Linker script: {0}'.format(self.ld_script) + + self.lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] + + self.symbols = [s.replace('"', '"') for s in self.toolchain.get_symbols()] + #print "%s" % self.symbols + ctx = { 'name': self.project_name, - 'include_paths': self.resources.inc_dirs, - 'linker_script': self.resources.linker_script, - 'library_paths': self.resources.lib_dirs, + 'include_paths': self.include_path, + 'exclude_paths': self.exclude_dirs, + 'linker_script': self.ld_script, + 'library_paths': self.lib_dirs, 'object_files': self.resources.objects, 'libraries': libraries, - 'symbols': self.toolchain.get_symbols(), + 'symbols': self.symbols, 'board_name': self.BOARDS[self.target.upper()]['name'], 'mcu_name': self.BOARDS[self.target.upper()]['mcuId'], + 'c_include_uid': self.__generate_uid(), + 'cpp_include_uid': self.__generate_uid(), 'debug_config_uid': self.__generate_uid(), 'debug_tool_compiler_uid': self.__generate_uid(), 'debug_tool_compiler_input_uid': self.__generate_uid(), diff --git a/tools/export/sw4stm32/cproject_common.tmpl b/tools/export/sw4stm32/cproject_common.tmpl index 94f1062f1f..d885b6fbdc 100644 --- a/tools/export/sw4stm32/cproject_common.tmpl +++ b/tools/export/sw4stm32/cproject_common.tmpl @@ -24,7 +24,7 @@ - + @@ -53,6 +56,9 @@ {% endfor %} + @@ -96,6 +102,9 @@ + + + @@ -193,6 +202,9 @@ + + + From 224ada2a51ca0c7f15018e58b8d7633fd2d6f545 Mon Sep 17 00:00:00 2001 From: Jarno Komula Date: Wed, 19 Jul 2017 15:30:12 +0300 Subject: [PATCH 40/60] Review corrections. --- tools/export/sw4stm32/__init__.py | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index e50d0e763c..85016f7623 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -14,8 +14,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ -import os +from os import walk, sep from os.path import splitext, basename, join, dirname from random import randint from tools.utils import mkdir @@ -82,33 +82,30 @@ class Sw4STM32(Exporter): return "%0.9u" % randint(0, 999999999) @staticmethod - def filter_dot(str): + def filter_dot(path): """ This function removes ./ from str. str must be converted with win_to_unix() before using this function. """ - if str == None: + if path is None: return None - if str[:2] == './': - return str[2:] - return str + if path[:2] == './': + return path[2:] + return path def build_excludelist(self): self.source_folders = [self.filter_dot(s) for s in set(dirname( src) for src in self.resources.c_sources + self.resources.cpp_sources + self.resources.s_sources)] if '.' in self.source_folders: self.source_folders.remove('.') - #print source_folders top_folders = [f for f in set(s.split('/')[0] for s in self.source_folders)] - #print top_folders for top_folder in top_folders: - # - for root, dirs, files in os.walk(top_folder, topdown=True): + for root, dirs, files in walk(top_folder, topdown=True): # Paths returned by os.walk() must be split with os.dep # to accomodate Windows weirdness. - parts = root.split(os.sep) + parts = root.split(sep) self.remove_unused('/'.join(parts)) def remove_unused(self, path): @@ -144,26 +141,20 @@ class Sw4STM32(Exporter): libraries.append(l[3:]) self.include_path = [self.filter_dot(s) for s in self.resources.inc_dirs] - print 'Include folders: {0}'.format(len(self.include_path)) - #for dir in self.include_path: - # print "%s" % dir + print 'Include folders: %d' % len(self.include_path) self.exclude_dirs = [] self.build_excludelist() - print 'Exclude folders: {0}'.format(len(self.exclude_dirs)) - #for dir in self.exclude_dirs: - # print "%s" % dir + print 'Exclude folders: %d' % len(self.exclude_dirs) self.exclude_dirs = '|'.join(self.exclude_dirs) self.ld_script = self.filter_dot(self.resources.linker_script) - #print 'Linker script: {0}'.format(self.ld_script) self.lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] self.symbols = [s.replace('"', '"') for s in self.toolchain.get_symbols()] - #print "%s" % self.symbols ctx = { 'name': self.project_name, From c2eafc9d38a90ee85369654a04738c99db7de777 Mon Sep 17 00:00:00 2001 From: Jarno Komula Date: Wed, 19 Jul 2017 16:46:58 +0300 Subject: [PATCH 41/60] Better readability. --- tools/export/sw4stm32/__init__.py | 324 ++++++++++++++++++++++++------ 1 file changed, 260 insertions(+), 64 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index 85016f7623..b0926faf24 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -23,62 +23,243 @@ from tools.export.exporters import Exporter class Sw4STM32(Exporter): + """ + Sw4STM32 class + """ NAME = 'Sw4STM32' TOOLCHAIN = 'GCC_ARM' BOARDS = { - 'B96B_F446VE': {'name': 'B96B-F446VE', 'mcuId': 'STM32F446VETx'}, - 'DISCO_F051R8': {'name': 'STM32F0DISCOVERY', 'mcuId': 'STM32F051R8Tx'}, - 'DISCO_F303VC': {'name': 'STM32F3DISCOVERY', 'mcuId': 'STM32F303VCTx'}, - 'DISCO_F334C8': {'name': 'STM32F3348DISCOVERY', 'mcuId': 'STM32F334C8Tx'}, - 'DISCO_F401VC': {'name': 'STM32F401C-DISCO', 'mcuId': 'STM32F401VCTx'}, - 'DISCO_F407VG': {'name': 'STM32F4DISCOVERY', 'mcuId': 'STM32F407VGTx'}, - 'DISCO_F413ZH': {'name': 'DISCO_F413', 'mcuId': 'STM32F413ZHTx'}, - 'DISCO_F429ZI': {'name': 'STM32F429I-DISCO', 'mcuId': 'STM32F429ZITx'}, - 'DISCO_F469NI': {'name': 'DISCO-F469NI', 'mcuId': 'STM32F469NIHx'}, - 'DISCO_F746NG': {'name': 'STM32F746G-DISCO', 'mcuId': 'STM32F746NGHx'}, - 'DISCO_F769NI': {'name': 'DISCO-F769NI', 'mcuId': 'STM32F769NIHx'}, - 'DISCO_L053C8': {'name': 'STM32L0538DISCOVERY', 'mcuId': 'STM32L053C8Tx'}, - 'DISCO_L072CZ_LRWAN1': {'name': 'DISCO-L072CZ-LRWAN1', 'mcuId': 'STM32L072CZTx'}, - 'DISCO_L475VG_IOT01A': {'name': 'STM32L475G-DISCO', 'mcuId': 'STM32L475VGTx'}, - 'DISCO_L476VG': {'name': 'STM32L476G-DISCO', 'mcuId': 'STM32L476VGTx'}, - 'NUCLEO_F030R8': {'name': 'NUCLEO-F030R8', 'mcuId': 'STM32F030R8Tx'}, - 'NUCLEO_F031K6': {'name': 'NUCLEO-F031K6', 'mcuId': 'STM32F031K6Tx'}, - 'NUCLEO_F042K6': {'name': 'NUCLEO-F042K6', 'mcuId': 'STM32F042K6Tx'}, - 'NUCLEO_F070RB': {'name': 'NUCLEO-F070RB', 'mcuId': 'STM32F070RBTx'}, - 'NUCLEO_F072RB': {'name': 'NUCLEO-F072RB', 'mcuId': 'STM32F072RBTx'}, - 'NUCLEO_F091RC': {'name': 'NUCLEO-F091RC', 'mcuId': 'STM32F091RCTx'}, - 'NUCLEO_F103RB': {'name': 'NUCLEO-F103RB', 'mcuId': 'STM32F103RBTx'}, - 'NUCLEO_F207ZG': {'name': 'NUCLEO-F207ZG', 'mcuId': 'STM32F207ZGTx'}, - 'NUCLEO_F302R8': {'name': 'NUCLEO-F302R8', 'mcuId': 'STM32F302R8Tx'}, - 'NUCLEO_F303K8': {'name': 'NUCLEO-F303K8', 'mcuId': 'STM32F303K8Tx'}, - 'NUCLEO_F303RE': {'name': 'NUCLEO-F303RE', 'mcuId': 'STM32F303RETx'}, - 'NUCLEO_F303ZE': {'name': 'NUCLEO-F303ZE', 'mcuId': 'STM32F303ZETx'}, - 'NUCLEO_F334R8': {'name': 'NUCLEO-F334R8', 'mcuId': 'STM32F334R8Tx'}, - 'NUCLEO_F401RE': {'name': 'NUCLEO-F401RE', 'mcuId': 'STM32F401RETx'}, - 'NUCLEO_F410RB': {'name': 'NUCLEO-F410RB', 'mcuId': 'STM32F410RBTx'}, - 'NUCLEO_F411RE': {'name': 'NUCLEO-F411RE', 'mcuId': 'STM32F411RETx'}, - 'NUCLEO_F429ZI': {'name': 'NUCLEO-F429ZI', 'mcuId': 'STM32F429ZITx'}, - 'NUCLEO_F446RE': {'name': 'NUCLEO-F446RE', 'mcuId': 'STM32F446RETx'}, - 'NUCLEO_F446ZE': {'name': 'NUCLEO-F446ZE', 'mcuId': 'STM32F446ZETx'}, - 'NUCLEO_F746ZG': {'name': 'NUCLEO-F746ZG', 'mcuId': 'STM32F746ZGTx'}, - 'NUCLEO_F767ZI': {'name': 'NUCLEO-F767ZI', 'mcuId': 'STM32F767ZITx'}, - 'NUCLEO_L011K4': {'name': 'NUCLEO-L011K4', 'mcuId': 'STM32L011K4Tx'}, - 'NUCLEO_L031K6': {'name': 'NUCLEO-L031K6', 'mcuId': 'STM32L031K6Tx'}, - 'NUCLEO_L053R8': {'name': 'NUCLEO-L053R8', 'mcuId': 'STM32L053R8Tx'}, - 'NUCLEO_L073RZ': {'name': 'NUCLEO-L073RZ', 'mcuId': 'STM32L073RZTx'}, - 'NUCLEO_L152RE': {'name': 'NUCLEO-L152RE', 'mcuId': 'STM32L152RETx'}, - 'NUCLEO_L432KC': {'name': 'NUCLEO-L432KC', 'mcuId': 'STM32L432KCUx'}, - 'NUCLEO_L476RG': {'name': 'NUCLEO-L476RG', 'mcuId': 'STM32L476RGTx'}, + 'B96B_F446VE': + { + 'name': 'B96B-F446VE', + 'mcuId': 'STM32F446VETx' + }, + 'DISCO_F051R8': + { + 'name': 'STM32F0DISCOVERY', + 'mcuId': 'STM32F051R8Tx' + }, + 'DISCO_F303VC': + { + 'name': 'STM32F3DISCOVERY', + 'mcuId': 'STM32F303VCTx' + }, + 'DISCO_F334C8': + { + 'name': 'STM32F3348DISCOVERY', + 'mcuId': 'STM32F334C8Tx' + }, + 'DISCO_F401VC': + { + 'name': 'STM32F401C-DISCO', + 'mcuId': 'STM32F401VCTx' + }, + 'DISCO_F407VG': + { + 'name': 'STM32F4DISCOVERY', + 'mcuId': 'STM32F407VGTx' + }, + 'DISCO_F413ZH': + { + 'name': 'DISCO_F413', + 'mcuId': 'STM32F413ZHTx' + }, + 'DISCO_F429ZI': + { + 'name': 'STM32F429I-DISCO', + 'mcuId': 'STM32F429ZITx' + }, + 'DISCO_F469NI': + { + 'name': 'DISCO-F469NI', + 'mcuId': 'STM32F469NIHx' + }, + 'DISCO_F746NG': + { + 'name': 'STM32F746G-DISCO', + 'mcuId': 'STM32F746NGHx' + }, + 'DISCO_F769NI': + { + 'name': 'DISCO-F769NI', + 'mcuId': 'STM32F769NIHx' + }, + 'DISCO_L053C8': + { + 'name': 'STM32L0538DISCOVERY', + 'mcuId': 'STM32L053C8Tx' + }, + 'DISCO_L072CZ_LRWAN1': + { + 'name': 'DISCO-L072CZ-LRWAN1', + 'mcuId': 'STM32L072CZTx' + }, + 'DISCO_L475VG_IOT01A': + { + 'name': 'STM32L475G-DISCO', + 'mcuId': 'STM32L475VGTx' + }, + 'DISCO_L476VG': + { + 'name': 'STM32L476G-DISCO', + 'mcuId': 'STM32L476VGTx' + }, + 'NUCLEO_F030R8': + { + 'name': 'NUCLEO-F030R8', + 'mcuId': 'STM32F030R8Tx' + }, + 'NUCLEO_F031K6': + { + 'name': 'NUCLEO-F031K6', + 'mcuId': 'STM32F031K6Tx' + }, + 'NUCLEO_F042K6': + { + 'name': 'NUCLEO-F042K6', + 'mcuId': 'STM32F042K6Tx' + }, + 'NUCLEO_F070RB': + { + 'name': 'NUCLEO-F070RB', + 'mcuId': 'STM32F070RBTx' + }, + 'NUCLEO_F072RB': + { + 'name': 'NUCLEO-F072RB', + 'mcuId': 'STM32F072RBTx' + }, + 'NUCLEO_F091RC': + { + 'name': 'NUCLEO-F091RC', + 'mcuId': 'STM32F091RCTx' + }, + 'NUCLEO_F103RB': + { + 'name': 'NUCLEO-F103RB', + 'mcuId': 'STM32F103RBTx' + }, + 'NUCLEO_F207ZG': + { + 'name': 'NUCLEO-F207ZG', + 'mcuId': 'STM32F207ZGTx' + }, + 'NUCLEO_F302R8': + { + 'name': 'NUCLEO-F302R8', + 'mcuId': 'STM32F302R8Tx' + }, + 'NUCLEO_F303K8': + { + 'name': 'NUCLEO-F303K8', + 'mcuId': 'STM32F303K8Tx' + }, + 'NUCLEO_F303RE': + { + 'name': 'NUCLEO-F303RE', + 'mcuId': 'STM32F303RETx' + }, + 'NUCLEO_F303ZE': + { + 'name': 'NUCLEO-F303ZE', + 'mcuId': 'STM32F303ZETx' + }, + 'NUCLEO_F334R8': + { + 'name': 'NUCLEO-F334R8', + 'mcuId': 'STM32F334R8Tx' + }, + 'NUCLEO_F401RE': + { + 'name': 'NUCLEO-F401RE', + 'mcuId': 'STM32F401RETx' + }, + 'NUCLEO_F410RB': + { + 'name': 'NUCLEO-F410RB', + 'mcuId': 'STM32F410RBTx' + }, + 'NUCLEO_F411RE': + { + 'name': 'NUCLEO-F411RE', + 'mcuId': 'STM32F411RETx' + }, + 'NUCLEO_F429ZI': + { + 'name': 'NUCLEO-F429ZI', + 'mcuId': 'STM32F429ZITx' + }, + 'NUCLEO_F446RE': + { + 'name': 'NUCLEO-F446RE', + 'mcuId': 'STM32F446RETx' + }, + 'NUCLEO_F446ZE': + { + 'name': 'NUCLEO-F446ZE', + 'mcuId': 'STM32F446ZETx' + }, + 'NUCLEO_F746ZG': + { + 'name': 'NUCLEO-F746ZG', + 'mcuId': 'STM32F746ZGTx' + }, + 'NUCLEO_F767ZI': + { + 'name': 'NUCLEO-F767ZI', + 'mcuId': 'STM32F767ZITx' + }, + 'NUCLEO_L011K4': + { + 'name': 'NUCLEO-L011K4', + 'mcuId': 'STM32L011K4Tx' + }, + 'NUCLEO_L031K6': + { + 'name': 'NUCLEO-L031K6', + 'mcuId': 'STM32L031K6Tx' + }, + 'NUCLEO_L053R8': + { + 'name': 'NUCLEO-L053R8', + 'mcuId': 'STM32L053R8Tx' + }, + 'NUCLEO_L073RZ': + { + 'name': 'NUCLEO-L073RZ', + 'mcuId': 'STM32L073RZTx' + }, + 'NUCLEO_L152RE': + { + 'name': 'NUCLEO-L152RE', + 'mcuId': 'STM32L152RETx' + }, + 'NUCLEO_L432KC': + { + 'name': 'NUCLEO-L432KC', + 'mcuId': 'STM32L432KCUx' + }, + 'NUCLEO_L476RG': + { + 'name': 'NUCLEO-L476RG', + 'mcuId': 'STM32L476RGTx' + }, } TARGETS = BOARDS.keys() - def __gen_dir(self, dirname): - settings = join(self.export_dir, dirname) + def __gen_dir(self, dir_name): + """ + Method that created directory + """ + settings = join(self.export_dir, dir_name) mkdir(settings) def __generate_uid(self): + """ + Method to create random int + """ return "%0.9u" % randint(0, 999999999) @staticmethod @@ -94,12 +275,19 @@ class Sw4STM32(Exporter): return path def build_excludelist(self): - self.source_folders = [self.filter_dot(s) for s in set(dirname( - src) for src in self.resources.c_sources + self.resources.cpp_sources + self.resources.s_sources)] + """ + This method creates list for excluded directories. + """ + self.source_folders = [self.filter_dot(s) + for s in set(dirname(src) for src in + self.resources.c_sources + + self.resources.cpp_sources + + self.resources.s_sources)] if '.' in self.source_folders: self.source_folders.remove('.') - top_folders = [f for f in set(s.split('/')[0] for s in self.source_folders)] + top_folders = [f for f in set(s.split('/')[0] + for s in self.source_folders)] for top_folder in top_folders: for root, dirs, files in walk(top_folder, topdown=True): @@ -107,19 +295,24 @@ class Sw4STM32(Exporter): # to accomodate Windows weirdness. parts = root.split(sep) self.remove_unused('/'.join(parts)) - + def remove_unused(self, path): - found = False + """ + Method for checking if path is needed. + Method adds path to excluded list if not needed + and is not subdirectory of already excluded directory + """ + found = False for used in self.include_path: if path == used: found = True - needToAdd = True + needtoadd = True if not found: - for dir in self.exclude_dirs: + for directory in self.exclude_dirs: # Do not exclude subfolders from excluded folder - if path.find(dir+'/') != -1: - needToAdd = False - if needToAdd: + if path.find(directory+'/') != -1: + needtoadd = False + if needtoadd: self.exclude_dirs.append(path) def generate(self): @@ -137,10 +330,11 @@ class Sw4STM32(Exporter): libraries = [] for lib in self.resources.libraries: - l, _ = splitext(basename(lib)) - libraries.append(l[3:]) + library, _ = splitext(basename(lib)) + libraries.append(library[3:]) - self.include_path = [self.filter_dot(s) for s in self.resources.inc_dirs] + self.include_path = [self.filter_dot(s) + for s in self.resources.inc_dirs] print 'Include folders: %d' % len(self.include_path) self.exclude_dirs = [] @@ -150,21 +344,23 @@ class Sw4STM32(Exporter): self.exclude_dirs = '|'.join(self.exclude_dirs) - self.ld_script = self.filter_dot(self.resources.linker_script) + ld_script = self.filter_dot(self.resources.linker_script) - self.lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] + # self.lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] + lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] - self.symbols = [s.replace('"', '"') for s in self.toolchain.get_symbols()] + symbols = [s.replace('"', '"') + for s in self.toolchain.get_symbols()] ctx = { 'name': self.project_name, 'include_paths': self.include_path, 'exclude_paths': self.exclude_dirs, - 'linker_script': self.ld_script, - 'library_paths': self.lib_dirs, + 'linker_script': ld_script, + 'library_paths': lib_dirs, 'object_files': self.resources.objects, 'libraries': libraries, - 'symbols': self.symbols, + 'symbols': symbols, 'board_name': self.BOARDS[self.target.upper()]['name'], 'mcu_name': self.BOARDS[self.target.upper()]['mcuId'], 'c_include_uid': self.__generate_uid(), From 3408e257144ce5c485ce3723d856ce34a39b9d29 Mon Sep 17 00:00:00 2001 From: Jarno Komula Date: Thu, 20 Jul 2017 13:10:06 +0300 Subject: [PATCH 42/60] Review changes + including config header from toolchain.get_config_header() instead of hardcoding it to project file. --- tools/export/sw4stm32/__init__.py | 27 ++++++++++----------- tools/export/sw4stm32/cproject_common.tmpl | 28 ++++++++++++++++------ 2 files changed, 34 insertions(+), 21 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index b0926faf24..05fe8bef98 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -15,8 +15,10 @@ See the License for the specific language governing permissions and limitations under the License. """ +import copy + from os import walk, sep -from os.path import splitext, basename, join, dirname +from os.path import splitext, basename, join, dirname, relpath from random import randint from tools.utils import mkdir from tools.export.exporters import Exporter @@ -251,7 +253,7 @@ class Sw4STM32(Exporter): def __gen_dir(self, dir_name): """ - Method that created directory + Method that creates directory """ settings = join(self.export_dir, dir_name) mkdir(settings) @@ -268,9 +270,9 @@ class Sw4STM32(Exporter): This function removes ./ from str. str must be converted with win_to_unix() before using this function. """ - if path is None: - return None - if path[:2] == './': + if not path: + return path + if path.startswith('./'): return path[2:] return path @@ -302,15 +304,12 @@ class Sw4STM32(Exporter): Method adds path to excluded list if not needed and is not subdirectory of already excluded directory """ - found = False - for used in self.include_path: - if path == used: - found = True + found = path in self.include_path needtoadd = True if not found: for directory in self.exclude_dirs: - # Do not exclude subfolders from excluded folder - if path.find(directory+'/') != -1: + # Do not exclude subfolders from excluded folder + if directory+'/' in path: needtoadd = False if needtoadd: self.exclude_dirs.append(path) @@ -326,6 +325,8 @@ class Sw4STM32(Exporter): fp_hardware = "fpv5-d16" fp_abi = "softfp" + config_header = self.filter_dot(self.toolchain.get_config_header()) + self.resources.win_to_unix() libraries = [] @@ -346,7 +347,6 @@ class Sw4STM32(Exporter): ld_script = self.filter_dot(self.resources.linker_script) - # self.lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] symbols = [s.replace('"', '"') @@ -355,6 +355,7 @@ class Sw4STM32(Exporter): ctx = { 'name': self.project_name, 'include_paths': self.include_path, + 'config_header': config_header, 'exclude_paths': self.exclude_dirs, 'linker_script': ld_script, 'library_paths': lib_dirs, @@ -363,8 +364,6 @@ class Sw4STM32(Exporter): 'symbols': symbols, 'board_name': self.BOARDS[self.target.upper()]['name'], 'mcu_name': self.BOARDS[self.target.upper()]['mcuId'], - 'c_include_uid': self.__generate_uid(), - 'cpp_include_uid': self.__generate_uid(), 'debug_config_uid': self.__generate_uid(), 'debug_tool_compiler_uid': self.__generate_uid(), 'debug_tool_compiler_input_uid': self.__generate_uid(), diff --git a/tools/export/sw4stm32/cproject_common.tmpl b/tools/export/sw4stm32/cproject_common.tmpl index d885b6fbdc..65528cdd0d 100644 --- a/tools/export/sw4stm32/cproject_common.tmpl +++ b/tools/export/sw4stm32/cproject_common.tmpl @@ -36,9 +36,11 @@ {% endfor %} - - + {% if config_header %} + + {% endif %} @@ -103,7 +107,7 @@ - + @@ -142,6 +146,11 @@ {% endfor %} + {% if config_header %} + + {% endif %} @@ -158,6 +167,11 @@ {% endfor %} + {% if config_header %} + + {% endif %} @@ -203,7 +217,7 @@ - + From 65c4a2204dbee9c66d07c7eda06b0faceddd47f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Wed, 16 Aug 2017 09:34:33 +0300 Subject: [PATCH 43/60] export: Fix sw4stm32 linker script problem Added makefile.target, and rule for linker script pre-compilation. --- tools/export/sw4stm32/__init__.py | 222 +++++++++++--------- tools/export/sw4stm32/makefile.targets.tmpl | 7 + 2 files changed, 132 insertions(+), 97 deletions(-) create mode 100644 tools/export/sw4stm32/makefile.targets.tmpl diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index 05fe8bef98..e40456350c 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -34,218 +34,218 @@ class Sw4STM32(Exporter): BOARDS = { 'B96B_F446VE': { - 'name': 'B96B-F446VE', - 'mcuId': 'STM32F446VETx' + 'name': 'B96B-F446VE', + 'mcuId': 'STM32F446VETx' }, 'DISCO_F051R8': { - 'name': 'STM32F0DISCOVERY', - 'mcuId': 'STM32F051R8Tx' + 'name': 'STM32F0DISCOVERY', + 'mcuId': 'STM32F051R8Tx' }, 'DISCO_F303VC': { - 'name': 'STM32F3DISCOVERY', - 'mcuId': 'STM32F303VCTx' + 'name': 'STM32F3DISCOVERY', + 'mcuId': 'STM32F303VCTx' }, 'DISCO_F334C8': { - 'name': 'STM32F3348DISCOVERY', - 'mcuId': 'STM32F334C8Tx' + 'name': 'STM32F3348DISCOVERY', + 'mcuId': 'STM32F334C8Tx' }, 'DISCO_F401VC': { - 'name': 'STM32F401C-DISCO', - 'mcuId': 'STM32F401VCTx' + 'name': 'STM32F401C-DISCO', + 'mcuId': 'STM32F401VCTx' }, 'DISCO_F407VG': { - 'name': 'STM32F4DISCOVERY', - 'mcuId': 'STM32F407VGTx' + 'name': 'STM32F4DISCOVERY', + 'mcuId': 'STM32F407VGTx' }, 'DISCO_F413ZH': { - 'name': 'DISCO_F413', - 'mcuId': 'STM32F413ZHTx' + 'name': 'DISCO_F413', + 'mcuId': 'STM32F413ZHTx' }, 'DISCO_F429ZI': { - 'name': 'STM32F429I-DISCO', - 'mcuId': 'STM32F429ZITx' + 'name': 'STM32F429I-DISCO', + 'mcuId': 'STM32F429ZITx' }, 'DISCO_F469NI': { - 'name': 'DISCO-F469NI', - 'mcuId': 'STM32F469NIHx' + 'name': 'DISCO-F469NI', + 'mcuId': 'STM32F469NIHx' }, 'DISCO_F746NG': { - 'name': 'STM32F746G-DISCO', - 'mcuId': 'STM32F746NGHx' + 'name': 'STM32F746G-DISCO', + 'mcuId': 'STM32F746NGHx' }, 'DISCO_F769NI': { - 'name': 'DISCO-F769NI', - 'mcuId': 'STM32F769NIHx' + 'name': 'DISCO-F769NI', + 'mcuId': 'STM32F769NIHx' }, 'DISCO_L053C8': { - 'name': 'STM32L0538DISCOVERY', - 'mcuId': 'STM32L053C8Tx' + 'name': 'STM32L0538DISCOVERY', + 'mcuId': 'STM32L053C8Tx' }, 'DISCO_L072CZ_LRWAN1': { - 'name': 'DISCO-L072CZ-LRWAN1', - 'mcuId': 'STM32L072CZTx' + 'name': 'DISCO-L072CZ-LRWAN1', + 'mcuId': 'STM32L072CZTx' }, 'DISCO_L475VG_IOT01A': { - 'name': 'STM32L475G-DISCO', - 'mcuId': 'STM32L475VGTx' + 'name': 'STM32L475G-DISCO', + 'mcuId': 'STM32L475VGTx' }, 'DISCO_L476VG': { - 'name': 'STM32L476G-DISCO', - 'mcuId': 'STM32L476VGTx' + 'name': 'STM32L476G-DISCO', + 'mcuId': 'STM32L476VGTx' }, 'NUCLEO_F030R8': { - 'name': 'NUCLEO-F030R8', - 'mcuId': 'STM32F030R8Tx' + 'name': 'NUCLEO-F030R8', + 'mcuId': 'STM32F030R8Tx' }, 'NUCLEO_F031K6': { - 'name': 'NUCLEO-F031K6', - 'mcuId': 'STM32F031K6Tx' + 'name': 'NUCLEO-F031K6', + 'mcuId': 'STM32F031K6Tx' }, 'NUCLEO_F042K6': { - 'name': 'NUCLEO-F042K6', - 'mcuId': 'STM32F042K6Tx' + 'name': 'NUCLEO-F042K6', + 'mcuId': 'STM32F042K6Tx' }, 'NUCLEO_F070RB': { - 'name': 'NUCLEO-F070RB', - 'mcuId': 'STM32F070RBTx' + 'name': 'NUCLEO-F070RB', + 'mcuId': 'STM32F070RBTx' }, 'NUCLEO_F072RB': { - 'name': 'NUCLEO-F072RB', - 'mcuId': 'STM32F072RBTx' + 'name': 'NUCLEO-F072RB', + 'mcuId': 'STM32F072RBTx' }, 'NUCLEO_F091RC': { - 'name': 'NUCLEO-F091RC', - 'mcuId': 'STM32F091RCTx' + 'name': 'NUCLEO-F091RC', + 'mcuId': 'STM32F091RCTx' }, 'NUCLEO_F103RB': { - 'name': 'NUCLEO-F103RB', - 'mcuId': 'STM32F103RBTx' + 'name': 'NUCLEO-F103RB', + 'mcuId': 'STM32F103RBTx' }, 'NUCLEO_F207ZG': { - 'name': 'NUCLEO-F207ZG', - 'mcuId': 'STM32F207ZGTx' + 'name': 'NUCLEO-F207ZG', + 'mcuId': 'STM32F207ZGTx' }, 'NUCLEO_F302R8': { - 'name': 'NUCLEO-F302R8', - 'mcuId': 'STM32F302R8Tx' + 'name': 'NUCLEO-F302R8', + 'mcuId': 'STM32F302R8Tx' }, 'NUCLEO_F303K8': { - 'name': 'NUCLEO-F303K8', - 'mcuId': 'STM32F303K8Tx' + 'name': 'NUCLEO-F303K8', + 'mcuId': 'STM32F303K8Tx' }, 'NUCLEO_F303RE': { - 'name': 'NUCLEO-F303RE', - 'mcuId': 'STM32F303RETx' + 'name': 'NUCLEO-F303RE', + 'mcuId': 'STM32F303RETx' }, 'NUCLEO_F303ZE': { - 'name': 'NUCLEO-F303ZE', - 'mcuId': 'STM32F303ZETx' + 'name': 'NUCLEO-F303ZE', + 'mcuId': 'STM32F303ZETx' }, 'NUCLEO_F334R8': { - 'name': 'NUCLEO-F334R8', - 'mcuId': 'STM32F334R8Tx' + 'name': 'NUCLEO-F334R8', + 'mcuId': 'STM32F334R8Tx' }, 'NUCLEO_F401RE': { - 'name': 'NUCLEO-F401RE', - 'mcuId': 'STM32F401RETx' + 'name': 'NUCLEO-F401RE', + 'mcuId': 'STM32F401RETx' }, 'NUCLEO_F410RB': { - 'name': 'NUCLEO-F410RB', - 'mcuId': 'STM32F410RBTx' + 'name': 'NUCLEO-F410RB', + 'mcuId': 'STM32F410RBTx' }, 'NUCLEO_F411RE': { - 'name': 'NUCLEO-F411RE', - 'mcuId': 'STM32F411RETx' + 'name': 'NUCLEO-F411RE', + 'mcuId': 'STM32F411RETx' }, 'NUCLEO_F429ZI': { - 'name': 'NUCLEO-F429ZI', - 'mcuId': 'STM32F429ZITx' + 'name': 'NUCLEO-F429ZI', + 'mcuId': 'STM32F429ZITx' }, 'NUCLEO_F446RE': { - 'name': 'NUCLEO-F446RE', - 'mcuId': 'STM32F446RETx' + 'name': 'NUCLEO-F446RE', + 'mcuId': 'STM32F446RETx' }, 'NUCLEO_F446ZE': { - 'name': 'NUCLEO-F446ZE', - 'mcuId': 'STM32F446ZETx' + 'name': 'NUCLEO-F446ZE', + 'mcuId': 'STM32F446ZETx' }, 'NUCLEO_F746ZG': { - 'name': 'NUCLEO-F746ZG', - 'mcuId': 'STM32F746ZGTx' + 'name': 'NUCLEO-F746ZG', + 'mcuId': 'STM32F746ZGTx' }, 'NUCLEO_F767ZI': { - 'name': 'NUCLEO-F767ZI', - 'mcuId': 'STM32F767ZITx' + 'name': 'NUCLEO-F767ZI', + 'mcuId': 'STM32F767ZITx' }, 'NUCLEO_L011K4': { - 'name': 'NUCLEO-L011K4', - 'mcuId': 'STM32L011K4Tx' + 'name': 'NUCLEO-L011K4', + 'mcuId': 'STM32L011K4Tx' }, 'NUCLEO_L031K6': { - 'name': 'NUCLEO-L031K6', - 'mcuId': 'STM32L031K6Tx' + 'name': 'NUCLEO-L031K6', + 'mcuId': 'STM32L031K6Tx' }, 'NUCLEO_L053R8': { - 'name': 'NUCLEO-L053R8', - 'mcuId': 'STM32L053R8Tx' + 'name': 'NUCLEO-L053R8', + 'mcuId': 'STM32L053R8Tx' }, 'NUCLEO_L073RZ': { - 'name': 'NUCLEO-L073RZ', - 'mcuId': 'STM32L073RZTx' + 'name': 'NUCLEO-L073RZ', + 'mcuId': 'STM32L073RZTx' }, 'NUCLEO_L152RE': { - 'name': 'NUCLEO-L152RE', - 'mcuId': 'STM32L152RETx' + 'name': 'NUCLEO-L152RE', + 'mcuId': 'STM32L152RETx' }, 'NUCLEO_L432KC': { - 'name': 'NUCLEO-L432KC', - 'mcuId': 'STM32L432KCUx' + 'name': 'NUCLEO-L432KC', + 'mcuId': 'STM32L432KCUx' }, 'NUCLEO_L476RG': { - 'name': 'NUCLEO-L476RG', - 'mcuId': 'STM32L476RGTx' + 'name': 'NUCLEO-L476RG', + 'mcuId': 'STM32L476RGTx' }, } @@ -281,15 +281,15 @@ class Sw4STM32(Exporter): This method creates list for excluded directories. """ self.source_folders = [self.filter_dot(s) - for s in set(dirname(src) for src in - self.resources.c_sources + - self.resources.cpp_sources + - self.resources.s_sources)] + for s in set(dirname(src) for src in + self.resources.c_sources + + self.resources.cpp_sources + + self.resources.s_sources)] if '.' in self.source_folders: self.source_folders.remove('.') top_folders = [f for f in set(s.split('/')[0] - for s in self.source_folders)] + for s in self.source_folders)] for top_folder in top_folders: for root, dirs, files in walk(top_folder, topdown=True): @@ -309,12 +309,29 @@ class Sw4STM32(Exporter): if not found: for directory in self.exclude_dirs: # Do not exclude subfolders from excluded folder - if directory+'/' in path: + if directory + '/' in path: needtoadd = False if needtoadd: self.exclude_dirs.append(path) def generate(self): + """ + Generate the .project and .cproject files. + """ + opts = {} + + if not self.resources.linker_script: + raise NotSupportedException("No linker script found.") + + print + print 'Create a System Workbench for STM32 managed project' + print 'Project name: {0}'.format(self.project_name) + print 'Target: {0}'.format(self.toolchain.target.name) + print 'Toolchain: {0}'.format(self.TOOLCHAIN) + print + + self.resources.win_to_unix() + fp_hardware = "no" fp_abi = "soft" core = self.toolchain.target.core @@ -324,6 +341,7 @@ class Sw4STM32(Exporter): elif core == "Cortex-M7FD": fp_hardware = "fpv5-d16" fp_abi = "softfp" + print 'FP hardware: ' + fp_hardware config_header = self.filter_dot(self.toolchain.get_config_header()) @@ -335,7 +353,7 @@ class Sw4STM32(Exporter): libraries.append(library[3:]) self.include_path = [self.filter_dot(s) - for s in self.resources.inc_dirs] + for s in self.resources.inc_dirs] print 'Include folders: %d' % len(self.include_path) self.exclude_dirs = [] @@ -346,18 +364,23 @@ class Sw4STM32(Exporter): self.exclude_dirs = '|'.join(self.exclude_dirs) ld_script = self.filter_dot(self.resources.linker_script) + print ('Linker script: {0}'.format(ld_script)) lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] symbols = [s.replace('"', '"') - for s in self.toolchain.get_symbols()] + for s in self.toolchain.get_symbols()] + # TODO: We need to fetch all flags from CDT + opts['ld'] = {} + opts['ld']['extra_flags'] = '' ctx = { 'name': self.project_name, 'include_paths': self.include_path, 'config_header': config_header, 'exclude_paths': self.exclude_dirs, - 'linker_script': ld_script, + 'ld_script': ld_script, + 'linker_script': 'linker-script-' + self.project_name + '.ld', 'library_paths': lib_dirs, 'object_files': self.resources.objects, 'libraries': libraries, @@ -372,10 +395,15 @@ class Sw4STM32(Exporter): 'release_tool_compiler_input_uid': self.__generate_uid(), 'uid': self.__generate_uid(), 'floating_point_hardware': fp_hardware, - 'floating_point_abi': fp_abi + 'floating_point_abi': fp_abi, + 'cpp_cmd': " ".join(self.toolchain.preproc), + 'options': opts } self.__gen_dir('.settings') - self.gen_file('sw4stm32/language_settings_commom.tmpl', ctx, '.settings/language.settings.xml') + self.gen_file('sw4stm32/language_settings_commom.tmpl', + ctx, '.settings/language.settings.xml') self.gen_file('sw4stm32/project_common.tmpl', ctx, '.project') self.gen_file('sw4stm32/cproject_common.tmpl', ctx, '.cproject') + self.gen_file('sw4stm32/makefile.targets.tmpl', ctx, + 'makefile.targets', trim_blocks=True, lstrip_blocks=True) diff --git a/tools/export/sw4stm32/makefile.targets.tmpl b/tools/export/sw4stm32/makefile.targets.tmpl new file mode 100644 index 0000000000..fa8eba821c --- /dev/null +++ b/tools/export/sw4stm32/makefile.targets.tmpl @@ -0,0 +1,7 @@ +# DO NOT REMOVE! Generated by the SW4STM32 exporter from the mbed project. + +{{linker_script}}: ../{{ld_script}} + {{cpp_cmd}} {{options.ld.extra_flags}} $< -o $@ + +{{name}}.elf: {{linker_script}} + From db376bf083a85212304b569d29d5427cc183d728 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Wed, 16 Aug 2017 16:02:30 +0300 Subject: [PATCH 44/60] export: Change linker script name SW4STM32 linker script name now contains target name. Print formatting is using new Python style. --- tools/export/sw4stm32/__init__.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index e40456350c..aa926aed2e 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -323,12 +323,10 @@ class Sw4STM32(Exporter): if not self.resources.linker_script: raise NotSupportedException("No linker script found.") - print - print 'Create a System Workbench for STM32 managed project' - print 'Project name: {0}'.format(self.project_name) - print 'Target: {0}'.format(self.toolchain.target.name) - print 'Toolchain: {0}'.format(self.TOOLCHAIN) - print + print ('\nCreate a System Workbench for STM32 managed project') + print ('Project name: {0}'.format(self.project_name)) + print ('Target: {0}'.format(self.toolchain.target.name)) + print ('Toolchain: {0}'.format(self.TOOLCHAIN) + '\n') self.resources.win_to_unix() @@ -341,7 +339,6 @@ class Sw4STM32(Exporter): elif core == "Cortex-M7FD": fp_hardware = "fpv5-d16" fp_abi = "softfp" - print 'FP hardware: ' + fp_hardware config_header = self.filter_dot(self.toolchain.get_config_header()) @@ -354,17 +351,17 @@ class Sw4STM32(Exporter): self.include_path = [self.filter_dot(s) for s in self.resources.inc_dirs] - print 'Include folders: %d' % len(self.include_path) + print ('Include folders: {0}'.format(len(self.include_path))) self.exclude_dirs = [] self.build_excludelist() - print 'Exclude folders: %d' % len(self.exclude_dirs) + print ('Exclude folders: {0}'.format(len(self.exclude_dirs))) self.exclude_dirs = '|'.join(self.exclude_dirs) ld_script = self.filter_dot(self.resources.linker_script) - print ('Linker script: {0}'.format(ld_script)) + print ('Linker script: {0}'.format(ld_script)) lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] @@ -380,7 +377,7 @@ class Sw4STM32(Exporter): 'config_header': config_header, 'exclude_paths': self.exclude_dirs, 'ld_script': ld_script, - 'linker_script': 'linker-script-' + self.project_name + '.ld', + 'linker_script': 'linker-script-' + self.toolchain.target.name + '.ld', 'library_paths': lib_dirs, 'object_files': self.resources.objects, 'libraries': libraries, From 7d2328564b6b0eec8bfaa2e741f4d14855250f65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Wed, 23 Aug 2017 16:22:09 +0300 Subject: [PATCH 45/60] export: Sw4STM32 inherits GNUARMEclipse Sw4STM32 is using methods from GNUARMEclipse class to handle flags. Flags are also passed to cproject file. --- tools/export/sw4stm32/__init__.py | 195 ++++++--- tools/export/sw4stm32/cproject_common.tmpl | 389 ++++++++++-------- .../sw4stm32/language_settings_commom.tmpl | 16 +- tools/export/sw4stm32/makefile.targets.tmpl | 8 +- 4 files changed, 376 insertions(+), 232 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index aa926aed2e..9c49b5c51b 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -1,6 +1,6 @@ """ mbed SDK -Copyright (c) 2011-2016 ARM Limited +Copyright (c) 2011-2017 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,10 +21,16 @@ from os import walk, sep from os.path import splitext, basename, join, dirname, relpath from random import randint from tools.utils import mkdir -from tools.export.exporters import Exporter +from tools.export.gnuarmeclipse import GNUARMEclipse +from tools.export.gnuarmeclipse import UID +from tools.build_api import prepare_toolchain +from sys import flags + +# Global random number generator instance. +u = UID() -class Sw4STM32(Exporter): +class Sw4STM32(GNUARMEclipse): """ Sw4STM32 class """ @@ -258,24 +264,6 @@ class Sw4STM32(Exporter): settings = join(self.export_dir, dir_name) mkdir(settings) - def __generate_uid(self): - """ - Method to create random int - """ - return "%0.9u" % randint(0, 999999999) - - @staticmethod - def filter_dot(path): - """ - This function removes ./ from str. - str must be converted with win_to_unix() before using this function. - """ - if not path: - return path - if path.startswith('./'): - return path[2:] - return path - def build_excludelist(self): """ This method creates list for excluded directories. @@ -314,11 +302,65 @@ class Sw4STM32(Exporter): if needtoadd: self.exclude_dirs.append(path) + def get_fpu_hardware(self, fpu_unit): + """ + Convert fpu unit name into hardware name. + """ + hw = '' + fpus = { + 'fpv4spd16': 'fpv4-sp-d16', + 'fpv5d16': 'fpv5-d16', + 'fpv5spd16': 'fpv5-sp-d16' + } + if fpu_unit in fpus: + hw = fpus[fpu_unit] + return hw + + def process_sw_options(self, opts, flags_in): + """ + Process System Workbench specific options. + + System Workbench for STM32 has some compile options, which are not recognized by the GNUARMEclipse exporter. + Those are handled in this method. + """ + opts['c']['preprocess'] = False + if '-E' in flags_in['c_flags']: + opts['c']['preprocess'] = True + opts['cpp']['preprocess'] = False + if '-E' in flags_in['cxx_flags']: + opts['cpp']['preprocess'] = True + opts['ld']['strip'] = False + if '-s' in flags_in['ld_flags']: + opts['ld']['strip'] = True + opts['ld']['shared'] = False + if '-shared' in flags_in['ld_flags']: + opts['ld']['shared'] = True + opts['ld']['soname'] = '' + opts['ld']['implname'] = '' + opts['ld']['defname'] = '' + for item in flags_in['ld_flags']: + if item.startswith('-Wl,-soname='): + opts['ld']['soname'] = item[len('-Wl,-soname='):] + if item.startswith('-Wl,--out-implib='): + opts['ld']['implname'] = item[len('-Wl,--out-implib='):] + if item.startswith('-Wl,--output-def='): + opts['ld']['defname'] = item[len('-Wl,--output-def='):] + opts['common']['arm.target.fpu.hardware'] = self.get_fpu_hardware( + opts['common']['arm.target.fpu.unit']) + opts['common']['debugging.codecov'] = False + if '-fprofile-arcs' in flags_in['common_flags'] and '-ftest-coverage' in flags_in['common_flags']: + opts['common']['debugging.codecov'] = True + # Passing linker options to linker with '-Wl,'-prefix. + for index in range(len(opts['ld']['flags'])): + item = opts['ld']['flags'][index] + if not item.startswith('-Wl,'): + opts['ld']['flags'][index] = '-Wl,' + item + def generate(self): """ Generate the .project and .cproject files. """ - opts = {} + options = {} if not self.resources.linker_script: raise NotSupportedException("No linker script found.") @@ -330,25 +372,24 @@ class Sw4STM32(Exporter): self.resources.win_to_unix() - fp_hardware = "no" - fp_abi = "soft" - core = self.toolchain.target.core - if core == "Cortex-M4F" or core == "Cortex-M7F": - fp_hardware = "fpv4-sp-d16" - fp_abi = "softfp" - elif core == "Cortex-M7FD": - fp_hardware = "fpv5-d16" - fp_abi = "softfp" - config_header = self.filter_dot(self.toolchain.get_config_header()) - self.resources.win_to_unix() - libraries = [] for lib in self.resources.libraries: library, _ = splitext(basename(lib)) libraries.append(library[3:]) + self.system_libraries = [ + 'stdc++', 'supc++', 'm', 'c', 'gcc', 'nosys' + ] + + profiles = self.get_all_profiles() + + self.as_defines = self.toolchain.get_symbols(True) + self.c_defines = self.toolchain.get_symbols() + self.cpp_defines = self.c_defines + print 'Symbols: {0}'.format(len(self.c_defines)) + self.include_path = [self.filter_dot(s) for s in self.resources.inc_dirs] print ('Include folders: {0}'.format(len(self.include_path))) @@ -367,9 +408,74 @@ class Sw4STM32(Exporter): symbols = [s.replace('"', '"') for s in self.toolchain.get_symbols()] - # TODO: We need to fetch all flags from CDT - opts['ld'] = {} - opts['ld']['extra_flags'] = '' + + for id in ['debug', 'release']: + opts = {} + opts['common'] = {} + opts['as'] = {} + opts['c'] = {} + opts['cpp'] = {} + opts['ld'] = {} + + opts['id'] = id + opts['name'] = opts['id'].capitalize() + + # TODO: Add prints to log or console in verbose mode. + #print ('\nBuild configuration: {0}'.format(opts['name'])) + + profile = profiles[id] + + # A small hack, do not bother with src_path again, + # pass an empty string to avoid crashing. + src_paths = [''] + toolchain = prepare_toolchain( + src_paths, "", self.toolchain.target.name, self.TOOLCHAIN, build_profile=[profile]) + + # Hack to fill in build_dir + toolchain.build_dir = self.toolchain.build_dir + + flags = self.toolchain_flags(toolchain) + + # TODO: Add prints to log or console in verbose mode. + # print 'Common flags:', ' '.join(flags['common_flags']) + # print 'C++ flags:', ' '.join(flags['cxx_flags']) + # print 'C flags:', ' '.join(flags['c_flags']) + # print 'ASM flags:', ' '.join(flags['asm_flags']) + # print 'Linker flags:', ' '.join(flags['ld_flags']) + + # Most GNU ARM Eclipse options have a parent, + # either debug or release. + if '-O0' in flags['common_flags'] or '-Og' in flags['common_flags']: + opts['parent_id'] = 'debug' + else: + opts['parent_id'] = 'release' + + self.process_options(opts, flags) + + self.process_sw_options(opts, flags) + + opts['as']['defines'] = self.as_defines + opts['c']['defines'] = self.c_defines + opts['cpp']['defines'] = self.cpp_defines + + opts['ld']['library_paths'] = [ + self.filter_dot(s) for s in self.resources.lib_dirs] + + opts['ld']['user_libraries'] = libraries + opts['ld']['system_libraries'] = self.system_libraries + opts['ld']['script'] = "linker-script-" + id + ".ld" + + # Unique IDs used in multiple places. + uid = {} + uid['config'] = u.id + uid['tool_c_compiler'] = u.id + uid['tool_c_compiler_input'] = u.id + uid['tool_cpp_compiler'] = u.id + uid['tool_cpp_compiler_input'] = u.id + + opts['uid'] = uid + + options[id] = opts ctx = { 'name': self.project_name, @@ -377,24 +483,17 @@ class Sw4STM32(Exporter): 'config_header': config_header, 'exclude_paths': self.exclude_dirs, 'ld_script': ld_script, - 'linker_script': 'linker-script-' + self.toolchain.target.name + '.ld', 'library_paths': lib_dirs, 'object_files': self.resources.objects, 'libraries': libraries, 'symbols': symbols, 'board_name': self.BOARDS[self.target.upper()]['name'], 'mcu_name': self.BOARDS[self.target.upper()]['mcuId'], - 'debug_config_uid': self.__generate_uid(), - 'debug_tool_compiler_uid': self.__generate_uid(), - 'debug_tool_compiler_input_uid': self.__generate_uid(), - 'release_config_uid': self.__generate_uid(), - 'release_tool_compiler_uid': self.__generate_uid(), - 'release_tool_compiler_input_uid': self.__generate_uid(), - 'uid': self.__generate_uid(), - 'floating_point_hardware': fp_hardware, - 'floating_point_abi': fp_abi, 'cpp_cmd': " ".join(self.toolchain.preproc), - 'options': opts + 'options': options, + # id property of 'u' will generate new random identifier every time + # when called. + 'u': u } self.__gen_dir('.settings') diff --git a/tools/export/sw4stm32/cproject_common.tmpl b/tools/export/sw4stm32/cproject_common.tmpl index 65528cdd0d..96fd518a9d 100644 --- a/tools/export/sw4stm32/cproject_common.tmpl +++ b/tools/export/sw4stm32/cproject_common.tmpl @@ -1,8 +1,10 @@ - - + {% for cfg_id in options %} + {% set opts = options[cfg_id] %} + + @@ -14,205 +16,253 @@ - - - - - - - - - - - - - - - - - - - - - - - @@ -223,18 +273,19 @@ + {% endfor %} - + - - - - + {% for cfg_key in options %} + {% set opts = options[cfg_key] %} + + {% endfor %} diff --git a/tools/export/sw4stm32/language_settings_commom.tmpl b/tools/export/sw4stm32/language_settings_commom.tmpl index d138720fd2..885c6e29cc 100644 --- a/tools/export/sw4stm32/language_settings_commom.tmpl +++ b/tools/export/sw4stm32/language_settings_commom.tmpl @@ -1,17 +1,8 @@ - - - - - - - - - - - - + {% for cfg_id in options %} + {% set opts = options[cfg_id] %} + @@ -22,4 +13,5 @@ + {% endfor %} diff --git a/tools/export/sw4stm32/makefile.targets.tmpl b/tools/export/sw4stm32/makefile.targets.tmpl index fa8eba821c..9066749498 100644 --- a/tools/export/sw4stm32/makefile.targets.tmpl +++ b/tools/export/sw4stm32/makefile.targets.tmpl @@ -1,7 +1,9 @@ # DO NOT REMOVE! Generated by the SW4STM32 exporter from the mbed project. -{{linker_script}}: ../{{ld_script}} - {{cpp_cmd}} {{options.ld.extra_flags}} $< -o $@ +{% for config, opts in options.iteritems() %} +{{opts['ld']['script']}}: ../{{ld_script}} + {{cpp_cmd}} {{opts.ld.other}} $< -o $@ -{{name}}.elf: {{linker_script}} +{{name}}-{{config}}.elf: {{opts['ld']['script']}} +{% endfor %} From deb9c1b3eabc8028789c20e082699d656e187a1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Tue, 29 Aug 2017 11:46:40 +0300 Subject: [PATCH 46/60] export: Remove dublicate methods in Sw4STM32 Removed unused methods and methods with dublicate functionality. Removed unused imports. Generating list of defines for assembler. --- tools/export/sw4stm32/__init__.py | 65 ++++++------------------------- 1 file changed, 11 insertions(+), 54 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index 9c49b5c51b..82a6be6b89 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -15,11 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. """ -import copy - -from os import walk, sep -from os.path import splitext, basename, join, dirname, relpath -from random import randint +from os.path import splitext, basename, join from tools.utils import mkdir from tools.export.gnuarmeclipse import GNUARMEclipse from tools.export.gnuarmeclipse import UID @@ -264,44 +260,6 @@ class Sw4STM32(GNUARMEclipse): settings = join(self.export_dir, dir_name) mkdir(settings) - def build_excludelist(self): - """ - This method creates list for excluded directories. - """ - self.source_folders = [self.filter_dot(s) - for s in set(dirname(src) for src in - self.resources.c_sources + - self.resources.cpp_sources + - self.resources.s_sources)] - if '.' in self.source_folders: - self.source_folders.remove('.') - - top_folders = [f for f in set(s.split('/')[0] - for s in self.source_folders)] - - for top_folder in top_folders: - for root, dirs, files in walk(top_folder, topdown=True): - # Paths returned by os.walk() must be split with os.dep - # to accomodate Windows weirdness. - parts = root.split(sep) - self.remove_unused('/'.join(parts)) - - def remove_unused(self, path): - """ - Method for checking if path is needed. - Method adds path to excluded list if not needed - and is not subdirectory of already excluded directory - """ - found = path in self.include_path - needtoadd = True - if not found: - for directory in self.exclude_dirs: - # Do not exclude subfolders from excluded folder - if directory + '/' in path: - needtoadd = False - if needtoadd: - self.exclude_dirs.append(path) - def get_fpu_hardware(self, fpu_unit): """ Convert fpu unit name into hardware name. @@ -394,21 +352,15 @@ class Sw4STM32(GNUARMEclipse): for s in self.resources.inc_dirs] print ('Include folders: {0}'.format(len(self.include_path))) - self.exclude_dirs = [] - self.build_excludelist() + self.compute_exclusions() - print ('Exclude folders: {0}'.format(len(self.exclude_dirs))) - - self.exclude_dirs = '|'.join(self.exclude_dirs) + print ('Exclude folders: {0}'.format(len(self.excluded_folders))) ld_script = self.filter_dot(self.resources.linker_script) print ('Linker script: {0}'.format(ld_script)) lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] - symbols = [s.replace('"', '"') - for s in self.toolchain.get_symbols()] - for id in ['debug', 'release']: opts = {} opts['common'] = {} @@ -454,7 +406,13 @@ class Sw4STM32(GNUARMEclipse): self.process_sw_options(opts, flags) - opts['as']['defines'] = self.as_defines + if opts['as']['usepreprocessor']: + opts['as']['other'] += ' -x assembler-with-cpp' + for as_def in self.as_defines: + if '=' in as_def: + opts['as']['other'] += ' -Wa,--defsym ' + as_def + else: + opts['as']['other'] += ' -Wa,--defsym ' + as_def + '=1' opts['c']['defines'] = self.c_defines opts['cpp']['defines'] = self.cpp_defines @@ -481,12 +439,11 @@ class Sw4STM32(GNUARMEclipse): 'name': self.project_name, 'include_paths': self.include_path, 'config_header': config_header, - 'exclude_paths': self.exclude_dirs, + 'exclude_paths': '|'.join(self.excluded_folders), 'ld_script': ld_script, 'library_paths': lib_dirs, 'object_files': self.resources.objects, 'libraries': libraries, - 'symbols': symbols, 'board_name': self.BOARDS[self.target.upper()]['name'], 'mcu_name': self.BOARDS[self.target.upper()]['mcuId'], 'cpp_cmd': " ".join(self.toolchain.preproc), From d9b978f3f561c772bdb0448029365314e2a8104a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Tue, 29 Aug 2017 11:53:28 +0300 Subject: [PATCH 47/60] export: Invalid linker script path in Sw4STM32 Fixed invalid linker script path in project file. Using 'defines' instead of 'symbols' in compiler options. --- tools/export/sw4stm32/cproject_common.tmpl | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tools/export/sw4stm32/cproject_common.tmpl b/tools/export/sw4stm32/cproject_common.tmpl index 96fd518a9d..3412e5e53e 100644 --- a/tools/export/sw4stm32/cproject_common.tmpl +++ b/tools/export/sw4stm32/cproject_common.tmpl @@ -43,7 +43,7 @@ {% endfor %} @@ -125,7 +125,7 @@ {% endfor %} @@ -192,7 +192,7 @@ - + diff --git a/tools/export/sw4stm32/makefile.targets.tmpl b/tools/export/sw4stm32/makefile.targets.tmpl index 9066749498..d6ff49ac43 100644 --- a/tools/export/sw4stm32/makefile.targets.tmpl +++ b/tools/export/sw4stm32/makefile.targets.tmpl @@ -1,5 +1,10 @@ # DO NOT REMOVE! Generated by the SW4STM32 exporter from the mbed project. +ldclean: +{% for config, opts in options.iteritems() %} + $(RM) {{opts['ld']['script']}} +{% endfor %} + {% for config, opts in options.iteritems() %} {{opts['ld']['script']}}: ../{{ld_script}} {{cpp_cmd}} {{opts.ld.other}} $< -o $@ From 6e6919c3cdbdf7d546fddb5cfc195fd7e09ff7f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Wed, 6 Sep 2017 12:41:11 +0300 Subject: [PATCH 50/60] export: Fix Windows problems with Sw4STM32 Quoting linker preprocessor command, if path contains parentheses. Using relative path to shorten list of included directories. Using Eclipse variables to get path to preprocessor. --- tools/export/sw4stm32/__init__.py | 29 ++++++++++++++------- tools/export/sw4stm32/cproject_common.tmpl | 12 ++++----- tools/export/sw4stm32/makefile.targets.tmpl | 6 ++++- 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/tools/export/sw4stm32/__init__.py b/tools/export/sw4stm32/__init__.py index 9138b99042..da7c8cca35 100644 --- a/tools/export/sw4stm32/__init__.py +++ b/tools/export/sw4stm32/__init__.py @@ -313,6 +313,12 @@ class Sw4STM32(GNUARMEclipse): item = opts['ld']['flags'][index] if not item.startswith('-Wl,'): opts['ld']['flags'][index] = '-Wl,' + item + # Assembler options + for as_def in self.as_defines: + if '=' in as_def: + opts['as']['other'] += ' --defsym ' + as_def + else: + opts['as']['other'] += ' --defsym ' + as_def + '=1' def generate(self): """ @@ -349,8 +355,9 @@ class Sw4STM32(GNUARMEclipse): self.cpp_defines = self.c_defines print 'Symbols: {0}'.format(len(self.c_defines)) - self.include_path = [self.filter_dot(s) - for s in self.resources.inc_dirs] + self.include_path = [] + for s in self.resources.inc_dirs: + self.include_path.append("../" + self.filter_dot(s)) print ('Include folders: {0}'.format(len(self.include_path))) self.compute_exclusions() @@ -362,6 +369,15 @@ class Sw4STM32(GNUARMEclipse): lib_dirs = [self.filter_dot(s) for s in self.resources.lib_dirs] + preproc_cmd = "" + # Hack for Windows. Build fails if command contains parentheses. + if ('(' in self.toolchain.preproc[0] or ')' in self.toolchain.preproc[0]) and self.toolchain.preproc[0][0] != "'": + preproc_cmd = '"' + \ + self.toolchain.preproc[0] + '"' + " " + \ + " ".join(self.toolchain.preproc[1:]) + else: + preproc_cmd = " ".join(self.toolchain.preproc) + for id in ['debug', 'release']: opts = {} opts['common'] = {} @@ -407,13 +423,6 @@ class Sw4STM32(GNUARMEclipse): self.process_sw_options(opts, flags) - if opts['as']['usepreprocessor']: - opts['as']['other'] += ' -x assembler-with-cpp' - for as_def in self.as_defines: - if '=' in as_def: - opts['as']['other'] += ' -Wa,--defsym ' + as_def - else: - opts['as']['other'] += ' -Wa,--defsym ' + as_def + '=1' opts['c']['defines'] = self.c_defines opts['cpp']['defines'] = self.cpp_defines @@ -447,7 +456,7 @@ class Sw4STM32(GNUARMEclipse): 'libraries': libraries, 'board_name': self.BOARDS[self.target.upper()]['name'], 'mcu_name': self.BOARDS[self.target.upper()]['mcuId'], - 'cpp_cmd': " ".join(self.toolchain.preproc), + 'cpp_cmd': preproc_cmd, 'options': options, # id property of 'u' will generate new random identifier every time # when called. diff --git a/tools/export/sw4stm32/cproject_common.tmpl b/tools/export/sw4stm32/cproject_common.tmpl index cc6c69542f..f6e5d00074 100644 --- a/tools/export/sw4stm32/cproject_common.tmpl +++ b/tools/export/sw4stm32/cproject_common.tmpl @@ -16,7 +16,7 @@ - + - + @@ -289,6 +289,9 @@ + + + {% endfor %} From b45a5636f2205d08395ba37cddbcc919847fd596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Heikkil=C3=A4?= Date: Fri, 8 Sep 2017 14:27:18 +0300 Subject: [PATCH 53/60] export: Fix invalid id's in Sw4STM32 project files --- tools/export/sw4stm32/cproject_common.tmpl | 23 +++++++++++-------- .../sw4stm32/language_settings_commom.tmpl | 5 ++-- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/tools/export/sw4stm32/cproject_common.tmpl b/tools/export/sw4stm32/cproject_common.tmpl index e2a7369064..2abb533686 100644 --- a/tools/export/sw4stm32/cproject_common.tmpl +++ b/tools/export/sw4stm32/cproject_common.tmpl @@ -21,17 +21,17 @@